问:
How to run Spark application assembled with Spark 2.1 on cluster with Spark 1.6?
I've been told that I could build a Spark application with one version of Spark and, as long as I use sbt assembly to build that, than I can run it with spark-submit on any spark cluster.

So, I've build my simple application with Spark 2.1.1. You can see my build.sbt file below. Than I'm starting this on my cluster with:

```<code>cd spark-1.6.0-bin-hadoop2.6/bin/
spark-submit --class  App --master local[*] /home/oracle/spark_test/db-synchronizer.jar
</code>```

So as you see I'm executing it with spark 1.6.0.

and I'm getting error:

```<code>17/06/08 06:59:20 ERROR ActorSystemImpl: Uncaught fatal error from thread [sparkDriver-akka.actor.default-dispatcher-4] shutting down ActorSystem [sparkDriver]
java.lang.NoSuchMethodError: org.apache.spark.SparkConf.getTimeAsMs(Ljava/lang/String;Ljava/lang/String;)J
        at org.apache.spark.streaming.kafka010.KafkaRDD.<init>(KafkaRDD.scala:70)
        at org.apache.spark.streaming.kafka010.DirectKafkaInputDStream.compute(DirectKafkaInputDStream.scala:219)
        at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1$$anonfun$1.apply(DStream.scala:300)
        at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1$$anonfun$1.apply(DStream.scala:300)
        at scala.util.DynamicVariable.withValue(DynamicVariable.scala:57)
        at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1.apply(DStream.scala:299)
        at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1.apply(DStream.scala:287)
        at scala.Option.orElse(Option.scala:257)
        at org.apache.spark.streaming.dstream.DStream.getOrCompute(DStream.scala:284)
        at org.apache.spark.streaming.dstream.ForEachDStream.generateJob(ForEachDStream.scala:38)
        at org.apache.spark.streaming.DStreamGraph$$anonfun$1.apply(DStreamGraph.scala:116)
        at org.apache.spark.streaming.DStreamGraph$$anonfun$1.apply(DStreamGraph.scala:116)
        at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:251)
        at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:251)
        at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
        at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47)
        at scala.collection.TraversableLike$class.flatMap(TraversableLike.scala:251)
        at scala.collection.AbstractTraversable.flatMap(Traversable.scala:105)
        at org.apache.spark.streaming.DStreamGraph.generateJobs(DStreamGraph.scala:116)
        at org.apache.spark.streaming.scheduler.JobGenerator$$anonfun$2.apply(JobGenerator.scala:243)
        at org.apache.spark.streaming.scheduler.JobGenerator$$anonfun$2.apply(JobGenerator.scala:241)
        at scala.util.Try$.apply(Try.scala:161)
        at org.apache.spark.streaming.scheduler.JobGenerator.generateJobs(JobGenerator.scala:241)
        at org.apache.spark.streaming.scheduler.JobGenerator.org$apache$spark$streaming$scheduler$JobGenerator$$processEvent(JobGenerator.scala:177)
        at org.apache.spark.streaming.scheduler.JobGenerator$$anonfun$start$1$$anon$1$$anonfun$receive$1.applyOrElse(JobGenerator.scala:86)
        at akka.actor.ActorCell.receiveMessage(ActorCell.scala:498)
        at akka.actor.ActorCell.invoke(ActorCell.scala:456)
        at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:237)
        at akka.dispatch.Mailbox.run(Mailbox.scala:219)
        at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:386)
        at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
        at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
        at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
        at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
17/06/08 06:59:20 WARN AkkaUtils: Error sending message [message = Heartbeat(<driver>,[Lscala.Tuple2;@ac5b61d,BlockManagerId(<driver>, localhost, 26012))] in 1 attempts
akka.pattern.AskTimeoutException: Recipient[Actor[akka://sparkDriver/user/HeartbeatReceiver#-1309342978]] had already been terminated.
        at akka.pattern.AskableActorRef$.ask$extension(AskSupport.scala:134)
        at org.apache.spark.util.AkkaUtils$.askWithReply(AkkaUtils.scala:194)
        at org.apache.spark.executor.Executor$$anon$1.run(Executor.scala:427)
17/06/08 06:59:23 WARN AkkaUtils: Error sending message [message = Heartbeat(<driver>,[Lscala.Tuple2;@ac5b61d,BlockManagerId(<driver>, localhost, 26012))] in 2 attempts
akka.pattern.AskTimeoutException: Recipient[Actor[akka://sparkDriver/user/HeartbeatReceiver#-1309342978]] had already been terminated.
        at akka.pattern.AskableActorRef$.ask$extension(AskSupport.scala:134)
        at org.apache.spark.util.AkkaUtils$.askWithReply(AkkaUtils.scala:194)
        at org.apache.spark.executor.Executor$$anon$1.run(Executor.scala:427)
17/06/08 06:59:26 WARN AkkaUtils: Error sending message [message = Heartbeat(<driver>,[Lscala.Tuple2;@ac5b61d,BlockManagerId(<driver>, localhost, 26012))] in 3 attempts
akka.pattern.AskTimeoutException: Recipient[Actor[akka://sparkDriver/user/HeartbeatReceiver#-1309342978]] had already been terminated.
        at akka.pattern.AskableActorRef$.ask$extension(AskSupport.scala:134)
        at org.apache.spark.util.AkkaUtils$.askWithReply(AkkaUtils.scala:194)
        at org.apache.spark.executor.Executor$$anon$1.run(Executor.scala:427)
17/06/08 06:59:29 WARN Executor: Issue communicating with driver in heartbeater
org.apache.spark.SparkException: Error sending message [message = Heartbeat(<driver>,[Lscala.Tuple2;@ac5b61d,BlockManagerId(<driver>, localhost, 26012))]
        at org.apache.spark.util.AkkaUtils$.askWithReply(AkkaUtils.scala:209)
        at org.apache.spark.executor.Executor$$anon$1.run(Executor.scala:427)
Caused by: akka.pattern.AskTimeoutException: Recipient[Actor[akka://sparkDriver/user/HeartbeatReceiver#-1309342978]] had already been terminated.
        at akka.pattern.AskableActorRef$.ask$extension(AskSupport.scala:134)
        at org.apache.spark.util.AkkaUtils$.askWithReply(AkkaUtils.scala:194)
        ... 1 more
17/06/08 06:59:39 WARN AkkaUtils: Error sending message [message = Heartbeat(<driver>,[Lscala.Tuple2;@5e4d0345,BlockManagerId(<driver>, localhost, 26012))] in 1 attempts
akka.pattern.AskTimeoutException: Recipient[Actor[akka://sparkDriver/user/HeartbeatReceiver#-1309342978]] had already been terminated.
        at akka.pattern.AskableActorRef$.ask$extension(AskSupport.scala:134)
        at org.apache.spark.util.AkkaUtils$.askWithReply(AkkaUtils.scala:194)
        at org.apache.spark.executor.Executor$$anon$1.run(Executor.scala:427)
17/06/08 06:59:42 WARN AkkaUtils: Error sending message [message = Heartbeat(<driver>,[Lscala.Tuple2;@5e4d0345,BlockManagerId(<driver>, localhost, 26012))] in 2 attempts
akka.pattern.AskTimeoutException: Recipient[Actor[akka://sparkDriver/user/HeartbeatReceiver#-1309342978]] had already been terminated.
        at akka.pattern.AskableActorRef$.ask$extension(AskSupport.scala:134)
        at org.apache.spark.util.AkkaUtils$.askWithReply(AkkaUtils.scala:194)
        at org.apache.spark.executor.Executor$$anon$1.run(Executor.scala:427)
17/06/08 06:59:45 WARN AkkaUtils: Error sending message [message = Heartbeat(<driver>,[Lscala.Tuple2;@5e4d0345,BlockManagerId(<driver>, localhost, 26012))] in 3 attempts
akka.pattern.AskTimeoutException: Recipient[Actor[akka://sparkDriver/user/HeartbeatReceiver#-1309342978]] had already been terminated.
        at akka.pattern.AskableActorRef$.ask$extension(AskSupport.scala:134)
        at org.apache.spark.util.AkkaUtils$.askWithReply(AkkaUtils.scala:194)
        at org.apache.spark.executor.Executor$$anon$1.run(Executor.scala:427)
17/06/08 06:59:48 WARN Executor: Issue communicating with driver in heartbeater
org.apache.spark.SparkException: Error sending message [message = Heartbeat(<driver>,[Lscala.Tuple2;@5e4d0345,BlockManagerId(<driver>, localhost, 26012))]
        at org.apache.spark.util.AkkaUtils$.askWithReply(AkkaUtils.scala:209)
        at org.apache.spark.executor.Executor$$anon$1.run(Executor.scala:427)
Caused by: akka.pattern.AskTimeoutException: Recipient[Actor[akka://sparkDriver/user/HeartbeatReceiver#-1309342978]] had already been terminated.
        at akka.pattern.AskableActorRef$.ask$extension(AskSupport.scala:134)
        at org.apache.spark.util.AkkaUtils$.askWithReply(AkkaUtils.scala:194)
        ... 1 more
</code>```

Base on some reading I see that typically error: java.lang.NoSuchMethodError is connected to different versions of Spark. And that might be true because I'm useing different ones. But shouldn't sbt assembly cover that? please see below by build.sbt and assembly.sbt files

build.sbt

```<code>name := "spark-db-synchronizator"

//Versions
version := "1.0.0"
scalaVersion := "2.10.6"
val sparkVersion = "2.1.1"
val sl4jVersion = "1.7.10"
val log4jVersion = "1.2.17"
val scalaTestVersion = "2.2.6"
val scalaLoggingVersion = "3.5.0"
val sparkTestingBaseVersion = "1.6.1_0.3.3"
val jodaTimeVersion = "2.9.6"
val jodaConvertVersion = "1.8.1"
val jsonAssertVersion = "1.2.3"

libraryDependencies ++= Seq(
  "org.apache.spark" %% "spark-core" % sparkVersion,
  "org.apache.spark" %% "spark-sql" % sparkVersion,
  "org.apache.spark" %% "spark-hive" % sparkVersion,
  "org.apache.spark" %% "spark-streaming-kafka-0-10" % sparkVersion,
  "org.apache.spark" %% "spark-streaming" % sparkVersion,
  "org.slf4j" % "slf4j-api" % sl4jVersion,
  "org.slf4j" % "slf4j-log4j12" % sl4jVersion exclude("log4j", "log4j"),
  "log4j" % "log4j" % log4jVersion % "provided",
  "org.joda" % "joda-convert" % jodaConvertVersion,
  "joda-time" % "joda-time" % jodaTimeVersion,
  "org.scalatest" %% "scalatest" % scalaTestVersion % "test",
  "com.holdenkarau" %% "spark-testing-base" % sparkTestingBaseVersion % "test",
  "org.skyscreamer" % "jsonassert" % jsonAssertVersion % "test"
)

assemblyJarName in assembly := "db-synchronizer.jar"

run in Compile := Defaults.runTask(fullClasspath in Compile, mainClass in(Compile, run), runner in(Compile, run))
runMain in Compile := Defaults.runMainTask(fullClasspath in Compile, runner in(Compile, run))

assemblyMergeStrategy in assembly := {
  case PathList("META-INF", xs @ _*) => MergeStrategy.discard
  case x => MergeStrategy.first
}

// Spark does not support parallel tests and requires JVM fork
parallelExecution in Test := false

fork in Test := true
javaOptions in Test ++= Seq("-Xms512M", "-Xmx2048M", "-XX:MaxPermSize=2048M", "-XX:+CMSClassUnloadingEnabled")
</code>```

assembly.sbt

```<code>addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.3")
</code>```

答:
You're correct and it is possible to run a Spark application with Spark 2.1.1 libraries bundled on some Spark 1.6 environments like Hadoop YARN (in CDH or HDP).

The trick is fairly often used in large corporations where the infrastructure team forces development teams to use some older Spark versions only because CDH (YARN) or HDP (YARN) do not support them.

You should use spark-submit from the newer Spark installation (I'd suggest using the latest and greatest 2.1.1 as of this writing) and bundle all Spark jars as part of your Spark application.

Just sbt assembly your Spark application with Spark 2.1.1 (as you specified in build.sbt) and spark-submit the uberjar using the very same version of Spark 2.1.1 to older Spark environments.

As a matter of fact, Hadoop YARN does not make Spark any better than any other application library or framework. It's quite reluctant to pay special attention to Spark.

That however requires a cluster environment (and just checked it won't work with Spark Standalone 1.6 when your Spark application uses Spark 2.1.1).

In your case, when you started your Spark application using local[*] master URL, it was not supposed to work.

```<code>cd spark-1.6.0-bin-hadoop2.6/bin/
spark-submit --class  App --master local[*] /home/oracle/spark_test/db-synchronizer.jar
</code>```

There are two reasons for this:

local[*] is fairly constrained by CLASSPATH and trying to convince Spark 1.6.0 to run Spark 2.1.1 on the same JVM might take you fairly long time (if possible at all)

You use older version to run more current 2.1.1. The opposite could work.

Use Hadoop YARN as...well...it does not pay attention to Spark and has been tested few times in my projects already.

I was wandering how can I know which version of i.e.spark-core is taken in runtime

Use web UI and you should see the version in your top-left corner.

You should also consult web UI's Environment tab where you find the configuration of the runtime environment. That's the most authoritative source about the hosting environment of your Spark application.

Near the bottom you should see the Classpath Entries which should give you the CLASSPATH with jars, files and classes.

Use it to find any CLASSPATH-related issues.

Body:
I've been told that I could build a Spark application with one version of Spark and, as long as I use sbt assembly to build that, than I can run it with spark-submit on any spark cluster.

So, I've build my simple application with Spark 2.1.1. You can see my build.sbt file below. Than I'm starting this on my cluster with:

cd spark-1.6.0-bin-hadoop2.6/bin/
spark-submit --class  App --master local[*] /home/oracle/spark_test/db-synchronizer.jar

So as you see I'm executing it with spark 1.6.0.

and I'm getting error:

17/06/08 06:59:20 ERROR ActorSystemImpl: Uncaught fatal error from thread [sparkDriver-akka.actor.default-dispatcher-4] shutting down ActorSystem [sparkDriver]
java.lang.NoSuchMethodError: org.apache.spark.SparkConf.getTimeAsMs(Ljava/lang/String;Ljava/lang/String;)J
        at org.apache.spark.streaming.kafka010.KafkaRDD.<init>(KafkaRDD.scala:70)
        at org.apache.spark.streaming.kafka010.DirectKafkaInputDStream.compute(DirectKafkaInputDStream.scala:219)
        at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1$$anonfun$1.apply(DStream.scala:300)
        at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1$$anonfun$1.apply(DStream.scala:300)
        at scala.util.DynamicVariable.withValue(DynamicVariable.scala:57)
        at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1.apply(DStream.scala:299)
        at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1.apply(DStream.scala:287)
        at scala.Option.orElse(Option.scala:257)
        at org.apache.spark.streaming.dstream.DStream.getOrCompute(DStream.scala:284)
        at org.apache.spark.streaming.dstream.ForEachDStream.generateJob(ForEachDStream.scala:38)
        at org.apache.spark.streaming.DStreamGraph$$anonfun$1.apply(DStreamGraph.scala:116)
        at org.apache.spark.streaming.DStreamGraph$$anonfun$1.apply(DStreamGraph.scala:116)
        at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:251)
        at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:251)
        at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
        at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47)
        at scala.collection.TraversableLike$class.flatMap(TraversableLike.scala:251)
        at scala.collection.AbstractTraversable.flatMap(Traversable.scala:105)
        at org.apache.spark.streaming.DStreamGraph.generateJobs(DStreamGraph.scala:116)
        at org.apache.spark.streaming.scheduler.JobGenerator$$anonfun$2.apply(JobGenerator.scala:243)
        at org.apache.spark.streaming.scheduler.JobGenerator$$anonfun$2.apply(JobGenerator.scala:241)
        at scala.util.Try$.apply(Try.scala:161)
        at org.apache.spark.streaming.scheduler.JobGenerator.generateJobs(JobGenerator.scala:241)
        at org.apache.spark.streaming.scheduler.JobGenerator.org$apache$spark$streaming$scheduler$JobGenerator$$processEvent(JobGenerator.scala:177)
        at org.apache.spark.streaming.scheduler.JobGenerator$$anonfun$start$1$$anon$1$$anonfun$receive$1.applyOrElse(JobGenerator.scala:86)
        at akka.actor.ActorCell.receiveMessage(ActorCell.scala:498)
        at akka.actor.ActorCell.invoke(ActorCell.scala:456)
        at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:237)
        at akka.dispatch.Mailbox.run(Mailbox.scala:219)
        at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:386)
        at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
        at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
        at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
        at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
17/06/08 06:59:20 WARN AkkaUtils: Error sending message [message = Heartbeat(<driver>,[Lscala.Tuple2;@ac5b61d,BlockManagerId(<driver>, localhost, 26012))] in 1 attempts
akka.pattern.AskTimeoutException: Recipient[Actor[akka://sparkDriver/user/HeartbeatReceiver#-1309342978]] had already been terminated.
        at akka.pattern.AskableActorRef$.ask$extension(AskSupport.scala:134)
        at org.apache.spark.util.AkkaUtils$.askWithReply(AkkaUtils.scala:194)
        at org.apache.spark.executor.Executor$$anon$1.run(Executor.scala:427)
17/06/08 06:59:23 WARN AkkaUtils: Error sending message [message = Heartbeat(<driver>,[Lscala.Tuple2;@ac5b61d,BlockManagerId(<driver>, localhost, 26012))] in 2 attempts
akka.pattern.AskTimeoutException: Recipient[Actor[akka://sparkDriver/user/HeartbeatReceiver#-1309342978]] had already been terminated.
        at akka.pattern.AskableActorRef$.ask$extension(AskSupport.scala:134)
        at org.apache.spark.util.AkkaUtils$.askWithReply(AkkaUtils.scala:194)
        at org.apache.spark.executor.Executor$$anon$1.run(Executor.scala:427)
17/06/08 06:59:26 WARN AkkaUtils: Error sending message [message = Heartbeat(<driver>,[Lscala.Tuple2;@ac5b61d,BlockManagerId(<driver>, localhost, 26012))] in 3 attempts
akka.pattern.AskTimeoutException: Recipient[Actor[akka://sparkDriver/user/HeartbeatReceiver#-1309342978]] had already been terminated.
        at akka.pattern.AskableActorRef$.ask$extension(AskSupport.scala:134)
        at org.apache.spark.util.AkkaUtils$.askWithReply(AkkaUtils.scala:194)
        at org.apache.spark.executor.Executor$$anon$1.run(Executor.scala:427)
17/06/08 06:59:29 WARN Executor: Issue communicating with driver in heartbeater
org.apache.spark.SparkException: Error sending message [message = Heartbeat(<driver>,[Lscala.Tuple2;@ac5b61d,BlockManagerId(<driver>, localhost, 26012))]
        at org.apache.spark.util.AkkaUtils$.askWithReply(AkkaUtils.scala:209)
        at org.apache.spark.executor.Executor$$anon$1.run(Executor.scala:427)
Caused by: akka.pattern.AskTimeoutException: Recipient[Actor[akka://sparkDriver/user/HeartbeatReceiver#-1309342978]] had already been terminated.
        at akka.pattern.AskableActorRef$.ask$extension(AskSupport.scala:134)
        at org.apache.spark.util.AkkaUtils$.askWithReply(AkkaUtils.scala:194)
        ... 1 more
17/06/08 06:59:39 WARN AkkaUtils: Error sending message [message = Heartbeat(<driver>,[Lscala.Tuple2;@5e4d0345,BlockManagerId(<driver>, localhost, 26012))] in 1 attempts
akka.pattern.AskTimeoutException: Recipient[Actor[akka://sparkDriver/user/HeartbeatReceiver#-1309342978]] had already been terminated.
        at akka.pattern.AskableActorRef$.ask$extension(AskSupport.scala:134)
        at org.apache.spark.util.AkkaUtils$.askWithReply(AkkaUtils.scala:194)
        at org.apache.spark.executor.Executor$$anon$1.run(Executor.scala:427)
17/06/08 06:59:42 WARN AkkaUtils: Error sending message [message = Heartbeat(<driver>,[Lscala.Tuple2;@5e4d0345,BlockManagerId(<driver>, localhost, 26012))] in 2 attempts
akka.pattern.AskTimeoutException: Recipient[Actor[akka://sparkDriver/user/HeartbeatReceiver#-1309342978]] had already been terminated.
        at akka.pattern.AskableActorRef$.ask$extension(AskSupport.scala:134)
        at org.apache.spark.util.AkkaUtils$.askWithReply(AkkaUtils.scala:194)
        at org.apache.spark.executor.Executor$$anon$1.run(Executor.scala:427)
17/06/08 06:59:45 WARN AkkaUtils: Error sending message [message = Heartbeat(<driver>,[Lscala.Tuple2;@5e4d0345,BlockManagerId(<driver>, localhost, 26012))] in 3 attempts
akka.pattern.AskTimeoutException: Recipient[Actor[akka://sparkDriver/user/HeartbeatReceiver#-1309342978]] had already been terminated.
        at akka.pattern.AskableActorRef$.ask$extension(AskSupport.scala:134)
        at org.apache.spark.util.AkkaUtils$.askWithReply(AkkaUtils.scala:194)
        at org.apache.spark.executor.Executor$$anon$1.run(Executor.scala:427)
17/06/08 06:59:48 WARN Executor: Issue communicating with driver in heartbeater
org.apache.spark.SparkException: Error sending message [message = Heartbeat(<driver>,[Lscala.Tuple2;@5e4d0345,BlockManagerId(<driver>, localhost, 26012))]
        at org.apache.spark.util.AkkaUtils$.askWithReply(AkkaUtils.scala:209)
        at org.apache.spark.executor.Executor$$anon$1.run(Executor.scala:427)
Caused by: akka.pattern.AskTimeoutException: Recipient[Actor[akka://sparkDriver/user/HeartbeatReceiver#-1309342978]] had already been terminated.
        at akka.pattern.AskableActorRef$.ask$extension(AskSupport.scala:134)
        at org.apache.spark.util.AkkaUtils$.askWithReply(AkkaUtils.scala:194)
        ... 1 more

Base on some reading I see that typically error: java.lang.NoSuchMethodError is connected to different versions of Spark. And that might be true because I'm useing different ones. But shouldn't sbt assembly cover that? please see below by build.sbt and assembly.sbt files

build.sbt

name := "spark-db-synchronizator"

//Versions
version := "1.0.0"
scalaVersion := "2.10.6"
val sparkVersion = "2.1.1"
val sl4jVersion = "1.7.10"
val log4jVersion = "1.2.17"
val scalaTestVersion = "2.2.6"
val scalaLoggingVersion = "3.5.0"
val sparkTestingBaseVersion = "1.6.1_0.3.3"
val jodaTimeVersion = "2.9.6"
val jodaConvertVersion = "1.8.1"
val jsonAssertVersion = "1.2.3"

libraryDependencies ++= Seq(
  "org.apache.spark" %% "spark-core" % sparkVersion,
  "org.apache.spark" %% "spark-sql" % sparkVersion,
  "org.apache.spark" %% "spark-hive" % sparkVersion,
  "org.apache.spark" %% "spark-streaming-kafka-0-10" % sparkVersion,
  "org.apache.spark" %% "spark-streaming" % sparkVersion,
  "org.slf4j" % "slf4j-api" % sl4jVersion,
  "org.slf4j" % "slf4j-log4j12" % sl4jVersion exclude("log4j", "log4j"),
  "log4j" % "log4j" % log4jVersion % "provided",
  "org.joda" % "joda-convert" % jodaConvertVersion,
  "joda-time" % "joda-time" % jodaTimeVersion,
  "org.scalatest" %% "scalatest" % scalaTestVersion % "test",
  "com.holdenkarau" %% "spark-testing-base" % sparkTestingBaseVersion % "test",
  "org.skyscreamer" % "jsonassert" % jsonAssertVersion % "test"
)

assemblyJarName in assembly := "db-synchronizer.jar"

run in Compile := Defaults.runTask(fullClasspath in Compile, mainClass in(Compile, run), runner in(Compile, run))
runMain in Compile := Defaults.runMainTask(fullClasspath in Compile, runner in(Compile, run))

assemblyMergeStrategy in assembly := {
  case PathList("META-INF", xs @ _*) => MergeStrategy.discard
  case x => MergeStrategy.first
}

// Spark does not support parallel tests and requires JVM fork
parallelExecution in Test := false

fork in Test := true
javaOptions in Test ++= Seq("-Xms512M", "-Xmx2048M", "-XX:MaxPermSize=2048M", "-XX:+CMSClassUnloadingEnabled")

assembly.sbt

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.3")

Body:
You're correct and it is possible to run a Spark application with Spark 2.1.1 libraries bundled on some Spark 1.6 environments like Hadoop YARN (in CDH or HDP).

The trick is fairly often used in large corporations where the infrastructure team forces development teams to use some older Spark versions only because CDH (YARN) or HDP (YARN) do not support them.

You should use spark-submit from the newer Spark installation (I'd suggest using the latest and greatest 2.1.1 as of this writing) and bundle all Spark jars as part of your Spark application.

Just sbt assembly your Spark application with Spark 2.1.1 (as you specified in build.sbt) and spark-submit the uberjar using the very same version of Spark 2.1.1 to older Spark environments.

As a matter of fact, Hadoop YARN does not make Spark any better than any other application library or framework. It's quite reluctant to pay special attention to Spark.

That however requires a cluster environment (and just checked it won't work with Spark Standalone 1.6 when your Spark application uses Spark 2.1.1).

In your case, when you started your Spark application using local[*] master URL, it was not supposed to work.

cd spark-1.6.0-bin-hadoop2.6/bin/
spark-submit --class  App --master local[*] /home/oracle/spark_test/db-synchronizer.jar

There are two reasons for this:

local[*] is fairly constrained by CLASSPATH and trying to convince Spark 1.6.0 to run Spark 2.1.1 on the same JVM might take you fairly long time (if possible at all)

You use older version to run more current 2.1.1. The opposite could work.

Use Hadoop YARN as...well...it does not pay attention to Spark and has been tested few times in my projects already.

I was wandering how can I know which version of i.e.spark-core is taken in runtime

Use web UI and you should see the version in your top-left corner.

You should also consult web UI's Environment tab where you find the configuration of the runtime environment. That's the most authoritative source about the hosting environment of your Spark application.

Near the bottom you should see the Classpath Entries which should give you the CLASSPATH with jars, files and classes.

Use it to find any CLASSPATH-related issues.


来源: stackexchange

问:
Simple JWT Auth using Jquery
I am trying to do a simple JWT Authentication using only JQuery. I have already tested the backend with postman and everything seems to work in there.

Here's how my frontend code looks like

```<code>$("#send").click(function(){
    var name = $('#name').val();
    var password = $('#password').val();
    var token = ''
    $.ajax({
      type: 'POST',
      url: '/authenticate',
      data: { name: name , password: password },
      success: function(resultData){
        var token = resultData.token;
        // console.log(token);
        $.ajax({
          type: 'GET',
          url: '/memberinfo',
          headers: {"Authorization": token},
          success: function(data){
             $(location).attr('href', '/memberinfo')
          }
        });
      }
    });
});
</code>```

so when I get redirected to the memberinfo page it shows me I am unauthorised. Not quite sure if I am doing the Ajax calls properly. Would be really helpful if some one could direct me the right way. Thanks

答:
For simple use case just retrieve a token in the login request response and save it to the localStorage or sessionStorage. Then use the token from the localStorage inside every request header.
Please, have a look at an example code here.

https://github.com/chaofz/jquery-jwt-auth

On the other hand that is not secure to store a token in these storages as it is not protected from XSS attacks.

You better store token in cookies and check your cookies policies to prevent CSRF attack.

Please read more here

ContentLicense: CC BY-SA 3.0

Title: Simple JWT Auth using Jquery

Body:
I am trying to do a simple JWT Authentication using only JQuery. I have already tested the backend with postman and everything seems to work in there.

Here's how my frontend code looks like

$("#send").click(function(){
    var name = $('#name').val();
    var password = $('#password').val();
    var token = ''
    $.ajax({
      type: 'POST',
      url: '/authenticate',
      data: { name: name , password: password },
      success: function(resultData){
        var token = resultData.token;
        // console.log(token);
        $.ajax({
          type: 'GET',
          url: '/memberinfo',
          headers: {"Authorization": token},
          success: function(data){
             $(location).attr('href', '/memberinfo')
          }
        });
      }
    });
});

so when I get redirected to the memberinfo page it shows me I am unauthorised. Not quite sure if I am doing the Ajax calls properly. Would be really helpful if some one could direct me the right way. Thanks

ContentLicense: CC BY-SA 4.0


问:
SSRS Formatting a string to a comma number
I have the following value in one of my fileds in SSRS:

```<code>=CStr(Fields!Shipment_Weight.Value) + "#"
</code>```

I do this becuase I need the #(pounds) sign at the end. This now does not allow me to format the number into something like 1,000 it gives me 1000 currently. Is there a way to add commas in the code rather than the format box since this is a string now? Values are all different from 1-1000000000

Thanks!

答:
I found the answer it is as follows:

```<code>=CStr(FORMAT(Fields!Shipment_Weight.Value,"N0")) + "#"
</code>```

That is how you use formatting code without having to put it in the formatting properties box.

ContentLicense: CC BY-SA 2.5

Body:
I have the following value in one of my fileds in SSRS:

=CStr(Fields!Shipment_Weight.Value) + "#"

I do this becuase I need the #(pounds) sign at the end. This now does not allow me to format the number into something like 1,000 it gives me 1000 currently. Is there a way to add commas in the code rather than the format box since this is a string now? Values are all different from 1-1000000000

Thanks!

Body:
I found the answer it is as follows:

=CStr(FORMAT(Fields!Shipment_Weight.Value,"N0")) + "#"

That is how you use formatting code without having to put it in the formatting properties box.


问:
Roulette wheel selection with positive and negative fitness values for minimization
I'm doing a genetic algorithm where each inidividual generates 3 new offsprings. The new individuals are evaluated using the fitness function, which may return negative and positive values. What is the correct approach to choose between the offsprings using the roulette wheel selection if I want to minimize?

Some possible values of the fitness function are: fitness_offspring_1 = -98.74; fitness_offspring_2 = -10.1; fitness_offspring_3 = 100.31

I'm working on Python but I only need the idea so I can implement it by myself.

答:
For using Roulette wheel selection for minimization, you have to do two pre-processing steps:

You have to get rid of the negative fitness values, because the fitness value will represent the selection probability, which can't be negative. The easiest way for doing this, is to subtract the lowest (negative) value from all fitness values. The lowest fitness value is now zero.

For minimizing, you have to revert the fitness values. This is done by setting the fitness values to max fitness - fitness. The individual with the best fitness has now the highest fitness value.

The transformed fitness values are now feed into the normal Roulette wheel selector, which selects the individual with the highest fitness. But essentially you are doing a minimization.

The Java GA, Jenetics, is doing minimization in this way.


问:
Dynamic font resize
This script resize text based on the text length. All works fine but the text does not resize up when deleting characters. what's missing? Hoping there is a script guru around to help me!

  $('#location').keypress(function() {

    var textLength = $(this).val().length;

    if (textLength < 20) {
      // Do noting
    } else if (textLength < 40) {
      $(this).css('font-size', '16px');
    } else if (textLength > 40) {
      $(this).css('font-size', '24px');
    }
    //console.log(textLength);
  }); ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#location {
  font-size: 24px;
  outline: none;
  width: 200px;
  height: 30px;
  display: table-cell;
  vertical-align: middle;
  border: 1px solid #ccc;
}</code>```

<input type="text" id="location" placeholder="Placeholder Text" />```

答:
keypress will not fire on backspace, so change it to keyup instead

Remove the else condition and made use of only if

```<code>$('#location').keyup(function() {

   var textLength = $(this).val().length;

   if (textLength < 40) {
       $(this).css('font-size', '16px');
   }
   if (textLength > 40) {
      $(this).css('font-size', '24px');
   }
    //console.log(textLength);
});
</code>```

Title: Dynamic font resize

Body:
This script resize text based on the text length. All works fine but the text does not resize up when deleting characters. what's missing? Hoping there is a script guru around to help me!

  $('#location').keypress(function() {

    var textLength = $(this).val().length;

    if (textLength < 20) {
      // Do noting
    } else if (textLength < 40) {
      $(this).css('font-size', '16px');
    } else if (textLength > 40) {
      $(this).css('font-size', '24px');
    }
    //console.log(textLength);
  });

#location {
  font-size: 24px;
  outline: none;
  width: 200px;
  height: 30px;
  display: table-cell;
  vertical-align: middle;
  border: 1px solid #ccc;
}

<input type="text" id="location" placeholder="Placeholder Text" />

Body:
keypress will not fire on backspace, so change it to keyup instead

Remove the else condition and made use of only if

$('#location').keyup(function() {

   var textLength = $(this).val().length;

   if (textLength < 40) {
       $(this).css('font-size', '16px');
   }
   if (textLength > 40) {
      $(this).css('font-size', '24px');
   }
    //console.log(textLength);
});


问:
SQL Server - Creating a Plan Guide without using an alias
I'm trying to create a plan guide in SQL Server 2012 SP3 Enterprise Edition for a specific query run by an application, which means I cannot alter the query in any way.

The query looks like this:

```<code>(@P1 nvarchar(5),@P2 bigint)
DELETE FROM INVENTSUMDELTA WHERE ((DATAAREAID=@P1) AND (TTSID=@P2))
</code>```

To create the plan guide, I used the following query:

```<code>EXEC sp_create_plan_guide
@name = N'INVENTSUMDELTAINDEX',
@stmt = N'DELETE FROM INVENTSUMDELTA WHERE ((DATAAREAID=@P1) AND (TTSID=@P2))',
@type = N'SQL',
@module_or_batch = NULL,
@params = N'@P1 nvarchar(5),@P2 bigint',
@hints = N'OPTION (TABLE HINT ( INVENTSUMDELTA, INDEX( I_2397TTSDIMIDX )))';
</code>```

However, I received an error:

Msg 8724, Level 16, State 1, Line 1
  Cannot execute query. Table-valued or OPENROWSET function 'INVENTSUMDELTA' cannot be specified in the TABLE HINT clause.

I checked the documentation and found the following:

TABLE HINT (exposed_object_name [ ,  [ [, ]...n ] ] )
   Applies the specified table hint to the table or view that corresponds to exposed_object_name. [...]

exposed_object_name can be one of the following references:

When an alias is used for the table or view in the FROM clause of the query, exposed_object_name is the alias.

When an alias is not used, exposed_object_name is the exact match of the table or view referenced in the FROM clause. For example, if the table or view is referenced using a two-part name, exposed_object_name is the same two-part name.

From this I gather that it should be possible to create a plan guide for a query that isn't using an alias. However, I cannot get it to work.

So my question is: how do I create a plan guide without using aliasing and without altering the original query?

答:
The error message is misleading. It has nothing to do with the nature of the object (you will get the same error with a nonexistent object). The problem is that it will not work for DELETE statements -- any TABLE HINT referring to a table that is the target of a DELETE will produce this error. This is not restricted to plan guides either -- a plain DELETE with an option will fail as well:

```<code>DELETE FROM does_not_exist
OPTION (TABLE HINT (does_not_exist, INDEX (does_not_exist)))
</code>```

Cannot execute query. Table-valued or OPENROWSET function 'does_not_exist' cannot be specified in the TABLE HINT clause.

This appears to be a bug, because if the statement is augmented with a WITH (ROWLOCK) hint at both the table and query level, the error disappears:

```<code>DELETE FROM does_not_exist WITH (ROWLOCK)
OPTION (TABLE HINT (does_not_exist, ROWLOCK, INDEX (does_not_exist)))
</code>```

Invalid object name 'does_not_exist'.

The same issue is covered in this question, and the solution is to rewrite the query in a form that does allow applying the hint.

In this case, we can't rewrite the query directly, but we can still get the desired effect by using a fixed query plan guide:

```<code>-- Alternate query using hint.
DECLARE @sql NVARCHAR(MAX) = N'WITH T AS (
    SELECT *
    FROM INVENTSUMDELTA WITH (INDEX (I_2397TTSDIMIDX))
    WHERE ((DATAAREAID=@P1) AND (TTSID=@P2))
)
DELETE T';
DECLARE @params NVARCHAR(MAX) = N'@P1 nvarchar(5),@P2 bigint'

-- Put the execution plan in the cache.
EXEC sp_executesql @sql, @params = @params, @P1=NULL, @P2=NULL;

-- Retrieve it.
DECLARE @query_plan NVARCHAR(MAX);
SELECT @query_plan = query_plan
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.[sql_handle]) AS st
CROSS APPLY sys.dm_exec_text_query_plan(qs.[plan_handle], DEFAULT, DEFAULT) AS qp
WHERE st.[text] LIKE '(' + @params + ')%' + @sql;

-- Create a plan guide associating the query with the new execution plan.
EXEC sp_create_plan_guide
    @name = N'INVENTSUMDELTAINDEX',
    @stmt = N'DELETE FROM INVENTSUMDELTA WHERE ((DATAAREAID=@P1) AND (TTSID=@P2))',
    @type = N'SQL',
    @module_or_batch = NULL,
    @params = @params,
    @hints = @query_plan;
</code>```

As always, plan guides should be the last resort if nothing else helps (updating statistics, creating new indexes, dropping suboptimal indexes). This answer assumes you've reviewed all the other options and the plan guide is necessary.

Body:
I'm trying to create a plan guide in SQL Server 2012 SP3 Enterprise Edition for a specific query run by an application, which means I cannot alter the query in any way.

The query looks like this:

(@P1 nvarchar(5),@P2 bigint)
DELETE FROM INVENTSUMDELTA WHERE ((DATAAREAID=@P1) AND (TTSID=@P2))

To create the plan guide, I used the following query:

EXEC sp_create_plan_guide
@name = N'INVENTSUMDELTAINDEX',
@stmt = N'DELETE FROM INVENTSUMDELTA WHERE ((DATAAREAID=@P1) AND (TTSID=@P2))',
@type = N'SQL',
@module_or_batch = NULL,
@params = N'@P1 nvarchar(5),@P2 bigint',
@hints = N'OPTION (TABLE HINT ( INVENTSUMDELTA, INDEX( I_2397TTSDIMIDX )))';

However, I received an error:

Msg 8724, Level 16, State 1, Line 1
  Cannot execute query. Table-valued or OPENROWSET function 'INVENTSUMDELTA' cannot be specified in the TABLE HINT clause.

I checked the documentation and found the following:

TABLE HINT (exposed_object_name [ ,  [ [, ]...n ] ] )
   Applies the specified table hint to the table or view that corresponds to exposed_object_name. [...]

exposed_object_name can be one of the following references:

When an alias is used for the table or view in the FROM clause of the query, exposed_object_name is the alias.

When an alias is not used, exposed_object_name is the exact match of the table or view referenced in the FROM clause. For example, if the table or view is referenced using a two-part name, exposed_object_name is the same two-part name.

From this I gather that it should be possible to create a plan guide for a query that isn't using an alias. However, I cannot get it to work.

So my question is: how do I create a plan guide without using aliasing and without altering the original query?

Body:
The error message is misleading. It has nothing to do with the nature of the object (you will get the same error with a nonexistent object). The problem is that it will not work for DELETE statements -- any TABLE HINT referring to a table that is the target of a DELETE will produce this error. This is not restricted to plan guides either -- a plain DELETE with an option will fail as well:

DELETE FROM does_not_exist
OPTION (TABLE HINT (does_not_exist, INDEX (does_not_exist)))

Cannot execute query. Table-valued or OPENROWSET function 'does_not_exist' cannot be specified in the TABLE HINT clause.

This appears to be a bug, because if the statement is augmented with a WITH (ROWLOCK) hint at both the table and query level, the error disappears:

DELETE FROM does_not_exist WITH (ROWLOCK)
OPTION (TABLE HINT (does_not_exist, ROWLOCK, INDEX (does_not_exist)))

Invalid object name 'does_not_exist'.

The same issue is covered in this question, and the solution is to rewrite the query in a form that does allow applying the hint.

In this case, we can't rewrite the query directly, but we can still get the desired effect by using a fixed query plan guide:

-- Alternate query using hint.
DECLARE @sql NVARCHAR(MAX) = N'WITH T AS (
    SELECT *
    FROM INVENTSUMDELTA WITH (INDEX (I_2397TTSDIMIDX))
    WHERE ((DATAAREAID=@P1) AND (TTSID=@P2))
)
DELETE T';
DECLARE @params NVARCHAR(MAX) = N'@P1 nvarchar(5),@P2 bigint'

-- Put the execution plan in the cache.
EXEC sp_executesql @sql, @params = @params, @P1=NULL, @P2=NULL;

-- Retrieve it.
DECLARE @query_plan NVARCHAR(MAX);
SELECT @query_plan = query_plan
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.[sql_handle]) AS st
CROSS APPLY sys.dm_exec_text_query_plan(qs.[plan_handle], DEFAULT, DEFAULT) AS qp
WHERE st.[text] LIKE '(' + @params + ')%' + @sql;

-- Create a plan guide associating the query with the new execution plan.
EXEC sp_create_plan_guide
    @name = N'INVENTSUMDELTAINDEX',
    @stmt = N'DELETE FROM INVENTSUMDELTA WHERE ((DATAAREAID=@P1) AND (TTSID=@P2))',
    @type = N'SQL',
    @module_or_batch = NULL,
    @params = @params,
    @hints = @query_plan;

As always, plan guides should be the last resort if nothing else helps (updating statistics, creating new indexes, dropping suboptimal indexes). This answer assumes you've reviewed all the other options and the plan guide is necessary.


问:
jQuery ajax call fires error event on a 200 success call
I have an ASP.NET Core WebAPI project with the following GET in my controller:

```<code>[HttpGet]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}
</code>```

I'm trying to call this method from jQuery ajax call:

```<code>$.ajax({
    type: "GET",
    url: url,
    async: true,
    dataType: "json",
    success: function (data) {
        setJsonResult(data);
        showResultPane("API request result");
    },
    error: function (obj, textStatus, errorThrown) {
        setHtmlResult("Error returned by API: " + errorThrown);
        showResultPane("Unauthorized request result");
    },
    beforeSend: function (request) {
        if (currentToken) {
            request.setRequestHeader("Authorization", "Bearer " + currentToken);
        }
    }
});
</code>```

I monitor the web traffic with Fiddler and I see that the server returns a 200 Ok response with the following:

```<code>HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Server: Kestrel
Access-Control-Allow-Origin: *
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type,     Accept, Authorization
Date: Thu, 08 Jun 2017 09:13:18 GMT

13
["value1","value2"]
0
</code>```

The problem is that while the response from the web server is successful, the jQuery ajax error method is still being fired instead of the success method. I've tried playing with the dataType parameter (changing it, removing it) - no effect.

I even tried returning a different value from the API that is just a string and even change dataType to text - still firing error.

What's going on here?

答:
Found the solution - don't yet understand the full extent of it. Basically it had to do with ASP.NET CORS policy. So for now I just enabled everything:</p>

```<code>app.UseCors(builder => builder.AllowAnyOrigin().AllowCredentials().AllowAnyHeader().AllowAnyMethod());
</code>```

Body:
I have an ASP.NET Core WebAPI project with the following GET in my controller:

[HttpGet]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

I'm trying to call this method from jQuery ajax call:

$.ajax({
    type: "GET",
    url: url,
    async: true,
    dataType: "json",
    success: function (data) {
        setJsonResult(data);
        showResultPane("API request result");
    },
    error: function (obj, textStatus, errorThrown) {
        setHtmlResult("Error returned by API: " + errorThrown);
        showResultPane("Unauthorized request result");
    },
    beforeSend: function (request) {
        if (currentToken) {
            request.setRequestHeader("Authorization", "Bearer " + currentToken);
        }
    }
});

I monitor the web traffic with Fiddler and I see that the server returns a 200 Ok response with the following:

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Server: Kestrel
Access-Control-Allow-Origin: *
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type,     Accept, Authorization
Date: Thu, 08 Jun 2017 09:13:18 GMT

13
["value1","value2"]
0

The problem is that while the response from the web server is successful, the jQuery ajax error method is still being fired instead of the success method. I've tried playing with the dataType parameter (changing it, removing it) - no effect.

I even tried returning a different value from the API that is just a string and even change dataType to text - still firing error.

What's going on here?

Body:
Found the solution - don't yet understand the full extent of it. Basically it had to do with ASP.NET CORS policy. So for now I just enabled everything:

app.UseCors(builder => builder.AllowAnyOrigin().AllowCredentials().AllowAnyHeader().AllowAnyMethod());


问:
Force footer to stick at the bottom of rendered pages
Hey I try to force footer to move at the bottom of the page as the content is added.
Similar to : http://jsfiddle.net/eTwJh/2/
. I'm using asp.net mvc with Layout page, where views are rendered as Layout page 'body' with @RenderBody().

P.S. Using position: relative for both footer and body-content now force footer to stay at the bottom of the page, but now hen page is opened, footer is at the half of the page (end of html) min-height: 100% on body element don't seem to have any effect..

Screenshoot: Footer not staying at the bottom of the page

Chrome Inspect Element: http:// imgur.com/BWuFxn2

Here is my code Layout.cshtml page:

```<code> <body>
 ....
 <div class="container body-content" style="position:relative">
    @RenderBody()
</div>
<footer>
    <p>© @DateTime.Now.Year Some Text</p>
</footer>

@if (!User.Identity.IsAuthenticated)
{
<!-- BEGIN # MODAL LOGIN -->
<div class="modal fade" id="login-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
    <div class="modal-dialog">
        <div class="modal-content" id="modal-content">
        </div>
    </div>
</div>
<!-- END # MODAL LOGIN -->
}
</body>
</html>
</code>```

Here is my CSS:

```<code>footer {
  clear: both;
  background-color: #000;
  width: 100%;
  padding: 20px 0;
  border-bottom: 1px solid #5c5c5c;
  position: absolute;
  bottom: 0px;
}

footer p {
    padding-left: 5px;
    color: #fff;
    display: table-cell;
}
</code>```

答:
Make sure both your body-content and footer classes have position set to relative. In the fiddle it's set to absolute because footer is inside wrapper and bottom: 0 pushes it to the bottom of that wrapper.

Or simply create a wrapper for these two divs like in provided fiddle.

Body:
Hey I try to force footer to move at the bottom of the page as the content is added.
Similar to : http://jsfiddle.net/eTwJh/2/
. I'm using asp.net mvc with Layout page, where views are rendered as Layout page 'body' with @RenderBody().

P.S. Using position: relative for both footer and body-content now force footer to stay at the bottom of the page, but now hen page is opened, footer is at the half of the page (end of html) min-height: 100% on body element don't seem to have any effect..

Screenshoot: Footer not staying at the bottom of the page

Chrome Inspect Element: http:// imgur.com/BWuFxn2

Here is my code Layout.cshtml page:

 ....

    @RenderBody()

© @DateTime.Now.Year Some Text

@if (!User.Identity.IsAuthenticated)
{

}

Here is my CSS:

footer {
  clear: both;
  background-color: #000;
  width: 100%;
  padding: 20px 0;
  border-bottom: 1px solid #5c5c5c;
  position: absolute;
  bottom: 0px;
}

footer p {
    padding-left: 5px;
    color: #fff;
    display: table-cell;
}


问:
Please explain overflow:hidden 's effect on backgrounds?
I know when your elements background is not behind all of its content, (eg: because of floated elements, positioned elements, margin) adding overflow:hidden fixes the issue, forcing the background to show behind those elements.

For example see this question and meder's answer.

However, when doing this, it is not hiding any overflowing content, so how does setting this effect anything at all?

Basically I know it works, but I want to understand why?

答:
It creates a new block formatting context, which clears the floats.

http://www.w3.org/TR/CSS2/visuren.html#block-formatting

And.. it does clip overflowing content: http://jsfiddle.net/rDmhn/


问:
PHP 1st while loop's output result as 2nd while loop's variable for query
Question 1: Is it possible to feed 1st while loop's output result as 2nd while loop's variable for query?

I have mySQL table "reorder_in_process" below:

```<code>(`id`, `item`, `to_order`, `cat_no`, `supplier`) VALUES
(48, 'Petri Dish', 62, 1006, 'Progressive'),
(47, 'Beaker', 46, 1005, 'Progressive'),
(46, 'Tissue', 17, 1008, 'Needpoint'),
(45, 'Pipet', 77, 1004, 'Kumpulan');
</code>```

And my php below:

```<code><?PHP
include ('db.php');
$sql4 = "SELECT DISTINCT supplier FROM reorder_in_process";
$result4 = mysqli_query($con,$sql4);
$supplier4 = $row4['supplier'];
$i=0;

while($row4 = mysqli_fetch_array($result4)){
echo "<h4>".$row4['supplier']."</h4>";

echo  "<div><table><tr>
                        <th>No</th>
                        <th>Item</th>
                        <th>Cat. No</th>
                        <th>Buy QTY</th>
                        <th>Supplier</th>
                    </tr>";
$sql5 = "SELECT * FROM reorder_in_process WHERE supplier=$supplier4";
$result5 = mysqli_query($con,$sql5);
while($row5 = mysqli_fetch_array($result5)) {
$i++;
    echo "<tr>
            <td>".$i. "</td>
           <td>".$row5['item']."</td>
           <td>".$row5['cat_no']."</td>
           <td>".$row5['to_order']."</td>
           <td>".$row5['supplier']."</td>
     </tr>";
}
echo "</table></div>";
}
mysqli_close($con);
?>
</code>```

I doesn't work...I want the output result like below:

```<code>Progressive
No  Item    Cat. No Buy QTY Supplier
1   Petri Dish  1006    62  Progressive
2   Beaker      1005    46  Progressive

Needpoint
No  Item    Cat. No Buy QTY Supplier
1   Tissue  1008    17  Needpoint

Kumpulan
No  Item    Cat. No Buy QTY Supplier
1   Pipet   1004    77  Kumpulan
</code>```

Pls help to find my mistake and solution to it. Thanks.

答:
First of all the below line is undefined because it's outside of the while loop

```<code> $supplier4 = $row4['supplier'];
</code>```

Push the above code into inside first while loop and string should be enclosed by single quotes like this

```<code> "...supplier='$supplier4'"
</code>```

you need to reset the $i=1 for each new supplier

Update 1:

```<code><?PHP
include ('db.php');
$sql4 = "SELECT DISTINCT supplier FROM reorder_in_process";
$result4 = mysqli_query($con,$sql4);

while($row4 = mysqli_fetch_array($result4)){

    $i=1;
    $supplier4 = $row4['supplier'];

    echo "<h4>".$row4['supplier']."</h4>";

    echo  "<div><table><tr>
                            <th>No</th>
                            <th>Item</th>
                            <th>Cat. No</th>
                            <th>Buy QTY</th>
                            <th>Supplier</th>
                       </tr>";

    $sql5 = "SELECT * FROM reorder_in_process WHERE supplier='$supplier4'";
    $result5 = mysqli_query($con,$sql5);
    while($row5 = mysqli_fetch_array($result5)) {

        echo "<tr>
                <td>".$i. "</td>
               <td>".$row5['item']."</td>
               <td>".$row5['cat_no']."</td>
               <td>".$row5['to_order']."</td>
               <td>".$row5['supplier']."</td>
         </tr>";

         $i++;
    }
    echo "</table></div>";
}
mysqli_close($con);
?>
</code>```

Body:
Question 1: Is it possible to feed 1st while loop's output result as 2nd while loop's variable for query?

I have mySQL table "reorder_in_process" below:

(`id`, `item`, `to_order`, `cat_no`, `supplier`) VALUES
(48, 'Petri Dish', 62, 1006, 'Progressive'),
(47, 'Beaker', 46, 1005, 'Progressive'),
(46, 'Tissue', 17, 1008, 'Needpoint'),
(45, 'Pipet', 77, 1004, 'Kumpulan');

And my php below:

<?PHP
include ('db.php');
$sql4 = "SELECT DISTINCT supplier FROM reorder_in_process";
$result4 = mysqli_query($con,$sql4);
$supplier4 = $row4['supplier'];
$i=0;

while($row4 = mysqli_fetch_array($result4)){
echo "
".$row4['supplier']."
";

echo  "

                        No
                        Item
                        Cat. No
                        Buy QTY
                        Supplier

";
$sql5 = "SELECT * FROM reorder_in_process WHERE supplier=$supplier4";
$result5 = mysqli_query($con,$sql5);
while($row5 = mysqli_fetch_array($result5)) {
$i++;
    echo "

            ".$i. "
           ".$row5['item']."
           ".$row5['cat_no']."
           ".$row5['to_order']."
           ".$row5['supplier']."

";
}
echo "

";
}
mysqli_close($con);
?>

I doesn't work...I want the output result like below:

Progressive
No  Item    Cat. No Buy QTY Supplier
1   Petri Dish  1006    62  Progressive
2   Beaker      1005    46  Progressive

Needpoint
No  Item    Cat. No Buy QTY Supplier
1   Tissue  1008    17  Needpoint

Kumpulan
No  Item    Cat. No Buy QTY Supplier
1   Pipet   1004    77  Kumpulan

Pls help to find my mistake and solution to it. Thanks.

Body:
First of all the below line is undefined because it's outside of the while loop

 $supplier4 = $row4['supplier'];

Push the above code into inside first while loop and string should be enclosed by single quotes like this

 "...supplier='$supplier4'"

you need to reset the $i=1 for each new supplier

Update 1:

<?PHP
include ('db.php');
$sql4 = "SELECT DISTINCT supplier FROM reorder_in_process";
$result4 = mysqli_query($con,$sql4);

while($row4 = mysqli_fetch_array($result4)){

    $i=1;
    $supplier4 = $row4['supplier'];

    echo "<h4>".$row4['supplier']."</h4>";

    echo  "<div><table><tr>
                            <th>No</th>
                            <th>Item</th>
                            <th>Cat. No</th>
                            <th>Buy QTY</th>
                            <th>Supplier</th>
                       </tr>";

    $sql5 = "SELECT * FROM reorder_in_process WHERE supplier='$supplier4'";
    $result5 = mysqli_query($con,$sql5);
    while($row5 = mysqli_fetch_array($result5)) {

        echo "<tr>
                <td>".$i. "</td>
               <td>".$row5['item']."</td>
               <td>".$row5['cat_no']."</td>
               <td>".$row5['to_order']."</td>
               <td>".$row5['supplier']."</td>
         </tr>";

         $i++;
    }
    echo "</table></div>";
}
mysqli_close($con);
?>


问:
How to hide JavaScripts in wordpress
I have inserted my javascripts in the header.php file, but I noticed the whole code can be stolen by simply lookin at the source from within any single post or homepage...

May you suggest me a simple way to hide my javascripts in wordpress somehow to prevent being copied/stolen?

答: You can't hide javascript. Client always need to access it.</p>

Title: How to hide JavaScripts in wordpress


问:
Design crushing to corner PyQT5
I'm kinda new to this so I'm basically just copy pasting the stuff from tutorials I've done to make it work.

I've made a designer.ui file with QtDesigner and now I've exported it to Python code. If I use the -x command then run the design Python it works fine, but if I import it to another file (so I can make connections) then it all crushes down to 1 place rather than sticking to the grid layout base.

If I launch my Main.py file (not designer code) then I get the error QLayout: Attempting to add QLayout "" to MainWindow "MainWindow", which already has a layout but I don't see where I'm adding a layout within my Main code...

My code is:
https://gist.github.com/crabcrabcam/3a6a9e847791117616d18ada0895f868

Thanks for any help :) If you need some more stuff just ask.

答:
The problem is caused because the QMainWindow class already has a layout where the QStatusBar, QMenubar, etc. are placed. To customize it just add QWidget with the setCentralWidget.

```<code>class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        w = QtWidgets.QWidget(MainWindow)
        MainWindow.setCentralWidget(w)
        self.gridLayout = QtWidgets.QGridLayout(w)
        self.gridLayout.setObjectName("gridLayout")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.btnOpenFile = QtWidgets.QPushButton(MainWindow)
        self.btnOpenFile.setObjectName("btnOpenFile")
        self.horizontalLayout.addWidget(self.btnOpenFile)
        self.btnSaveFile = QtWidgets.QPushButton(MainWindow)
        self.btnSaveFile.setObjectName("btnSaveFile")
        self.horizontalLayout.addWidget(self.btnSaveFile)
        self.btnSendEmail = QtWidgets.QPushButton(MainWindow)
        self.btnSendEmail.setObjectName("btnSendEmail")
        self.horizontalLayout.addWidget(self.btnSendEmail)
        self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1)
        self.txtEditMain = QtWidgets.QPlainTextEdit(MainWindow)
        self.txtEditMain.setObjectName("txtEditMain")
        self.gridLayout.addWidget(self.txtEditMain, 1, 0, 1, 1)
        self.btnClear = QtWidgets.QPushButton(MainWindow)
        self.btnClear.setObjectName("btnClear")
        self.gridLayout.addWidget(self.btnClear, 2, 0, 1, 1)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
</code>```

Another observation, when you inherit from a class you must call the constructor of that class. In your case you are inheriting from QMainWindow then you should call the QMainWindow constructor and not QWidget.

```<code>class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent=parent)
        self.setupUi(self)
</code>```

Title: Design crushing to corner PyQT5

Body:
The problem is caused because the QMainWindow class already has a layout where the QStatusBar, QMenubar, etc. are placed. To customize it just add QWidget with the setCentralWidget.

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        w = QtWidgets.QWidget(MainWindow)
        MainWindow.setCentralWidget(w)
        self.gridLayout = QtWidgets.QGridLayout(w)
        self.gridLayout.setObjectName("gridLayout")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.btnOpenFile = QtWidgets.QPushButton(MainWindow)
        self.btnOpenFile.setObjectName("btnOpenFile")
        self.horizontalLayout.addWidget(self.btnOpenFile)
        self.btnSaveFile = QtWidgets.QPushButton(MainWindow)
        self.btnSaveFile.setObjectName("btnSaveFile")
        self.horizontalLayout.addWidget(self.btnSaveFile)
        self.btnSendEmail = QtWidgets.QPushButton(MainWindow)
        self.btnSendEmail.setObjectName("btnSendEmail")
        self.horizontalLayout.addWidget(self.btnSendEmail)
        self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1)
        self.txtEditMain = QtWidgets.QPlainTextEdit(MainWindow)
        self.txtEditMain.setObjectName("txtEditMain")
        self.gridLayout.addWidget(self.txtEditMain, 1, 0, 1, 1)
        self.btnClear = QtWidgets.QPushButton(MainWindow)
        self.btnClear.setObjectName("btnClear")
        self.gridLayout.addWidget(self.btnClear, 2, 0, 1, 1)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

Another observation, when you inherit from a class you must call the constructor of that class. In your case you are inheriting from QMainWindow then you should call the QMainWindow constructor and not QWidget.

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent=parent)
        self.setupUi(self)


问:
Get Payment dates in a list
I have a payment check application, in that I get 2 strings:

```<code>String contractBegin = "01-01-2018";
String contractEnd = "31-12-2018";
</code>```

Now every payment must be done the last Friday of the month. I need to calculate those dates and place it in a list or array.

Is there any optimal way to do that using the Java 8 nice features?

I started here:

```<code>    String contractBegin = "01-01-2018";
    String contractEnd = "31-12-2018";

    LocalDate contractStart = LocalDate.parse(contractBegin, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
    LocalDate contractStop = LocalDate.parse(contractEnd, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
    System.out.println(contractStart);
    System.out.println(contractStop);
    List<LocalDate> payCheck= new ArrayList<>();
    for (int i = 0; i < args.length; i++) {
        payCheck.add(...) ??
    }
</code>```

答:
Another alternative to @gnostrenoff's answer is to use TemporalAdjusters.lastInMonth() method, which gives you the specified last day of week in the month:

```<code>// get the last Friday of the month
payCheckDate = payCheckDate.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY));
</code>```

The rest of the while loop is the same as @gnostrenoff's answer.

Title: Get Payment dates in a list

Body:
I have a payment check application, in that I get 2 strings:

String contractBegin = "01-01-2018";
String contractEnd = "31-12-2018";

Now every payment must be done the last Friday of the month. I need to calculate those dates and place it in a list or array.

Is there any optimal way to do that using the Java 8 nice features?

I started here:

    String contractBegin = "01-01-2018";
    String contractEnd = "31-12-2018";

    LocalDate contractStart = LocalDate.parse(contractBegin, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
    LocalDate contractStop = LocalDate.parse(contractEnd, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
    System.out.println(contractStart);
    System.out.println(contractStop);
    List<LocalDate> payCheck= new ArrayList<>();
    for (int i = 0; i < args.length; i++) {
        payCheck.add(...) ??
    }

Body:
Another alternative to @gnostrenoff's answer is to use TemporalAdjusters.lastInMonth() method, which gives you the specified last day of week in the month:

// get the last Friday of the month
payCheckDate = payCheckDate.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY));

The rest of the while loop is the same as @gnostrenoff's answer.


问:
C# notation understanding Select(int.Parse)
I found a little script that I understand fully. I've got a string with "1 -2 5 40" for example. It reads the input string, splits it into a temporary array. Then this array is parsed and each element is transformed into an integer. The whole thing is order to give the nearest integer to zero.

But what I don't understand is the notation Select(int.Parse). There is no lambda expression here and the method int.Parse isn't called with brackets. Same with the OrderBy(Math.Abs)

Thank you in advance =)

```<code>var temps = Console.ReadLine().Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries);

var result = temps.Select(int.Parse)
.OrderBy(Math.Abs)
.ThenByDescending(x => x)
.FirstOrDefault();
</code>```

答:
Select LINQ IEnumerable<> extension method signature looks like that:

```<code>public static IEnumerable<TResult> Select<TSource, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, TResult> selector
)
</code>```

Look at the selector argument. In your case you pass to Select .Net standard function int.Parse which has signature:

```<code>public static int Parse(
    string s
)
</code>```

.Net compiler can convert delegates to Func<...> or Action<...>. In case of int.Parse it can be converted to Func and therefore can be passed as argument to Select method.

Exactly the same with OrderBy. Look at its signature too.

Body:
I found a little script that I understand fully. I've got a string with "1 -2 5 40" for example. It reads the input string, splits it into a temporary array. Then this array is parsed and each element is transformed into an integer. The whole thing is order to give the nearest integer to zero.

But what I don't understand is the notation Select(int.Parse). There is no lambda expression here and the method int.Parse isn't called with brackets. Same with the OrderBy(Math.Abs)

Thank you in advance =)

var temps = Console.ReadLine().Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries);

var result = temps.Select(int.Parse)
.OrderBy(Math.Abs)
.ThenByDescending(x => x)
.FirstOrDefault();

Body:
Select LINQ IEnumerable<> extension method signature looks like that:

public static IEnumerable<TResult> Select<TSource, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, TResult> selector
)

Look at the selector argument. In your case you pass to Select .Net standard function int.Parse which has signature:

public static int Parse(
    string s
)

.Net compiler can convert delegates to Func<...> or Action<...>. In case of int.Parse it can be converted to Func and therefore can be passed as argument to Select method.

Exactly the same with OrderBy. Look at its signature too.


问:
Horizontally Placed Equal Width Equal Horizontal Space Buttons With Auto Layout
I have written the following code to achieve

Horizontally spaced equal width fixed height equal horizontal spaced three button but somehow it's not working fine. Can anyone rectify this ?

```<code>UIButton *cancelBtn = [UIButton new];

cancelBtn.frame = CGRectMake(10, 5, (popupView.bounds.size.width-40)/3, 30);

[cancelBtn setTitle:@"Cancel" forState:UIControlStateNormal];

[cancelBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

[cancelBtn setBackgroundColor:[UIColor lightGrayColor]];

[popupView addSubview:cancelBtn];

UIButton *resetBtn = [UIButton new];

resetBtn.frame = CGRectMake(cancelBtn.frame.origin.x+cancelBtn.bounds.size.width+10, 5, (popupView.bounds.size.width-40)/3, 30);

[resetBtn setTitle:@"Reset" forState:UIControlStateNormal];

[resetBtn setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];

[resetBtn setBackgroundColor:[UIColor darkGrayColor]];

[popupView addSubview:resetBtn];

UIButton *doneBtn = [UIButton new];

doneBtn.frame = CGRectMake(popupView.bounds.size.width-10-((popupView.bounds.size.width-40)/3), 5, (popupView.bounds.size.width-40)/3, 30);

[doneBtn setTitle:@"Done" forState:UIControlStateNormal];

[doneBtn setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];

[doneBtn setBackgroundColor:[UIColor blackColor]];

[popupView addSubview:doneBtn];

cancelBtn.translatesAutoresizingMaskIntoConstraints = NO;

[cancelBtn addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:30]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeTop multiplier:1.0f constant:5.0f] ];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeLeft multiplier:1.0f constant:10.0f]];
 resetBtn.translatesAutoresizingMaskIntoConstraints = NO;

[resetBtn addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:30]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeTop multiplier:1.0f constant:5.0f] ];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:resetBtn attribute:NSLayoutAttributeLeft multiplier:1.0f constant:10.0f]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:resetBtn attribute:NSLayoutAttributeRight multiplier:1.0f constant:-10.0f]];

doneBtn.translatesAutoresizingMaskIntoConstraints = NO;

[doneBtn addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:30]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeTop multiplier:1.0f constant:5.0f] ];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeRight multiplier:1.0f constant:-10.0f]];
[popupView addConstraint:[NSLayoutConstraint     constraintWithItem:cancelBtn attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:resetBtn attribute:NSLayoutAttributeWidth multiplier:1 constant:0]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:doneBtn attribute:NSLayoutAttributeWidth multiplier:1 constant:0]];
</code>```

How to fix this ?

I want to achieve a popup like this.

enter image description here

答:
use stackView instead of UIView there are lots of flexibility.

You don't have to think about child view's autolayout inside stackView.

Stack View has a bunch of features to satisfy your needs

Code:

```<code>-(void)createStackViewWithButton {

UIButton *doneBtn = [UIButton new];
[doneBtn setTitle:@"Done" forState:UIControlStateNormal];

[doneBtn setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];

[doneBtn setBackgroundColor:[UIColor blackColor]];

[doneBtn.heightAnchor constraintEqualToConstant:40].active = true;
[doneBtn.widthAnchor constraintEqualToConstant:100].active = true;

UIButton *doneBtn2 = [UIButton new];
[doneBtn2 setTitle:@"Cancel" forState:UIControlStateNormal];

[doneBtn2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

[doneBtn2 setBackgroundColor:[UIColor greenColor]];

[doneBtn2.heightAnchor constraintEqualToConstant:40].active = true;
[doneBtn2.widthAnchor constraintEqualToConstant:100].active = true;

UIButton *doneBtn3 = [UIButton new];
[doneBtn3 setTitle:@"Edit" forState:UIControlStateNormal];

[doneBtn3 setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];

[doneBtn3 setBackgroundColor:[UIColor blueColor]];

[doneBtn3.heightAnchor constraintEqualToConstant:40].active = true;
[doneBtn3.widthAnchor constraintEqualToConstant:100].active = true;

UIStackView *stackView = [[UIStackView alloc] init];

stackView.axis = UILayoutConstraintAxisHorizontal;
stackView.distribution = UIStackViewDistributionEqualSpacing;
stackView.alignment = UIStackViewAlignmentCenter;
stackView.spacing = 0;

[stackView addArrangedSubview:doneBtn];
[stackView addArrangedSubview:doneBtn2];
[stackView addArrangedSubview:doneBtn3];

stackView.translatesAutoresizingMaskIntoConstraints = false;
[self.view addSubview:stackView];

//Layout for Stack View
[stackView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = true;
[stackView.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = true;

}
</code>```

output:

Body:
I have written the following code to achieve

Horizontally spaced equal width fixed height equal horizontal spaced three button but somehow it's not working fine. Can anyone rectify this ?

UIButton *cancelBtn = [UIButton new];

cancelBtn.frame = CGRectMake(10, 5, (popupView.bounds.size.width-40)/3, 30);

[cancelBtn setTitle:@"Cancel" forState:UIControlStateNormal];

[cancelBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

[cancelBtn setBackgroundColor:[UIColor lightGrayColor]];

[popupView addSubview:cancelBtn];

UIButton *resetBtn = [UIButton new];

resetBtn.frame = CGRectMake(cancelBtn.frame.origin.x+cancelBtn.bounds.size.width+10, 5, (popupView.bounds.size.width-40)/3, 30);

[resetBtn setTitle:@"Reset" forState:UIControlStateNormal];

[resetBtn setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];

[resetBtn setBackgroundColor:[UIColor darkGrayColor]];

[popupView addSubview:resetBtn];

UIButton *doneBtn = [UIButton new];

doneBtn.frame = CGRectMake(popupView.bounds.size.width-10-((popupView.bounds.size.width-40)/3), 5, (popupView.bounds.size.width-40)/3, 30);

[doneBtn setTitle:@"Done" forState:UIControlStateNormal];

[doneBtn setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];

[doneBtn setBackgroundColor:[UIColor blackColor]];

[popupView addSubview:doneBtn];

cancelBtn.translatesAutoresizingMaskIntoConstraints = NO;

[cancelBtn addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:30]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeTop multiplier:1.0f constant:5.0f] ];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeLeft multiplier:1.0f constant:10.0f]];
 resetBtn.translatesAutoresizingMaskIntoConstraints = NO;

[resetBtn addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:30]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeTop multiplier:1.0f constant:5.0f] ];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:resetBtn attribute:NSLayoutAttributeLeft multiplier:1.0f constant:10.0f]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:resetBtn attribute:NSLayoutAttributeRight multiplier:1.0f constant:-10.0f]];

doneBtn.translatesAutoresizingMaskIntoConstraints = NO;

[doneBtn addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:30]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeTop multiplier:1.0f constant:5.0f] ];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeRight multiplier:1.0f constant:-10.0f]];
[popupView addConstraint:[NSLayoutConstraint     constraintWithItem:cancelBtn attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:resetBtn attribute:NSLayoutAttributeWidth multiplier:1 constant:0]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:doneBtn attribute:NSLayoutAttributeWidth multiplier:1 constant:0]];

How to fix this ?

I want to achieve a popup like this.

enter image description here

Body:
use stackView instead of UIView there are lots of flexibility.

You don't have to think about child view's autolayout inside stackView.

Stack View has a bunch of features to satisfy your needs

Code:

-(void)createStackViewWithButton {

UIButton *doneBtn = [UIButton new];
[doneBtn setTitle:@"Done" forState:UIControlStateNormal];

[doneBtn setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];

[doneBtn setBackgroundColor:[UIColor blackColor]];

[doneBtn.heightAnchor constraintEqualToConstant:40].active = true;
[doneBtn.widthAnchor constraintEqualToConstant:100].active = true;

UIButton *doneBtn2 = [UIButton new];
[doneBtn2 setTitle:@"Cancel" forState:UIControlStateNormal];

[doneBtn2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

[doneBtn2 setBackgroundColor:[UIColor greenColor]];

[doneBtn2.heightAnchor constraintEqualToConstant:40].active = true;
[doneBtn2.widthAnchor constraintEqualToConstant:100].active = true;

UIButton *doneBtn3 = [UIButton new];
[doneBtn3 setTitle:@"Edit" forState:UIControlStateNormal];

[doneBtn3 setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];

[doneBtn3 setBackgroundColor:[UIColor blueColor]];

[doneBtn3.heightAnchor constraintEqualToConstant:40].active = true;
[doneBtn3.widthAnchor constraintEqualToConstant:100].active = true;

UIStackView *stackView = [[UIStackView alloc] init];

stackView.axis = UILayoutConstraintAxisHorizontal;
stackView.distribution = UIStackViewDistributionEqualSpacing;
stackView.alignment = UIStackViewAlignmentCenter;
stackView.spacing = 0;

[stackView addArrangedSubview:doneBtn];
[stackView addArrangedSubview:doneBtn2];
[stackView addArrangedSubview:doneBtn3];

stackView.translatesAutoresizingMaskIntoConstraints = false;
[self.view addSubview:stackView];

//Layout for Stack View
[stackView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = true;
[stackView.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = true;

}

output:


问:
CakePHP Search between 2 Date Records
I am building a small Web App that lets users reserve Office Rooms and Equipment. For the Reservation they enter a Start and an End Date.

When a user tries to find out if any (for example) car is available on 2012-10-23, and the database holds reservation date records of Start: 2012-10-20 and End: 2012-10-25 for (lets say) all the cars, how do I include all the dates between my date entries in the search?

The $date variable gets it's value from the Date Search Form Field.

This, unfortunately does not work, and I can't figure out how to use daysAsSql for this query:

```<code>$conditions = array(
    'conditions' => array(
        '? BETWEEN ? AND ?' => array($date,'Equipment.date_start','Equipment.date_end'),
    )));

$this->set('equipments', $this->Equipment->find('all', $conditions));
</code>```

答:
Here is CakePHP BETWEEN query example.

I'm defining my arrays as variables, and then using those variables in my CakePHP find function call:

```<code>// just return these two fields
$fields = array('uri', 'page_views');

// use this "between" range
$conditions = array('Event.date BETWEEN ? and ?' => array($start_date, $end_date));

// run the "select between" query
$results = $this->Event->find('all',
         array('fields'=>$fields,
               'conditions'=>$conditions));
</code>```

Ref from

Title: CakePHP Search between 2 Date Records

Body:
I am building a small Web App that lets users reserve Office Rooms and Equipment. For the Reservation they enter a Start and an End Date.

When a user tries to find out if any (for example) car is available on 2012-10-23, and the database holds reservation date records of Start: 2012-10-20 and End: 2012-10-25 for (lets say) all the cars, how do I include all the dates between my date entries in the search?

The $date variable gets it's value from the Date Search Form Field.

This, unfortunately does not work, and I can't figure out how to use daysAsSql for this query:

$conditions = array(
    'conditions' => array(
        '? BETWEEN ? AND ?' => array($date,'Equipment.date_start','Equipment.date_end'),
    )));

$this->set('equipments', $this->Equipment->find('all', $conditions));

Body:
Here is CakePHP BETWEEN query example.

I'm defining my arrays as variables, and then using those variables in my CakePHP find function call:

// just return these two fields
$fields = array('uri', 'page_views');

// use this "between" range
$conditions = array('Event.date BETWEEN ? and ?' => array($start_date, $end_date));

// run the "select between" query
$results = $this->Event->find('all',
         array('fields'=>$fields,
               'conditions'=>$conditions));

Ref from


问:
Getting Unix timestamp from the past with java 8
since Java 8 I can use instant and LocalDateTime

To get the Unix timestamp:

```<code>long unixTimestamp = Instant.now().getEpochSecond();
</code>```

But if I want to get a time from the past, lets say 2 weeks I use this:

```<code>int unixtime2weeksAgo = (int) ((System.currentTimeMillis() - 24 * 60 * 60 * 1000 * 14) / 1000L)
</code>```

With the docu I couldn't build a solution based on the new java 8 features is here someone who could provide a good solution by using instant or LocalDateTime?

答:
"Two weeks ago" is dependent on your time zone (there may have been some DST changes etc.). So using Instant or LocalDateTime may create issues because they don't include any time zone information.

Assuming you want to do it in UTC, you can use:

```<code>ZonedDateTime twoWeeksAgo = ZonedDateTime.now(ZoneOffset.UTC).minusWeeks(2);
long unixTs = twoWeeksAgo.toEpochSecond();
</code>```

You can specify a different time zone in place of ZoneOffset.UTC seen above. For example, ZoneId.of( "Asia/Kolkata" ).

Body:
since Java 8 I can use instant and LocalDateTime

To get the Unix timestamp:

long unixTimestamp = Instant.now().getEpochSecond();

But if I want to get a time from the past, lets say 2 weeks I use this:

int unixtime2weeksAgo = (int) ((System.currentTimeMillis() - 24 * 60 * 60 * 1000 * 14) / 1000L)

With the docu I couldn't build a solution based on the new java 8 features is here someone who could provide a good solution by using instant or LocalDateTime?

Body:
"Two weeks ago" is dependent on your time zone (there may have been some DST changes etc.). So using Instant or LocalDateTime may create issues because they don't include any time zone information.

Assuming you want to do it in UTC, you can use:

ZonedDateTime twoWeeksAgo = ZonedDateTime.now(ZoneOffset.UTC).minusWeeks(2);
long unixTs = twoWeeksAgo.toEpochSecond();

You can specify a different time zone in place of ZoneOffset.UTC seen above. For example, ZoneId.of( "Asia/Kolkata" ).


问:
C++ Qt Multiple Definitions
I'm trying to create a simple GUI application (so far) in Qt with C++ using the MinGW compiler. However, the compiler is informing me that I have a multiple definition of 'WiimoteScouter::WiimoteScouter(QWidget*)' on line 4 of wiimotescouter.cpp. I am using a check to make sure the header isn't included multiple times, but apparently it's not working, and I'm not sure why.

Here's the header file:

```<code>#ifndef WIIMOTESCOUTER_H
#define WIIMOTESCOUTER_H

#include <QWidget>

class QLabel;
class QLineEdit;
class QTextEdit;

class WiimoteScouter : public QWidget
{
    Q_OBJECT

public:
    WiimoteScouter(QWidget *parent = 0);

private:
    QLineEdit *eventLine;
};

#endif // WIIMOTESCOUTER_H
</code>```

And here's the cpp file:

```<code>#include <QtGui>
#include "wiimotescouter.h"

WiimoteScouter::WiimoteScouter(QWidget *parent) :
    QWidget(parent)
{
    QLabel *eventLabel = new QLabel(tr("Event:"));
    eventLine = new QLineEdit;

    QGridLayout *mainLayout = new QGridLayout;
    mainLayout->addWidget(eventLabel, 0, 0);
    mainLayout->addWidget(eventLine, 0, 1);

    setLayout(mainLayout);
    setWindowTitle(tr("Wiimote Alliance Scouter"));
}
</code>```

Lastly, the main.cpp:

```<code>#include <QtGui>
#include "wiimotescouter.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    WiimoteScouter wiimoteScouter;
    wiimoteScouter.show();

    return app.exec();
}
</code>```

答:
For me it was due to Qt's compilation model in Windows using MinGW.

My code compiled perfectly fine for Linux, but for Windows the linker errors were happening for following files:

```<code>Message.cpp
Util.cpp
</code>```

At first, in the .pro file, I couldn't find any similar file names. Then observing keenly I figured out that, the external google protobuf library, which I was compiling along, had some library files inside its folder named as:

```<code>message.cc
util.cc
</code>```

The cases and the extensions were different, but somehow it created mess in the Qt compilation. I just added an underscore to those library files and the things worked fine.

Title: C++ Qt Multiple Definitions

Body:
I'm trying to create a simple GUI application (so far) in Qt with C++ using the MinGW compiler. However, the compiler is informing me that I have a multiple definition of 'WiimoteScouter::WiimoteScouter(QWidget*)' on line 4 of wiimotescouter.cpp. I am using a check to make sure the header isn't included multiple times, but apparently it's not working, and I'm not sure why.

Here's the header file:

#ifndef WIIMOTESCOUTER_H
#define WIIMOTESCOUTER_H

#include <QWidget>

class QLabel;
class QLineEdit;
class QTextEdit;

class WiimoteScouter : public QWidget
{
    Q_OBJECT

public:
    WiimoteScouter(QWidget *parent = 0);

private:
    QLineEdit *eventLine;
};

#endif // WIIMOTESCOUTER_H

And here's the cpp file:

#include <QtGui>
#include "wiimotescouter.h"

WiimoteScouter::WiimoteScouter(QWidget *parent) :
    QWidget(parent)
{
    QLabel *eventLabel = new QLabel(tr("Event:"));
    eventLine = new QLineEdit;

    QGridLayout *mainLayout = new QGridLayout;
    mainLayout->addWidget(eventLabel, 0, 0);
    mainLayout->addWidget(eventLine, 0, 1);

    setLayout(mainLayout);
    setWindowTitle(tr("Wiimote Alliance Scouter"));
}

Lastly, the main.cpp:

#include <QtGui>
#include "wiimotescouter.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    WiimoteScouter wiimoteScouter;
    wiimoteScouter.show();

    return app.exec();
}

Body:
For me it was due to Qt's compilation model in Windows using MinGW.

My code compiled perfectly fine for Linux, but for Windows the linker errors were happening for following files:

Message.cpp
Util.cpp

At first, in the .pro file, I couldn't find any similar file names. Then observing keenly I figured out that, the external google protobuf library, which I was compiling along, had some library files inside its folder named as:

message.cc
util.cc

The cases and the extensions were different, but somehow it created mess in the Qt compilation. I just added an underscore to those library files and the things worked fine.


问:
Error 404 on delete row codeigniter 2
im deleting a row in coneigniter2  but it takes me to 404 page
(The page you requested was not found.)

this is my code

Controler Post

```<code> class Posts extends CI_Controller{

public function index(){
 $data['title'] = 'Ultimos Post';
  $data['posts'] = $this->Post_model->get_posts();
   $this->load->view('templates/header');
    $this->load->view('posts/index',$data);
     $this->load->view('templates/footer');
 }
   ...

   public function delete($id){
      //apagar post pelo id
         $this->Post_Model->delete_post($id);
          redirect('posts');

   }}
</code>```

Post Model

```<code> class Post_model extends Ci_Model{
  ...

    public function delete_post($id) {

              $this->db->where('id',$id);
                $this->db->delete('posts');

        }}
</code>```

In the View.php

```<code><?php echo form_open('/posts/delete/'.$post['id']);?>
<input type="submit" value="Delete" class="btn btn-danger" name="delete">
</code>```

Routes.php

```<code>$route['posts/create'] = 'posts/create';
$route['posts/(:any)'] = 'posts/view/$1';
$route['posts'] = 'posts/index';
$route['default_controller'] = "pages/view";
$route['(:any)'] = 'pages/view/$1';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
</code>```

答:
After deleting your redirecting its on Posts,
Which calling the index function of Posts controller .
The problem in you Posts controller index method , Please
share that method or check it yourself .</p>

Title: Error 404 on delete row codeigniter 2

Body:
im deleting a row in coneigniter2  but it takes me to 404 page
(The page you requested was not found.)

this is my code

Controler Post

 class Posts extends CI_Controller{

public function index(){
 $data['title'] = 'Ultimos Post';
  $data['posts'] = $this->Post_model->get_posts();
   $this->load->view('templates/header');
    $this->load->view('posts/index',$data);
     $this->load->view('templates/footer');
 }
   ...

   public function delete($id){
      //apagar post pelo id
         $this->Post_Model->delete_post($id);
          redirect('posts');

   }}

Post Model

 class Post_model extends Ci_Model{
  ...

    public function delete_post($id) {

              $this->db->where('id',$id);
                $this->db->delete('posts');

        }}

In the View.php

<?php echo form_open('/posts/delete/'.$post['id']);?>
<input type="submit" value="Delete" class="btn btn-danger" name="delete">

Routes.php

$route['posts/create'] = 'posts/create';
$route['posts/(:any)'] = 'posts/view/$1';
$route['posts'] = 'posts/index';
$route['default_controller'] = "pages/view";
$route['(:any)'] = 'pages/view/$1';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;


问:
How to call function if the value changes in any text input with same class?
How to call function if another function changes the value of any text field with class netvalue.</p>

```<code><input name="1" type="text" class="netvalue" readonly>
<input name="2" type="text" class="netvalue" readonly>
<input name="3" type="text" class="netvalue" readonly>

<script>
$(".netvalue").oninput(function(){
       confirm('changed');
});
<script>
</code>```

答:
You can trigger an input-change.

$(".netvalue").change(function(){
  console.log('changed')
});
$("#button").click(function(){
  $("input[name='1']").val("some text");
  $(".netvalue").trigger('change');
}); ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Insert text</button>
<input name="1" type="text" class="netvalue" >
<input name="2" type="text" class="netvalue" >
<input name="3" type="text" class="netvalue" ></code>```

Body:
How to call function if another function changes the value of any text field with class netvalue.

<input name="1" type="text" class="netvalue" readonly>
<input name="2" type="text" class="netvalue" readonly>
<input name="3" type="text" class="netvalue" readonly>

Body:
You can trigger an input-change.

$(".netvalue").change(function(){
  console.log('changed')
});
$("#button").click(function(){
  $("input[name='1']").val("some text");
  $(".netvalue").trigger('change');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Insert text</button>
<input name="1" type="text" class="netvalue" >
<input name="2" type="text" class="netvalue" >
<input name="3" type="text" class="netvalue" >


问:
Import Android Test Project into Eclipse from Version Control
I have an Android Eclipse project and an associated Android Test Eclipse project checked into a subversion repository.  Given a checked out working copy, how do I bring the Android Test project into an Eclipse workspace?

It's easy to add the Android project to the workspace (just File->New Project->Android Project->From Existing Source and point it at the directory in the svn working copy).  But, the 'New Android Test Project' does not have an option to create from existing source.

答:
Was searching for this functionality and didn't find it either :)

What I did in the end is this:

Moved my existing test project directory (checked out from version control) to a temp dir

In Eclipse I created a new empty Android Unit Test project, located it in the directory with the name of the original test project directory

Closed Eclipse and copied a .classpath and .project files from newly created test project to a current root directory of old test project (in a temp dir)

Removed a new empty test project directory, moved old one from temp location back to original location

Simply put, I just generated new .classpath and .project files and copied them to checked out project dir.

After cleaning and refreshing in Eclipse this worked out :)
Of course this is not a real solution, but an ugly workaround which I even don't expect to work in any situation, but who knows, might help you.
Cheers.


问:
How to get hover efect only on part of the element?
I have the below code:

.container {
 padding-top:20px;
}

.container:hover {
 background-color: red;
}

.text {
  padding-top: 20px;
}

.container:before {
content: 'before';
top: 5px;
position: absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>
  <span class='text'>
    My text
  </span>
</div></code>```

I needed the 'before' as a title so inserted it as a pseudo, moved up and created palce for it by adding padding to the div. Now when I hover over the div the pseudo gets highlighted as well, which I don't want.

AS it's a skin for external app I have very limited possibilities to add elements to dom, which is what I guess should be done. How can I highlight only bottom part of the div without the pseudo? Maybe there's a better way to style the pseudo itself so that it doesn't get hovered over? Pure CSS appreciated.

答:
You can try hover .text instead of .container and give "initial" or "transparent" background to the pseudo element.

Just my $0.02:
I hope you understand that this whole thing is very strange, to say the least. It will limit any further customizations like font-height etc. Each time a new line of text will be added, you'll need to adjust padding or margin or top. Honestly, I don't understand what kind of app has such a strict skin that can't let you add an element.

Body:
I have the below code:

.container {
 padding-top:20px;
}

.container:hover {
 background-color: red;
}

.text {
  padding-top: 20px;
}

.container:before {
content: 'before';
top: 5px;
position: absolute;
}

    My text

I needed the 'before' as a title so inserted it as a pseudo, moved up and created palce for it by adding padding to the div. Now when I hover over the div the pseudo gets highlighted as well, which I don't want.

AS it's a skin for external app I have very limited possibilities to add elements to dom, which is what I guess should be done. How can I highlight only bottom part of the div without the pseudo? Maybe there's a better way to style the pseudo itself so that it doesn't get hovered over? Pure CSS appreciated.


问:
Use of CachingAuthenticator in Dropwizard
I want to discard old authentications from dropwizard, which is why I'm using blow configuration of CachingAuthenticator.

```<code>@Override
public void run(WebConfiguration configuration, Environment environment) {
   environment.jersey().register(new ActivityResource());

   CachingAuthenticator<BasicCredentials, AuthUser> cachingAuthenticator =
        new CachingAuthenticator<>(environment.metrics(), new WebAuthenticator(),
                configuration.getAuthenticationCachePolicy());
}
</code>```

Policy is in yml file as

```<code>authenticationCachePolicy: maximumSize=10, expireAfterAccess=1m
</code>```

My questions are:

how do I register(get it working) cachingAuthenticator so every request will be authenticated?

How to set expireAfterAccess in seconds?

Anything which is wrong in code, please suggest...

答:
Working solution

```<code>/** authentication config */
CachingAuthenticator<BasicCredentials, AuthUser> cachingAuthenticator = new CachingAuthenticator<>(
    environment.metrics(), new MyAuthenticator(), configuration.getAuthenticationCachePolicy());

environment.jersey().register(new AuthDynamicFeature(new BasicCredentialAuthFilter.Builder<AuthUser>()
    .setAuthenticator(cachingAuthenticator).setRealm("kedar.javalkar.realm").buildAuthFilter()));

environment.jersey().register(new AuthValueFactoryProvider.Binder<>(AuthUser.class));
</code>```

The yml can either have

```<code># Caching authenticator.
authenticationCachePolicy: maximumSize=10000, expireAfterAccess=10m
</code>```

or

```<code># Caching authenticator.
authenticationCachePolicy: maximumSize=10000, expireAfterAccess=1s
</code>```

Body:
I want to discard old authentications from dropwizard, which is why I'm using blow configuration of CachingAuthenticator.

@Override
public void run(WebConfiguration configuration, Environment environment) {
   environment.jersey().register(new ActivityResource());

   CachingAuthenticator<BasicCredentials, AuthUser> cachingAuthenticator =
        new CachingAuthenticator<>(environment.metrics(), new WebAuthenticator(),
                configuration.getAuthenticationCachePolicy());
}

Policy is in yml file as

authenticationCachePolicy: maximumSize=10, expireAfterAccess=1m

My questions are:

how do I register(get it working) cachingAuthenticator so every request will be authenticated?

How to set expireAfterAccess in seconds?

Anything which is wrong in code, please suggest...

Body:
Working solution

/** authentication config */
CachingAuthenticator<BasicCredentials, AuthUser> cachingAuthenticator = new CachingAuthenticator<>(
    environment.metrics(), new MyAuthenticator(), configuration.getAuthenticationCachePolicy());

environment.jersey().register(new AuthDynamicFeature(new BasicCredentialAuthFilter.Builder<AuthUser>()
    .setAuthenticator(cachingAuthenticator).setRealm("kedar.javalkar.realm").buildAuthFilter()));

environment.jersey().register(new AuthValueFactoryProvider.Binder<>(AuthUser.class));

The yml can either have

# Caching authenticator.
authenticationCachePolicy: maximumSize=10000, expireAfterAccess=10m

or

# Caching authenticator.
authenticationCachePolicy: maximumSize=10000, expireAfterAccess=1s