text:
Q: Spark is throughing scala.reflect.internal.MissingRequirementError when writing Naive Bayes model I am getting Exception when i am running a sample code in spark-shell (1.6.0) using scala Future
Sample Code
import org.apache.spark.ml.classification.NaiveBayesModel
import java.util.concurrent.Executors
import scala.concurrent.{ ExecutionContext, Future }
import scala.util.{ Failure, Success }

implicit lazy val ec1 = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10))
implicit lazy val ec2 = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10))

(300 until 400).foreach { x =>
  Future {
     sc.setJobGroup(x.toString, "description");
     val model = NaiveBayesModel.load("/tmp/nb_0")
     model.save(s"/tmp/nb$x")
  }(ec1).onComplete {
     case Success(value) => println(s"output $value ")
     case Failure(e) => e.printStackTrace
  }(ec2)
}

Here, I am reading one naive bayes model form local disk and writing it multiple times in Asyc mode with different file names.
Exception
scala.reflect.internal.MissingRequirementError: class org.apache.spark.ml.classification.NaiveBayesModel.NaiveBayesModelWriter in JavaMirror with org.apache.spark.repl.SparkIMain$TranslatingClassLoader@16d48c9 of type class org.apache.spark.repl.SparkIMain$TranslatingClassLoader with classpath [/tmp/spark-bce3a131-f6d5-4b5a-9853-3aa0d70b928f] and parent being org.apache.spark.repl.SparkIMain$$anon$2@2dc584da of type class org.apache.spark.repl.SparkIMain$$anon$2 with classpath [file:/usr/lib/jvm/java-7-oracle/jre/lib/resources.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/rt.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/jsse.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/jce.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/charsets.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/jfr.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunec.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/localedata.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/dnsns.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunjce_provider.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/zipfs.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunpkcs11.jar,file:/usr/local/spark-1.6.0/conf/,file:/usr/local/spark-1.6.0/assembly/target/scala-2.10/spark-assembly-1.6.0-hadoop2.4.1.jar,file:/usr/local/spark-1.6.0/lib_managed/jars/datanucleus-core-3.2.10.jar,file:/usr/local/spark-1.6.0/lib_managed/jars/datanucleus-api-jdo-3.2.6.jar,file:/usr/local/spark-1.6.0/lib_managed/jars/datanucleus-rdbms-3.2.9.jar,file:/home/kaushal/kaushal-drive/spark/Simba_Spark_JDBC_Desktop/SimbaRTU_SparkJDBC41_Client_1.0.0.1001/,file:/usr/local/spark-1.6.0/lib_managed/jars/mysql-connector-java-5.1.36.jar] and parent being sun.misc.Launcher$AppClassLoader@3ad6a0e0 of type class sun.misc.Launcher$AppClassLoader with classpath [file:/usr/local/spark-1.6.0/conf/,file:/usr/local/spark-1.6.0/assembly/target/scala-2.10/spark-assembly-1.6.0-hadoop2.4.1.jar,file:/usr/local/spark-1.6.0/lib_managed/jars/datanucleus-core-3.2.10.jar,file:/usr/local/spark-1.6.0/lib_managed/jars/datanucleus-api-jdo-3.2.6.jar,file:/usr/local/spark-1.6.0/lib_managed/jars/datanucleus-rdbms-3.2.9.jar] and parent being sun.misc.Launcher$ExtClassLoader@60dbf04d of type class sun.misc.Launcher$ExtClassLoader with classpath [file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunec.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/localedata.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/dnsns.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunjce_provider.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/zipfs.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunpkcs11.jar] and parent being primordial classloader with boot classpath [/usr/lib/jvm/java-7-oracle/jre/lib/resources.jar:/usr/lib/jvm/java-7-oracle/jre/lib/rt.jar:/usr/lib/jvm/java-7-oracle/jre/lib/sunrsasign.jar:/usr/lib/jvm/java-7-oracle/jre/lib/jsse.jar:/usr/lib/jvm/java-7-oracle/jre/lib/jce.jar:/usr/lib/jvm/java-7-oracle/jre/lib/charsets.jar:/usr/lib/jvm/java-7-oracle/jre/lib/jfr.jar:/usr/lib/jvm/java-7-oracle/jre/classes] not found.
    at scala.reflect.internal.MissingRequirementError$.signal(MissingRequirementError.scala:16)
    at scala.reflect.internal.MissingRequirementError$.notFound(MissingRequirementError.scala:17)
    at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:48)
    at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:61)
    at scala.reflect.internal.Mirrors$RootsBase.staticModuleOrClass(Mirrors.scala:72)
    at scala.reflect.internal.Mirrors$RootsBase.staticClass(Mirrors.scala:119)
    at scala.reflect.internal.Mirrors$RootsBase.staticClass(Mirrors.scala:21)
    at org.apache.spark.ml.classification.NaiveBayesModel$NaiveBayesModelWriter$$typecreator1$1.apply(NaiveBayes.scala:264)
    at scala.reflect.api.TypeTags$WeakTypeTagImpl.tpe$lzycompute(TypeTags.scala:231)
    at scala.reflect.api.TypeTags$WeakTypeTagImpl.tpe(TypeTags.scala:231)
    at org.apache.spark.sql.catalyst.ScalaReflection$class.localTypeOf(ScalaReflection.scala:642)
    at org.apache.spark.sql.catalyst.ScalaReflection$.localTypeOf(ScalaReflection.scala:30)
    at org.apache.spark.sql.catalyst.ScalaReflection$class.schemaFor(ScalaReflection.scala:630)
    at org.apache.spark.sql.catalyst.ScalaReflection$.schemaFor(ScalaReflection.scala:30)
    at org.apache.spark.sql.SQLContext.createDataFrame(SQLContext.scala:430)
    at org.apache.spark.ml.classification.NaiveBayesModel$NaiveBayesModelWriter.saveImpl(NaiveBayes.scala:264)
    at org.apache.spark.ml.util.MLWriter.save(ReadWrite.scala:90)
    at org.apache.spark.ml.util.MLWritable$class.save(ReadWrite.scala:130)
    at org.apache.spark.ml.classification.NaiveBayesModel.save(NaiveBayes.scala:130)
    at $line61.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1$$anonfun$apply$mcVI$sp$1.apply$mcV$sp(<console>:65)
    at $line61.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1$$anonfun$apply$mcVI$sp$1.apply(<console>:63)
    at $line61.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1$$anonfun$apply$mcVI$sp$1.apply(<console>:63)
    at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24)
    at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
scala.reflect.internal.MissingRequirementError: class org.apache.spark.ml.classification.NaiveBayesModel.NaiveBayesModelWriter in JavaMirror with org.apache.spark.repl.SparkIMain$TranslatingClassLoader@16d48c9 of type class org.apache.spark.repl.SparkIMain$TranslatingClassLoader with classpath [/tmp/spark-bce3a131-f6d5-4b5a-9853-3aa0d70b928f] and parent being org.apache.spark.repl.SparkIMain$$anon$2@2dc584da of type class org.apache.spark.repl.SparkIMain$$anon$2 with classpath [file:/usr/lib/jvm/java-7-oracle/jre/lib/resources.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/rt.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/jsse.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/jce.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/charsets.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/jfr.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunec.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/localedata.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/dnsns.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunjce_provider.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/zipfs.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunpkcs11.jar,file:/usr/local/spark-1.6.0/conf/,file:/usr/local/spark-1.6.0/assembly/target/scala-2.10/spark-assembly-1.6.0-hadoop2.4.1.jar,file:/usr/local/spark-1.6.0/lib_managed/jars/datanucleus-core-3.2.10.jar,file:/usr/local/spark-1.6.0/lib_managed/jars/datanucleus-api-jdo-3.2.6.jar,file:/usr/local/spark-1.6.0/lib_managed/jars/datanucleus-rdbms-3.2.9.jar,file:/home/kaushal/kaushal-drive/spark/Simba_Spark_JDBC_Desktop/SimbaRTU_SparkJDBC41_Client_1.0.0.1001/,file:/usr/local/spark-1.6.0/lib_managed/jars/mysql-connector-java-5.1.36.jar] and parent being sun.misc.Launcher$AppClassLoader@3ad6a0e0 of type class sun.misc.Launcher$AppClassLoader with classpath [file:/usr/local/spark-1.6.0/conf/,file:/usr/local/spark-1.6.0/assembly/target/scala-2.10/spark-assembly-1.6.0-hadoop2.4.1.jar,file:/usr/local/spark-1.6.0/lib_managed/jars/datanucleus-core-3.2.10.jar,file:/usr/local/spark-1.6.0/lib_managed/jars/datanucleus-api-jdo-3.2.6.jar,file:/usr/local/spark-1.6.0/lib_managed/jars/datanucleus-rdbms-3.2.9.jar] and parent being sun.misc.Launcher$ExtClassLoader@60dbf04d of type class sun.misc.Launcher$ExtClassLoader with classpath [file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunec.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/localedata.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/dnsns.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunjce_provider.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/zipfs.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunpkcs11.jar] and parent being primordial classloader with boot classpath [/usr/lib/jvm/java-7-oracle/jre/lib/resources.jar:/usr/lib/jvm/java-7-oracle/jre/lib/rt.jar:/usr/lib/jvm/java-7-oracle/jre/lib/sunrsasign.jar:/usr/lib/jvm/java-7-oracle/jre/lib/jsse.jar:/usr/lib/jvm/java-7-oracle/jre/lib/jce.jar:/usr/lib/jvm/java-7-oracle/jre/lib/charsets.jar:/usr/lib/jvm/java-7-oracle/jre/lib/jfr.jar:/usr/lib/jvm/java-7-oracle/jre/classes] not found.
    at scala.reflect.internal.MissingRequirementError$.signal(MissingRequirementError.scala:16)
    at scala.reflect.internal.MissingRequirementError$.notFound(MissingRequirementError.scala:17)
    at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:48)
    at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:61)
    at scala.reflect.internal.Mirrors$RootsBase.staticModuleOrClass(Mirrors.scala:72)
    at scala.reflect.internal.Mirrors$RootsBase.staticClass(Mirrors.scala:119)
    at scala.reflect.internal.Mirrors$RootsBase.staticClass(Mirrors.scala:21)
    at org.apache.spark.ml.classification.NaiveBayesModel$NaiveBayesModelWriter$$typecreator1$1.apply(NaiveBayes.scala:264)
    at scala.reflect.api.TypeTags$WeakTypeTagImpl.tpe$lzycompute(TypeTags.scala:231)
    at scala.reflect.api.TypeTags$WeakTypeTagImpl.tpe(TypeTags.scala:231)
    at org.apache.spark.sql.catalyst.ScalaReflection$class.localTypeOf(ScalaReflection.scala:642)
    at org.apache.spark.sql.catalyst.ScalaReflection$.localTypeOf(ScalaReflection.scala:30)
    at org.apache.spark.sql.catalyst.ScalaReflection$class.schemaFor(ScalaReflection.scala:630)
    at org.apache.spark.sql.catalyst.ScalaReflection$.schemaFor(ScalaReflection.scala:30)
    at org.apache.spark.sql.SQLContext.createDataFrame(SQLContext.scala:430)
    at org.apache.spark.ml.classification.NaiveBayesModel$NaiveBayesModelWriter.saveImpl(NaiveBayes.scala:264)
    at org.apache.spark.ml.util.MLWriter.save(ReadWrite.scala:90)
    at org.apache.spark.ml.util.MLWritable$class.save(ReadWrite.scala:130)
    at org.apache.spark.ml.classification.NaiveBayesModel.save(NaiveBayes.scala:130)
    at $line61.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1$$anonfun$apply$mcVI$sp$1.apply$mcV$sp(<console>:65)
    at $line61.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1$$anonfun$apply$mcVI$sp$1.apply(<console>:63)
    at $line61.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1$$anonfun$apply$mcVI$sp$1.apply(<console>:63)
    at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24)
    at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
scala.reflect.internal.MissingRequirementError: class org.apache.spark.ml.classification.NaiveBayesModel.NaiveBayesModelWriter in JavaMirror with org.apache.spark.repl.SparkIMain$TranslatingClassLoader@16d48c9 of type class org.apache.spark.repl.SparkIMain$TranslatingClassLoader with classpath [/tmp/spark-bce3a131-f6d5-4b5a-9853-3aa0d70b928f] and parent being org.apache.spark.repl.SparkIMain$$anon$2@2dc584da of type class org.apache.spark.repl.SparkIMain$$anon$2 with classpath [file:/usr/lib/jvm/java-7-oracle/jre/lib/resources.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/rt.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/jsse.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/jce.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/charsets.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/jfr.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunec.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/localedata.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/dnsns.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunjce_provider.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/zipfs.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunpkcs11.jar,file:/usr/local/spark-1.6.0/conf/,file:/usr/local/spark-1.6.0/assembly/target/scala-2.10/spark-assembly-1.6.0-hadoop2.4.1.jar,file:/usr/local/spark-1.6.0/lib_managed/jars/datanucleus-core-3.2.10.jar,file:/usr/local/spark-1.6.0/lib_managed/jars/datanucleus-api-jdo-3.2.6.jar,file:/usr/local/spark-1.6.0/lib_managed/jars/datanucleus-rdbms-3.2.9.jar,file:/home/kaushal/kaushal-drive/spark/Simba_Spark_JDBC_Desktop/SimbaRTU_SparkJDBC41_Client_1.0.0.1001/,file:/usr/local/spark-1.6.0/lib_managed/jars/mysql-connector-java-5.1.36.jar] and parent being sun.misc.Launcher$AppClassLoader@3ad6a0e0 of type class sun.misc.Launcher$AppClassLoader with classpath [file:/usr/local/spark-1.6.0/conf/,file:/usr/local/spark-1.6.0/assembly/target/scala-2.10/spark-assembly-1.6.0-hadoop2.4.1.jar,file:/usr/local/spark-1.6.0/lib_managed/jars/datanucleus-core-3.2.10.jar,file:/usr/local/spark-1.6.0/lib_managed/jars/datanucleus-api-jdo-3.2.6.jar,file:/usr/local/spark-1.6.0/lib_managed/jars/datanucleus-rdbms-3.2.9.jar] and parent being sun.misc.Launcher$ExtClassLoader@60dbf04d of type class sun.misc.Launcher$ExtClassLoader with classpath [file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunec.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/localedata.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/dnsns.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunjce_provider.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/zipfs.jar,file:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunpkcs11.jar] and parent being primordial classloader with boot classpath [/usr/lib/jvm/java-7-oracle/jre/lib/resources.jar:/usr/lib/jvm/java-7-oracle/jre/lib/rt.jar:/usr/lib/jvm/java-7-oracle/jre/lib/sunrsasign.jar:/usr/lib/jvm/java-7-oracle/jre/lib/jsse.jar:/usr/lib/jvm/java-7-oracle/jre/lib/jce.jar:/usr/lib/jvm/java-7-oracle/jre/lib/charsets.jar:/usr/lib/jvm/java-7-oracle/jre/lib/jfr.jar:/usr/lib/jvm/java-7-oracle/jre/classes] not found.
    at scala.reflect.internal.MissingRequirementError$.signal(MissingRequirementError.scala:16)
    at scala.reflect.internal.MissingRequirementError$.notFound(MissingRequirementError.scala:17)
    at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:48)
    at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:61)
    at scala.reflect.internal.Mirrors$RootsBase.staticModuleOrClass(Mirrors.scala:72)
    at scala.reflect.internal.Mirrors$RootsBase.staticClass(Mirrors.scala:119)
    at scala.reflect.internal.Mirrors$RootsBase.staticClass(Mirrors.scala:21)
    at org.apache.spark.ml.classification.NaiveBayesModel$NaiveBayesModelWriter$$typecreator1$1.apply(NaiveBayes.scala:264)
    at scala.reflect.api.TypeTags$WeakTypeTagImpl.tpe$lzycompute(TypeTags.scala:231)
    at scala.reflect.api.TypeTags$WeakTypeTagImpl.tpe(TypeTags.scala:231)
    at org.apache.spark.sql.catalyst.ScalaReflection$class.localTypeOf(ScalaReflection.scala:642)
    at org.apache.spark.sql.catalyst.ScalaReflection$.localTypeOf(ScalaReflection.scala:30)
    at org.apache.spark.sql.catalyst.ScalaReflection$class.schemaFor(ScalaReflection.scala:630)
    at org.apache.spark.sql.catalyst.ScalaReflection$.schemaFor(ScalaReflection.scala:30)
    at org.apache.spark.sql.SQLContext.createDataFrame(SQLContext.scala:430)
    at org.apache.spark.ml.classification.NaiveBayesModel$NaiveBayesModelWriter.saveImpl(NaiveBayes.scala:264)
    at org.apache.spark.ml.util.MLWriter.save(ReadWrite.scala:90)
    at org.apache.spark.ml.util.MLWritable$class.save(ReadWrite.scala:130)
    at org.apache.spark.ml.classification.NaiveBayesModel.save(NaiveBayes.scala:130)
    at $line61.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1$$anonfun$apply$mcVI$sp$1.apply$mcV$sp(<console>:65)
    at $line61.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1$$anonfun$apply$mcVI$sp$1.apply(<console>:63)
    at $line61.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1$$anonfun$apply$mcVI$sp$1.apply(<console>:63)
    at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24)
    at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
java.lang.AssertionError: assertion failed: class MLWriter
    at scala.reflect.internal.pickling.UnPickler$Scan.readSymbolRef(UnPickler.scala:784)
    at scala.reflect.internal.pickling.UnPickler$Scan.readType(UnPickler.scala:346)
    at scala.reflect.internal.pickling.UnPickler$Scan$$anonfun$readTypeRef$1.apply(UnPickler.scala:792)
    at scala.reflect.internal.pickling.UnPickler$Scan$$anonfun$readTypeRef$1.apply(UnPickler.scala:792)
    at scala.reflect.internal.pickling.UnPickler$Scan.at(UnPickler.scala:171)
    at scala.reflect.internal.pickling.UnPickler$Scan.readTypeRef(UnPickler.scala:792)
    at scala.reflect.internal.pickling.UnPickler$Scan.readType(UnPickler.scala:366)
    at scala.reflect.internal.pickling.UnPickler$Scan$LazyTypeRef$$anonfun$34.apply(UnPickler.scala:855)
    at scala.reflect.internal.pickling.UnPickler$Scan$LazyTypeRef$$anonfun$34.apply(UnPickler.scala:855)
    at scala.reflect.internal.pickling.UnPickler$Scan.at(UnPickler.scala:171)
    at scala.reflect.internal.pickling.UnPickler$Scan$LazyTypeRef.complete(UnPickler.scala:855)
    at scala.reflect.internal.Symbols$Symbol.info(Symbols.scala:1231)
    at scala.reflect.internal.Symbols$Symbol.initialize(Symbols.scala:1374)
    at scala.reflect.internal.Symbols$Symbol.annotations(Symbols.scala:1581)
    at scala.reflect.internal.Symbols$Symbol.addAnnotation(Symbols.scala:1600)
    at scala.reflect.internal.pickling.UnPickler$Scan.readSymbolAnnotation(UnPickler.scala:491)
    at scala.reflect.internal.pickling.UnPickler$Scan.run(UnPickler.scala:88)
    at scala.reflect.internal.pickling.UnPickler.unpickle(UnPickler.scala:37)
    at scala.reflect.runtime.JavaMirrors$JavaMirror.unpickleClass(JavaMirrors.scala:565)
    at scala.reflect.runtime.SymbolLoaders$TopClassCompleter.complete(SymbolLoaders.scala:32)
    at scala.reflect.internal.Symbols$Symbol.info(Symbols.scala:1231)
    at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:43)
    at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:61)
    at scala.reflect.internal.Mirrors$RootsBase.staticModuleOrClass(Mirrors.scala:72)
    at scala.reflect.internal.Mirrors$RootsBase.staticClass(Mirrors.scala:119)
    at scala.reflect.internal.Mirrors$RootsBase.staticClass(Mirrors.scala:21)
    at org.apache.spark.ml.classification.NaiveBayesModel$NaiveBayesModelWriter$$typecreator1$1.apply(NaiveBayes.scala:264)
    at scala.reflect.api.TypeTags$WeakTypeTagImpl.tpe$lzycompute(TypeTags.scala:231)
    at scala.reflect.api.TypeTags$WeakTypeTagImpl.tpe(TypeTags.scala:231)
    at org.apache.spark.sql.catalyst.ScalaReflection$class.localTypeOf(ScalaReflection.scala:642)
    at org.apache.spark.sql.catalyst.ScalaReflection$.localTypeOf(ScalaReflection.scala:30)
    at org.apache.spark.sql.catalyst.ScalaReflection$class.schemaFor(ScalaReflection.scala:630)
    at org.apache.spark.sql.catalyst.ScalaReflection$.schemaFor(ScalaReflection.scala:30)
    at org.apache.spark.sql.SQLContext.createDataFrame(SQLContext.scala:430)
    at org.apache.spark.ml.classification.NaiveBayesModel$NaiveBayesModelWriter.saveImpl(NaiveBayes.scala:264)
    at org.apache.spark.ml.util.MLWriter.save(ReadWrite.scala:90)
    at org.apache.spark.ml.util.MLWritable$class.save(ReadWrite.scala:130)
    at org.apache.spark.ml.classification.NaiveBayesModel.save(NaiveBayes.scala:130)
    at $line61.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1$$anonfun$apply$mcVI$sp$1.apply$mcV$sp(<console>:65)
    at $line61.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1$$anonfun$apply$mcVI$sp$1.apply(<console>:63)
    at $line61.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1$$anonfun$apply$mcVI$sp$1.apply(<console>:63)
    at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24)
    at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
scala.reflect.internal.Symbols$CyclicReference: illegal cyclic reference involving class NaiveBayesModelWriter
    at scala.reflect.internal.Symbols$Symbol$$anonfun$info$3.apply(Symbols.scala:1220)
    at scala.reflect.internal.Symbols$Symbol$$anonfun$info$3.apply(Symbols.scala:1218)
    at scala.Function0$class.apply$mcV$sp(Function0.scala:40)
    at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
    at scala.reflect.internal.Symbols$Symbol.lock(Symbols.scala:482)
    at scala.reflect.internal.Symbols$Symbol.info(Symbols.scala:1218)
    at scala.reflect.internal.BuildUtils$BuildImpl.select(BuildUtils.scala:20)
    at scala.reflect.internal.BuildUtils$BuildImpl.selectType(BuildUtils.scala:11)
    at scala.reflect.internal.BuildUtils$BuildImpl.selectType(BuildUtils.scala:8)
    at org.apache.spark.ml.classification.NaiveBayesModel$NaiveBayesModelWriter$$typecreator1$1.apply(NaiveBayes.scala:264)
    at scala.reflect.api.TypeTags$WeakTypeTagImpl.tpe$lzycompute(TypeTags.scala:231)
    at scala.reflect.api.TypeTags$WeakTypeTagImpl.tpe(TypeTags.scala:231)
    at org.apache.spark.sql.catalyst.ScalaReflection$class.localTypeOf(ScalaReflection.scala:642)
    at org.apache.spark.sql.catalyst.ScalaReflection$.localTypeOf(ScalaReflection.scala:30)
    at org.apache.spark.sql.catalyst.ScalaReflection$class.schemaFor(ScalaReflection.scala:630)
    at org.apache.spark.sql.catalyst.ScalaReflection$.schemaFor(ScalaReflection.scala:30)
    at org.apache.spark.sql.SQLContext.createDataFrame(SQLContext.scala:430)
    at org.apache.spark.ml.classification.NaiveBayesModel$NaiveBayesModelWriter.saveImpl(NaiveBayes.scala:264)
    at org.apache.spark.ml.util.MLWriter.save(ReadWrite.scala:90)
    at org.apache.spark.ml.util.MLWritable$class.save(ReadWrite.scala:130)
    at org.apache.spark.ml.classification.NaiveBayesModel.save(NaiveBayes.scala:130)
    at $line61.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1$$anonfun$apply$mcVI$sp$1.apply$mcV$sp(<console>:65)
    at $line61.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1$$anonfun$apply$mcVI$sp$1.apply(<console>:63)
    at $line61.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1$$anonfun$apply$mcVI$sp$1.apply(<console>:63)
    at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24)
    at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
java.lang.RuntimeException: error reading Scala signature of org.apache.spark.ml.classification.NaiveBayesModel: assertion failed: class MLWriter
    at scala.reflect.internal.pickling.UnPickler.unpickle(UnPickler.scala:45)
    at scala.reflect.runtime.JavaMirrors$JavaMirror.unpickleClass(JavaMirrors.scala:565)
    at scala.reflect.runtime.SymbolLoaders$TopClassCompleter.complete(SymbolLoaders.scala:32)
    at scala.reflect.internal.Symbols$Symbol.info(Symbols.scala:1231)
    at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:43)
    at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:61)
    at scala.reflect.internal.Mirrors$RootsBase.staticModuleOrClass(Mirrors.scala:72)
    at scala.reflect.internal.Mirrors$RootsBase.staticClass(Mirrors.scala:119)
    at scala.reflect.internal.Mirrors$RootsBase.staticClass(Mirrors.scala:21)
    at org.apache.spark.ml.classification.NaiveBayesModel$NaiveBayesModelWriter$$typecreator1$1.apply(NaiveBayes.scala:264)
    at scala.reflect.api.TypeTags$WeakTypeTagImpl.tpe$lzycompute(TypeTags.scala:231)
    at scala.reflect.api.TypeTags$WeakTypeTagImpl.tpe(TypeTags.scala:231)
    at org.apache.spark.sql.catalyst.ScalaReflection$class.localTypeOf(ScalaReflection.scala:642)
    at org.apache.spark.sql.catalyst.ScalaReflection$.localTypeOf(ScalaReflection.scala:30)
    at org.apache.spark.sql.catalyst.ScalaReflection$class.schemaFor(ScalaReflection.scala:630)
    at org.apache.spark.sql.catalyst.ScalaReflection$.schemaFor(ScalaReflection.scala:30)
    at org.apache.spark.sql.SQLContext.createDataFrame(SQLContext.scala:430)
    at org.apache.spark.ml.classification.NaiveBayesModel$NaiveBayesModelWriter.saveImpl(NaiveBayes.scala:264)
    at org.apache.spark.ml.util.MLWriter.save(ReadWrite.scala:90)
    at org.apache.spark.ml.util.MLWritable$class.save(ReadWrite.scala:130)
    at org.apache.spark.ml.classification.NaiveBayesModel.save(NaiveBayes.scala:130)
    at $line61.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1$$anonfun$apply$mcVI$sp$1.apply$mcV$sp(<console>:65)
    at $line61.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1$$anonfun$apply$mcVI$sp$1.apply(<console>:63)
    at $line61.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1$$anonfun$apply$mcVI$sp$1.apply(<console>:63)
    at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24)
    at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)


text:
Q: query 'sharedWithMe=false' Invalid Value? Any variation of 'sharedWithMe=false' gives me the 400 error 'Invalid Value' in reference to the q parameter:
sharedWithMe=false
sharedWithMe!=true
not(sharedWithMe=true)
etc...

It's annoying, I want to get a list of all my files using the 'allDrives' corpora (User files + Shared Drives + Shared with me) but not include the files that have been shared with me.
There's simply no way to do this without breaking it down into separate requests (1 for root Drive with 'me' in owner query, and a request for each shared drive I'm a member of.
Does anyone know why it's doing this, or can suggest an elegant solution around this?

A: This is a bug
It seems that the documentation doesn't reflect the actual behavior for the sharedWithMe Search Query Term.
Here is a recent tracker that I found which reports this issue:
https://issuetracker.google.com/issues/173111277
Feel free to star it to indicate that you are affected too.
Reference
Subscribing by starring an Issue

A: Actually it is a bug that you can solve with this workaround:
Instead to use "sharedWithMe=false", consider to use "'me' in owners", even in "q" parameter

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to load background image in Next.JS I am new to next.js as I am trying to create website using nextjs I want to add background image on home page but its showing error.I am trying to add image in css style I have image available inside public folder below is my code:
index.js
const Home = () => {
  return(

Home page

  )
}

export default Home;

globals.css
html,
body {
  padding: 0;
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
    Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
}

* {
  box-sizing: border-box;
  margin: 0px;
  padding: 0px;
}

.sec1{
  background-image: url("../public/banner-food.jpg");
}

Someone let me know how can I resolve this issue.


text:
Q: Access all cells in TableView Hi I am tying to iterate through all the cells of my tableview but My tableview variable only let's me access the visible cells. so is there a way to declare the tableview without using the dequeuereusableCellWithIdentifier? or is there a way to iterate through all the cells?
Thanks,

A: To efficiently display a table, cells are used and reused depending on which ones are visible onscreen. In fact, this is what dequeuereusableCellWithIdentifier is suggesting - you specify different types of cells so they can be recycled later, as new ones are displayed and the components of offscreen ones are available for reuse.
You should define what needs to be changed or retrieve cells using table view cellForRowAtIndexPath.

A: You Are Already Accessing All The Cells In The TableView.
Note: I lied, two or more cells may be kept for quick reuse as well by tableView, but are not shown immediately.
At a time, a tableView only shows limited amount to cells to maintain performance and memory usage. So, for this purpose dequeuereusableCellWithIdentifier() method is utilised to let iOS handle the reuse of cells when necessary.
This way, no matter how large the dataSource, from 100,1000 to 1M, for the tableView, it will show the data in its cell smoothly and without any hiccups. That is why, you have limited cells visible and only those are the total cell used and reused by the tableView again and again.
By this definition, the total cell in use are the total visibleCells. So, when you are accessing the visibleCells, you are already accessing all the cells tableView has in use.
If you want to access all the data used by the cell, then please access the dataSource of tableView, not the visibleCells only.
Kind Regards,
Suman Adhikari


text:
Q: How to merge application.properties with application-default.properties and include in other test profiles with Spring Boot >2.4 We would like to merge src/main/resources/application.properties with additional default properties when running tests which in turn should be included by other (test) properties files activated via specific profiles in our Spring Boot application.
Up until Spring Boot 2.4 this worked quite well by having all common test properties in src/test/resources/application-default.properties to keep things DRY. Those were then automatically merged with the ones from src/main/resources/application.properties by Spring [1]. This allowed us to have our own set of default properties without requiring tests to specify an @ActiveProfiles("default").
Other (test) profiles could then have their own application-<profile>.properties with spring.profiles.include=default and then further extend the defaults.
With Spring Boot 2.4 I'm struggling with the new "rules":

*

*I can no longer load application-default.properties from application-<profile>.properties since spring.profiles.include is no longer allowed in non profile-specific documents [2].

*I don't want to introduce a src/test/resources/application.properties since I don't want to repeat everything from src/main/resources/application.properties. Also I don't want to load any activate any test-related profiles in the app's properties.
It looks like one solution could be to explicitly add spring.profiles.include=default to src/main/resources/application.properties to force the application to include the properties file with default properties which will work as before when it comes to running the actual application but consider src/test/resources/application-default.properties when running the tests.
Is this the way to go or are there smarter solutions to tackle this problem and still keep the properties free of redundancies?

A: spring.profiles.active=dev
add this config in application.properties file


text:
Q: Apache reverse proxy help needed I've got a somewhat unique (maybe not, but unique to me) architecture here for some home apps that variously require PHP 5.6 and PHP 7.1. This is the architecture recommended to me by /r/docker:

*

*One container acting as Apache Reverse Proxy that will ingest a DNS request on port 80 and then pass it to one of the below containers' ports.

*One container running Apache with PHP 5.6, listening on port 8081.

*One container running Apache with PHP 7.1, listening on port 8080.

I've been able to get domainname.com to work this way, by setting up the following domainname.com.conf in /etc/apache2/sites-available:
<VirtualHost *:80>

ServerName domainname.com

<Proxy *>

Allow from localhost

</Proxy>

ProxyPass "/" "http://public.ip.address:8080/" retry=0
ProxyPreserveHost On

</VirtualHost>

However, one of my subdomains needs to push to an application on the PHP 5.6 side. So I've set up this subdomain.domainname.com.conf:
<VirtualHost *:80>

ServerName subdomain.domainname.com

<Proxy *>

Allow from localhost

</Proxy>

ProxyPass "/" "http://public.ip.address:8081/subdomain/" retry=0
ProxyPreserveHost On

</VirtualHost>

Indeed, going directly to http://public.ip.address:8081/subdomain/ loads the application just fine, but for whatever reason, going to http://subdomain.domain.com gives a 503. Originally it was just showing the Apache on Ubuntu page, which is when I realized I needed to a2ensite and reload Apache, which has since been done.
The logs show this:
[Wed Jul 10 21:36:59.049131 2019] [proxy:error] [pid 2298:tid 139882856969984] (113)No route to host: AH00957: HTTP: attempt to connect to public.ip.address:8081 (3.220.176.240) failed
[Wed Jul 10 21:36:59.049182 2019] [proxy_http:error] [pid 2298:tid 139882856969984] [client 128.229.4.2:58611] AH01114: HTTP: failed to make connection to backend: public.ip.address

We know that the system can access 8080 just fine, so I'm not sure why it's struggling with this traffic. As mentioned above, hitting the ProxyPass URL directly from the outside loads the page fine, so traffic inbound to that container is fine. SELinux is disabled. This is in AWS and Security Groups are configured properly as far as I can tell (see: traffic works from outside).
Using the public IP address is the only way I've been able to get inter-container traffic to work, because using Docker's bridge IPs didn't work previously.
On the old system, when all my apps were just PHP 5.6, I had a standard VirtualHost statement that just took in the subdomain.domain.com and pointed it to a specific DocumentRoot. I can't do that here since the reverse proxy container needs to hand off the traffic to the container with the right PHP version.
Many thanks for any tips or tricks here.


text:
Q: Show column that column data is not NULL based on row Book Table
bookID    tripNo
b01         t01
b02         t02
b03         t03

Trip Table
tripNo  bookID  seat1     seat1    seat2    seat3  seat4    seat5    seat6     seat7    seat8    seat9    seat10    seat11    seat11
t01      b01     booked   booked   NULL     NULL   booked   booked   booked     booked  NULL    NULL        NULL    booked      booked
t02      b02     NULL     booked    NULL    NULL   booked   NULL     booked     NULL    NULL    booked      NULL    booked      booked
t03      b03     booked   booked   NULL     booked   booked   booked   booked   booked  NULL    booked      booked  booked      booked

How do I make it like show all the seat that is not NULL?
Expected Result
bookID   Booked
b01       seat1,seat2,seat5,seat6,seat7,seat12,seat13
b02       seat2,seat5,seat7,seat10,seat12,seat13

A: A SQL query returns a fixed set of columns, so you cannot conditionally remove a column.  So, you can't really do what you want, unless you resort to dynamic SQL.
Your trip table has an awkward format.  You should really have a table TripSeats with one row per trip and per seat.
If each trip has exactly 11 seats, then you can create them when the trip is created -- just populate them with NULL values.
If you did this, it would be very easy to extract the information you want.


text:
Q: finding out common words in various documents python I have a csv file which is something like this:
 book_store_id  book_price   name

 1              200.0        foo
 1              320.0        bar
 2              220.0        foobar
 2              280.0        foo

So.. this is a huge list..
Now I am trying to find out that if the input is "foo"
then since bookstore id 1 has "foo" marked lowest price, then I want to return "book_store" 1
Now How I am doing this is creating an inverted index which returns something like
foo:1,2
bar:1
foobar:2

and so on, and then a seperate dictionary where I am maintaining the price of book in a store.. but is this the best way out to solve this out.
What is the most efficient way to solve this problem in python?

A: I would create a third data structure (python dict, or database table or whatever).
the data structures key should be the name (assuming name is unique).
The value this "name" key points at should be the minimum price.
Every time you insert a new book, or update the price of a book, look up the books minimum price in the third data structure, if it is less than the minimum price, set the new minimum price.
Don't forget, if you delete a book, or increase its price, make sure you update the minimum.
(you could add another column so each book has a boolean "is current minimum". Then on price increase you only need to update the minimum if this is true.
The problem is, then you need to find the next best minimum when you remove the old minimum.
This is where it's good to have a heapq
python has a nice implementation of heapq here:
http://docs.python.org/library/heapq.html
Otherwise you have to loop through all values to find the new minimum upon every price increase, or you have to store the 5 best prices each time, say.
have fun :)

A: It all depends on the amount of data you are dealing with. If the amount is not too high, then what you are doing is just fine.


text:
Q: How to check if tuple has element? I have an exception from which I'm trying to get args, but if fails.
print hasattr(e, 'args')
print type(e.args)
print hasattr(e.args, '1')
print hasattr(e.args, '0')
print '1' in e.args
print '0' in e.args
print 1 in e.args
print 0 in e.args
print e.args[0]
print e.args[1]

This prints:
True
<type 'tuple'>
False
False
False
False
False
False
Devices not found
4

A: You simply use the in operator:
>>> try:
...   raise Exception('spam', 'eggs')
... except Exception as inst:
...   print inst.args
...   print 'spam' in inst.args
...
('spam', 'eggs')
True

If your code is returning False then most likely 1 wasn't an argument to the exception. Perhaps post the code where the exception was raised.
You can check if the tuple has positions 0 to N by doing len.

A: You can check the length of your tuple:
t = 1, 2, 3,
if len(t) >= 1:
    value = t[0]    # no error there

...or you can just check for an IndexError, which I'd say is more pythonic:
t = 1, 2, 3,
try:
    value = t[4]
except IndexError:
    # handle error case
    pass

The latter is a concept named EAFP: Easier to ask for forgiveness than permission, which is a well known and common Python coding style.


text:
Q: Pass data between UserForms Within Excel VBA I have a User Form similar to the following where the user enters an ID number and then the details are displayed on the user form:
Private Sub btnIDNo_Click()
Dim IDNo As Long
If txtIDNo.Text <> "" Then
    If IsNumeric(txtIDNo.Text) = True Then
        lblError.Caption = ""
        IDNo = txtIDNo.Text
        Worksheets("Details").Activate
        Range("B4").Select
        While ActiveCell.Value <> "" And ActiveCell.Value <> IDNo
            ActiveCell.Offset(1, 0).Select
        Wend
        If ActiveCell.Value = IDNo Then
            txtName.Value = ActiveCell.Offset(0, 1).Value
            txtPhone.Value = ActiveCell.Offset(0, 2).Value
        Else
            lblError.Caption = "Cannot find ID nummber"
        End If
    Else
        lblError.Caption = "Please enter the ID Number in numeric form"
    End If
End If
End Sub

On the Details User Form, I have an "Edit" button. Clicking the "Edit" button would open another user form where the user can change the details of that ID number, but obviously not the ID number itself. To do this, I need to pass the ID number from the Details User Form to the Edit User Form. Is there a way of doing this?
The bottom on the Show Details User Form to open the Edit User Form is similar to the following:
Private Sub CommandButton1_Click()
Dim IDNo As Long
If txtIDNo.Text <> "" Then
    If IsNumeric(txtIDNo.Text) = True Then
        lblError.Caption = ""
        IDNo= txtIDNo.Text
        ufmEditDetails.Show
        ufmShowDetails.Hide
    Else
        lblError.Caption = "Please enter the ID Number in numeric form"
    End If
Range("B4").Select
End If
End Sub

I have already looked at the following links but they don't seem to help:
http://www.mrexcel.com/forum/excel-questions/671964-visual-basic-applications-pass-variables-between-user-forms.html
http://gregmaxey.mvps.org/word_tip_pages/userform_pass_data.html
http://peltiertech.com/Excel/PropertyProcedures.html

A: There are many many ways... Here are some...
Way 1

*

*Declare a Public Variable in a Module

*Assign to that variable in Userform1 and then launch Userform2. This variable will retain it's value. Example

In Userform1
Private Sub CommandButton1_Click()
    MyVal = "Sid"
    UserForm2.Show
End Sub

In Userform2
Private Sub CommandButton1_Click()
    MsgBox MyVal
End Sub

In Module
Public MyVal

Way 2
Use the .Tag property of the userform
In Userform1
Private Sub CommandButton1_Click()
    UserForm2.Tag = "Sid"
    UserForm2.Show
End Sub

In Userform2
Private Sub CommandButton1_Click()
    MsgBox Me.Tag
End Sub

Way 3
Add a Label in Userform2 and set it's visible property to False
In Userform1
Private Sub CommandButton1_Click()
    UserForm2.Label1.Caption = "Sid"
    UserForm2.Show
End Sub

In Userform2
Private Sub CommandButton1_Click()
    MsgBox Label1.Caption
End Sub

A: There are serveral ways to solve this problem.
The one that I use is declare global or public variable in module
Example:
Public commonVariable As String

then in userform you can assign or retrieve value from this variable.
For example
in userform1:
Private Sub btnIDNo_Click()
    commonVariable = "UserId"
End Sub

in UserForm2:
Private Sub CommandButton1_Click()
    me.txtIDNo.Text = commonVariable
End Sub

A: The most simplest way is:
UserForm2.TxtIDNo.Text = UserForm1.txtIDNo.Text


text:
Q: pine scrip logic confusion confessed in pine script logic
hi im trying to convert pine script to mql4 , my question is
what is this statement mean "x-x[length]" , x[length] is the the 14th element of the array x but what is x , i suppose it is the whole array but this make no sense there is no comparison between one element and whole array any
 help will be appreciated thanks

//@version=2
study("Pseudo Polynomial Channel",overlay=true)
length = input(14),morph = input(0.9,minval=0,maxval=1),mult = input(1.),flatten = input(1.)
//----
x = n
y = close
m(a,b) =>
    p = morph * a + (1-morph) * b
k = nz(m(k[length],y),y) + (x-x[length])/(x[length*2]-x[length]) * (nz(m(k[length*2],y),y) - nz(m(k[length],y),y))/flatten
k1 = sma(k,length)
er = cum(abs(y-k1))/n * mult
//----
a = k1 + er
b = k1 - er
//----
A = plot(a,color=#2196f3,linewidth=2,transp=0)
plot(k1,color=#e65100,linewidth=2,transp=0)
B = plot(b,color=#ff1100,linewidth=2,transp=0)
fill(A,B,#2196f3,transp=95)

A: x is the equivalent of x[0], so the most recent element of the time series. Note that Pine uses time series—not arrays—which entails the elements referred to with the [ ] history-referencing operator vary on each bar. See the usrman on the subject.


text:
Q: Memcached server consolidation issue on Rails 2.3: unable to find server during initialization I have a Ruby on Rails 2.3.10 application that has an API running on one server and the application on another. Due to the nature of the app, the API, and the typical user flow; I need to centralize our caching. Currently I have memcached (1.4.2) running on each server (Ubuntu 10.04.1 LTS).
When I try moving to a centralized memcached server, I consistently get this error both in production and development:
Read error: #<RuntimeError: #<ActionController::Session::MemCacheStore:0x108cb5dc8> unable to find server during initialization.

My development.rb and production.rb configs look like this:
config.cache_store = :mem_cache_store, 'XX.XX.XX.XXX:11211'

I already configured my iptables and opened up port 11211. I can also then telnet into that server from my local machine and the servers.
Everything runs fine using this
config.cache_store = :mem_cache_store

as long as memcached is running on the localhost.
I've also tried this using the last version of the Dalli gem that supports Rails 2.3 and get the same error.
Any ideas? I've searched everywhere and it looks like I'm configured correctly, but obviously something is wrong here.


text:
Q: KSOAP2 double ID exception in android I am using KSOAP2 in my android application, and when I try to perform a particular webservice request, I got this "double ID" exception. Where i'am going wrong ? Please help me.
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(SOAP_ADDRESS);

        SoapPrimitive response = null;
        try {
          androidHttpTransport.call(SOAP_ACTION, envelope); //<<--- Getting exception here
          response = (SoapPrimitive)envelope.getResponse();

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), e+"", Toast.LENGTH_LONG).show();
        }

StackTrace :
java.lang.RuntimeException: double ID
at org.ksoap2.serialization.SoapSerializationEnvelope.read(SoapSerializationEnvelope.java:407)
at org.ksoap2.serialization.SoapSerializationEnvelope.readUnknown(SoapSerializationEnvelope.java:273)
 at org.ksoap2.serialization.SoapSerializationEnvelope.read(SoapSerializationEnvelope.java:389)
at org.ksoap2.serialization.SoapSerializationEnvelope.readUnknown(SoapSerializationEnvelope.java:273)
at org.ksoap2.serialization.SoapSerializationEnvelope.read(SoapSerializationEnvelope.java:389)
at org.ksoap2.serialization.SoapSerializationEnvelope.readUnknown(SoapSerializationEnvelope.java:273)
 at org.ksoap2.serialization.SoapSerializationEnvelope.read(SoapSerializationEnvelope.java:389)
at org.ksoap2.serialization.SoapSerializationEnvelope.readUnknown(SoapSerializationEnvelope.java:273)
 at org.ksoap2.serialization.SoapSerializationEnvelope.read(SoapSerializationEnvelope.java:389)
 at org.ksoap2.serialization.SoapSerializationEnvelope.parseBody(SoapSerializationEnvelope.java:151)
 at org.ksoap2.SoapEnvelope.parse(SoapEnvelope.java:140)
 at org.ksoap2.transport.Transport.parseResponse(Transport.java:116)
at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:235)
at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:114)
at com.menthatech.soap_login_test.SampleSoapTest_LoginActivity.onClick(SampleSoapTest_LoginActivity.java:94)
at android.view.View.performClick(View.java:2408)
at android.view.View$PerformClick.run(View.java:8816)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)

A: I had this exception today... I don't know if your case is the same...
In my case was because the Webservice (C#) return a Dataset, but, I work that changing some columns and return then, so, I have 2 Tables with same Id. with diffgr:before tag.
So, when you work your dataset just put the code before your Webservice return the object:
ds.AcceptChanges();
:-)

A: Here is nice example that might help you: Click Here
Here is my quick fix to this issue:
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
            SoapEnvelope.VER11);

SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
soapEnvelope.setOutputSoapObject(Request);
soapEnvelope.dotNet = true;

List<Integer> companies =  new ArrayList<Integer>();
companies.add(65);
companies.add(66);
companies.add(67);

Request.addProperty("name", "test1");
SoapObject soapCompanies = new SoapObject(NAMESPACE, "companies");
for (Integer i : companies){
    soapCompanies.addProperty("int", i);
}
Request.addSoapObject(soapCompanies);

Output XML:
<n0:companies xmlns:n0 = "http://tempuri.org/">
            <int i:type = "d:int">65</int>
            <int i:type = "d:int">66</int>
            <int i:type = "d:int">67</int>
</n0:companies>
<name i:type = "d:string">test1</name>

A: I want to record different solutions for people who encounter this problem....
Because call the DataSet data back to XML use the "diffgram".
The "double ID" error is <diffgr:id> repeate,have the same ID
e.g:
A Table have "Table"、"Table1" (if your dataSet select more table)
if "A" have 11 records and show to the XML is
<Table diffgr:id="Table1">、<Table diffgr:id="Table2">.........<Table diffgr:id="Table11">
if B have 10 records and show to the XML is
<Table1 diffgr:id="Table11">、<Table diffgr:id="Table12">.........<Table diffgr:id="Table110">
SO.
You can see the diffgr:id="Table11" repeat. That is why have "double Id" error

Solution
change the DataSet Table name
SqlDataAdapter.Fill(DataSet);
DataSet.Tables[0].TableName = "Table_";
DataSet.Tables[1].TableName = "Table1_";
DataSet.AcceptChanges();


text:
Q: How to set Flink TaskManager Total Flink Memory? I'm wanting to run quite a number of PyFlink jobs on Kubernetes, where the amount of state and number of events being processed is small and therefore I'd like to use as little memory in my clusters as possible so I can bin pack most efficiently. I'm running a Flink cluster per job. I'm currently trying to see how small I can make the memory settings.
I set taskmanager.memory.process.size: 512mb in my Flink config. The container is being started with requested memory of 512Mi.
When my TaskManager starts up, I get an error message:

IllegalConfigurationException: Sum of configured Framework Heap Memory
(128mb), Framework Off-Heap Memory (128mb), Task Off-Heap Memory (0
bytes), Managed Memory (25.6mb) and Network Memory (64mb) exceed
configured Total Flink Memory (64mb).

My understanding of the docs (https://nightlies.apache.org/flink/flink-docs-release-1.14/docs/deployment/memory/mem_setup_tm/) is that I should just need to set taskmanager.memory.process.size. Where is the 64mb figure coming from which makes up the Total Flink Memory? How do I change this?


text:
Q: MongoDB - Embeded Version for "Voting with Atomic Operators" I read the Voting with Atomic Operators article. In this article, the voters field is an array of ObjectIds. But I would like to store the voters as an array of embedded documents with the following format:
{
  user: ObjectId,
  date: Date,
  isDownvote: Boolean,  // If false, it's an upvote.
}

The user can upvote or downvote the post just like the voting system provided by Stack Overflow. So, for example, when the user want to upvote a post, there are cases to consider:

*

*If a downvote by the user already exists, then update the vote's isDownvote to false.

*Else push a new vote with isDownvote being false.

How can I push/pull a vote in single query with this format of votes?

A: $push : { voters : {
  user: ObjectId,
  date: Date
}}

A: Another way of doing this fully atomically is:
db.posts.update({'_id':post_id}, {
    '$pull': {'votes.user':ObjectId},
    '$addToSet': {votes: {
        user: objectId,
        date: Date,
        isdownvote: isdownvote
    }}
})

As already said, there is no upsert for subdocuments so this kind of cheats and deletes the old vote and writes it again. The date field should still be ok because if the user votes again then the date field should change to the last time that user voted so in my mind that part makes sense.


text:
Q: Short story where the hero quotes "Full Fathom Five Thy Father Lies" while having an underwater adventure I read this in a science fiction anthology which I checked out from a public library in Indiana sometime in the early 1980s. I'm thinking no later than 1985. I don't know how old the book was when I saw it, nor when the story in question was first published. I may have run across a copy again in the 1990s, and thus refreshed my memory a bit, but I'm not sure of that. I remember the plot pretty well, but nothing about the author's name, nor that of the main character.
Plot Points:

*

*The main character is a scuba diver or something similar. (The word "scuba" may not have been applied to whatever gear he was wearing.) Many years ago, his beloved brother drowned -- I forget whether the brother had been diving at the time, or if "his ship was sunk in a hurricane," or what -- but that doesn't keep the protagonist from enjoying himself down below the surface of the water from time to time.

*Early on in the story, while exploring underwater, the protagonist spots a human skeleton which appears to have been resting in one place for a long time. The protagonist immediately remembers some words sung by the character Ariel in Shakespeare's The Tempest. (A play which I had never read or watched, at that time, so this story was my first encounter with these memorable words.)

Full fathom five thy father lies;
  Of his bones are coral made;
  Those are pearls that were his eyes:
  Nothing of him that doth fade,
  But doth suffer a sea-change
  Into something rich and strange.
  Sea-nymphs hourly ring his knell:
  Ding-dong.
  Hark! Now I hear them – Ding-dong, bell.

The protagonist then mentally compares the descriptive details from the poetry to the underwater tableau in front of him, thinking such things as "Full fathom five? Well, not quite that deep," and so forth. I think it may have been explicitly stated that this couldn't possibly be the skeleton of his drowned brother.

*Thus far, the story could be happening in "the real world." But now it gets weird. The protagonist comes face-to-face (using the word "face" somewhat loosely) with a humanoid-shaped creature or conglomeration which, I think, appears to have been made from various smaller units of marine organisms -- perhaps a fish here, some seaweed there, and so forth, as if someone were assembling a man-sized jigsaw puzzle out of biological odds and ends, but not making much effort to create a convincing imitation of a human body. This creature (assuming, arbitrarily, that we should regard it as a single entity) stays underwater throughout the story, but somehow manages to persuade the protagonist to follow it further out from shore with the intent of being helpful.

*I think something is done which (temporarily) allows the protagonist to breathe comfortably while underwater, so that he won't be facing a hard-and-fast time limit, mandated by the capacity of an air tank, during his attempts to be helpful to whatever society the "guide" represents. But I may be confusing that part with a plot device from another tale of underwater adventure which I read as a boy.

*The protagonist fights some sort of sea-monster which may have resembled a giant clam, and kills it. I can't for the life of me remember what was implied about why the sea-dwellers who sent that "messenger" couldn't have ganged up on the monster and done the dirty work themselves. Perhaps the clam was powerfully telepathic, but less effective against the brains of land-based organisms? (That's more of a wild guess than anything else.)

*Having done this, the protagonist is then guided to where a giant sea-shell opens up to reveal what appears to be, more or less, a beautiful young woman -- water-breathing, but looking much closer to "human" than does the original guide-creature -- and the protagonist gets the distinct impression, perhaps via limited psychic communication, that he is supposed to mate with her, right here and now! He wonders if this is supposed to be a special reward for his valiant service, or one last favor they are requesting of him (if the underwater civilization has plans for his genes), or something else. But whatever the motives behind this offer may be, he doesn't feel comfortable with the idea of a one-night stand with a mysterious, perhaps genetically-engineered, marine creature that only resembles a member of his own species . . . and so he turns down this rare opportunity.

*That decision does not go over well. In fact, it stirs up a great deal of animosity. The protagonist starts trying to fight his way back up to the surface, but now he is having serious trouble breathing. As I said, I'm not sure if he was being "magically" aided in breathing underwater before, but if he was, the magic is now being revoked. Or, if there wasn't any magic, then maybe someone or something rips away some of his scuba gear. Either way, he figures he'll be dead before he makes it back up to the surface and over to dry land. Then he feels a strong arm wrap itself around his torso from behind him, and someone essentially carries him up to the surface and shoves him up onto a beach, but disappears below the waves before the protagonist can turn around and get a good look at the rescuer.

*Someone else -- an ordinary land-dwelling human being, this time -- comes along and speaks to the protagonist, asking about what has just happened. Our hero says something along these lines: "I wouldn't have made it back if I hadn't been helped. I think . . . it was my brother!"
I don't remember whether the author's name was familiar to me at the time I first read this. It may have been one of those cases where an author only dabbled in SF/Fantasy a few times in his life. I'm sure the story is not collected in any of the many volumes I own that collect much of the shorter fiction of such big-name authors as Poul Anderson, Roger Zelazny, and Gordon R. Dickson.
I did make some effort to Google for this story before taking the trouble to type out that plot summary. As a result, I'm certain it is not the story "Full Fathom Five My Father Lies" by Rand B. Lee (the answer to this old question). Nor does it seem to be any of the fictional works which Wikipedia, on the following pages, lists as having recycled some or all of those famous lines by Shakespeare: Ariel's Song and Full fathom five (catchphrase).
With that said, does anyone recognize this from my description?

A: The Sea Change by Arthur Jean Cox looks to be possibility.
I found an excerpt of the story in
The Best from Fantasy and Science Fiction Seventeenth Series in Google Books searching for skeleton "pearls that were his eyes" (the third search result).
natsscifiguide.com describes it as:
A man drowns at sea, but is resurrected in an underwater "hive."


text:
Q: Android fragments: container variable in onCreateView is null i have an application that is only fragment based, and actually (i'm just creating basic content) i have only one fragment, declared directly into the layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <fragment
        android:name="com.italialinux.fragments.MainFragment"
        android:id="@+id/main_screen_fragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        />

</FrameLayout>

And this layout is loaded inside main activity, with the following code:
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_screen);
    }
}

And the MainFragment class is the following:
public class MainFragment extends Fragment {

    final static private long ONE_SECOND = 1000;
    final static private long TWENTY_SECONDS = ONE_SECOND * 20;

    private final static String TAG = "MainFragment";
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        View view = inflater.inflate(R.layout.new_reminder, container, false);
        return view;
    }

And the new_reminder layout contains just two EditText and several labels.
The problem is that i cannot inflate the layout, since the container variable passed in onCreateView is null.
I saw many questions on SO, like the following:
Android Fragment is given a null container in onCreateView()
And all says that i need to use a transaction, but what i don't understood is:
if i have a fragment that is immutable, in a layout, and doesn't need to change (like in that case, and like in many examples where you have a ListFragment that contains a list of items), how i can inflate the layout inside the current view?
With ListFragment it works, but what if i don't want to use it?
The onCreateView method is called correctly.

A: In your main layout, try using android:layout_width="match_parent" instead of android:layout_width="0dp".
And you shouldn't be calling onSaveInstanceState(savedInstanceState) in onCreate; it is called by the framework when your fragment is going down to allow it to save its state.


text:
Q: Can't set id on img Tag using puppeteer I am trying to set id's to all  tags of a page, my loop runs its iterations completely but some of the  tags doesn't get the id's as can be seen in the below image:

Here is my code:
const browser = await puppeteer.launch({
    args: [
        '--no-sandbox',
    ],
  });
  const page = await browser.newPage();
  await page.setViewport({ width: 1440, height: 10000 })
  await page.goto(url, {
        waitUntil: 'networkidle2',
        timeout: 0,
  });

await page.evaluate(() => {
const images = document.getElementsByTagName('img') || []
    for (let i = 0; i < images.length; i++) {
        document.getElementsByTagName('img')[i].id = `${i}`
        document.getElementsByTagName('img')[i].src = document.getElementsByTagName('img')[i].getAttribute('src')?.startsWith('https') ?
        document.getElementsByTagName('img')[i].getAttribute('src')! :
        `https://leza.notion.site${document.getElementsByTagName('img')[i].getAttribute('src')}`
    }
})

Am I missing anything? Any help would be highly appreciated!
I keep getting this warning log
PAGE LOG: %c NOTION%c WARNING %c background: black; color: white; background: black; color: orange font-weight: normal Reverting mutation of attribute src from "/image/https%3A%2F%2Fraw.githubusercontent.com%2Feirikmadland%2Fnotion-icons%2Fmaster%2Fv5%2Ficon3%2Ful-file-search-alt.svg?table=block&id=db9359ba-4fcd-4a24-9744-8514d7810939&userId=&cache=v2" -> "https://leza.notion.site/image/https%3A%2F%2Fraw.githubusercontent.com%2Feirikmadland%2Fnotion-icons%2Fmaster%2Fv5%2Ficon3%2Ful-file-search-alt.svg?table=block&id=db9359ba-4fcd-4a24-9744-8514d7810939&userId=&cache=v2" in component  JSHandle@object

A: Instead of
await page.evaluate(() => {
    const images = document.getElementsByTagName('img') || []

try using:
await page.$eval('.img', (images) => { /* DO STUFF... */ });

So the following code should work:
await page.$eval('.img', (images) => {
    for (let i = 0; i < images.length; i++) {
        const currentImage = images[i];
        const targetImageId = `${i}`;
        const currentImageSrc = currentImage.getAttribute('src');
        const targetImageSrc = currentImageSrc?.startsWith('https')
            ? currentImageSrc!
            : `https://leza.notion.site${currentImageSrc}`;

        currentImage.setAttribute("id", targetImageId);
        currentImage.setAttribute("src", targetImageSrc);
    }
});

Note that your url will look something like the following, which are probably not correct URLs for the two 1st ones:

https://leza.notion.sitehttp://www.gravatar.com/avatar/8947787d4067fa6e66e485bfc72233e4?s=48&d=identicon&r=PG&f=1

or

https://leza.notion.sitemyimage.png

or

https://leza.notion.sitemy/image.png


text:
Q: Does Visual Studio 2015 Community support remote profiling? My system:
Server: Windows 10 Pro 1511 10586.36 Microsoft Visual Studio 2015 Community 14.0.24720.00 Update 1
Client: Windows 10 IoT Core (build 10586) Raspberry Pi 2.
My question:
I would like to profile C++ native application on Raspberry Pi 2.
But i was unable to find how exactly to do it.
Default profiling launch wizard works ok when using the application which is deployed locally but doesn't work for the case when application deployed remotely.
Here is the link Visual studio 2012 profiling remotely debugged process which is about VS 2012 actually, but it seems that even for 2015 problem is the same.
So is there a direct way to use VS remote profiling tool similar to the local one?


text:
Q: Google maps JS API shows blue focus border Google Maps JS API began displaying blue focus border around the map after switching to another browser tab and then go back. Once the map is clicked the border vanishes.
The element with the border is generated by Gmaps and within their DOM. Border seems to show only in full-page map display.

Tracing Gmap DOM show a border at child of gm-style: (div.gm-style > div)

The opacity: 0 is dynamic and change to opacity: 1 after click to another browser tab.
Why Gmaps JS API like this works? Any idea how to clearly remove this square from viewpoint?
Edit:

*

*blue square shows in Chrome 89 && Mozilla 86

*Steps: open js fiddle link -> focus the map (easy roll map from side to side) -> change browser tab -> go back to tab with jsfiddle example -> blue square
JSFiddle example
Opened issue as bug:
Google Issuetracker

A: I met the same issue,  the CSS works:
.gm-style iframe + div { border:none!important; }

A: Issue closed as a google maps bug. Bug will be fixed in next GMApi release.
Issuetracker Google


text:
Q: Sending push notification from php to android app working in android app development using Ionic framework as frontend and php as a backend. can someone suggest your points how can we achieve this.
am ready with sample app (followed the below steps)
1. created sample app using below comments
ionic start devdactic-android-push
cd devdactic-android-push
ionic add ionic-platform-web-client
ionic plugin add phonegap-plugin-push
ionic io init

2. updated app.js as below
$ionicPlatform.ready(function() {
    $ionicPlatform.ready(function() {
         var push = new Ionic.Push({
          "debug": true
         });

         push.register(function(token) {
           console.log("Device token:",token.token);
        });
     });
  });

*run the below commend to get the device token
Ionic serve

*I could get the device token in cosole

*I need to get device token of real android phone
so prepared the apk file
ionic platform add android
ionic build android

*Install the generated apk in phone

*got the device token of real device from console( used the chrome inspector to check android app console)

*created one project in google cloud platform
so i have both project number(GCM console) and device token
project id - 257581368411
Device Token - DEV-e51b469d-9024-4d88-a0a9-1147f45b13f4
how to send notification from PHP script using above values?
and below is my system information:
Cordova CLI: 6.1.1
Ionic Version: 1.2.4
Ionic CLI Version: 1.7.14
Ionic App Lib Version: 0.7.0
OS: Windows 7 SP1
Node Version: v5.0.0

A: You can use the script below to send push notifications
Source: https://gist.github.com/prime31/5675017
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'YOUR-API-ACCESS-KEY-GOES-HERE' );

$registrationIds = array( $_GET['id'] );

// prep the bundle
$msg = array
(
    'message'   => 'here is a message. message',
    'title'     => 'This is a title. title',
    'subtitle'  => 'This is a subtitle. subtitle',
    'tickerText'    => 'Ticker text here...Ticker text here...Ticker text here',
    'vibrate'   => 1,
    'sound'     => 1,
    'largeIcon' => 'large_icon',
    'smallIcon' => 'small_icon'
);
$fields = array
(
    'registration_ids'  => $registrationIds,
    'data'          => $msg
);

$headers = array
(
    'Authorization: key=' . API_ACCESS_KEY,
    'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;


text:
Q: How to test user has claims after _signInManager.SignInWithClaimsAsync is called in ASP.NET Core I want to test that user has assigned claims after it is logged in.
I made integration tests and I realized that httpContext.User.Identity.IsAuthenticated is true only after response is set to client (Set-Cookie header is sent)
So my idea was to get that cookie and send another request. That works but how do I get claims? My ideas was to get it using _appFactory.Services.GetRequuiredService<IHttpContextAccessor>() but HttpContext property of that service is always null.
Here is code to make it even more clear:
   //Arrange
      var httpClient = _appFactory.CreateClient();
      var signInManager = _appFactory.Services.GetRequiredService<SignInManager<User>>();
    var userManager = _appFactory.Services.GetRequiredService<UserManager<User>>();
    var authService = _appFactory.Services.GetRequiredService<IAuthService>();

     **var httpContextAccessor= _appFactory.Services.GetRequiredService<IHttpContextAccessor>();**

    var controller = new AuthController(signInManager, userManager, authService);
    var aspNetCookieName = ".AspNetCore.Identity.Application";
    var httpContext = new DefaultHttpContext()
    {
        RequestServices = _appFactory.Services,

    };

    controller.ControllerContext.HttpContext = httpContext;
    signInManager.Context = httpContext;

    //Act

    var requestMessage = new HttpRequestMessage(HttpMethod.Get, "/users"); //first request
    HttpResponseMessage responseHomePageBeforeLogin = await httpClient.SendAsync(requestMessage);

    _ = await controller.Login(new Models.ViewModel.LoginViewModel()
    {
        Email = TestsConstants.DEFAULT_USER.Email,
        Password = TestsConstants.DEFAULT_USER.Password
    });

    _ = controller.Response.Headers.TryGetValue("Set-Cookie", out StringValues value);
    var cookie = value.FirstOrDefault();
    requestMessage = new HttpRequestMessage(HttpMethod.Get, "/users");
    requestMessage.Headers.Add("Cookie", cookie);
    HttpResponseMessage responseHomePage = await httpClient.SendAsync(requestMessage);

  **var httpContext=httpContextAccessor.HttpContext;//here is null httpContext**
    //Assert
  Assert.IsNotNull(responseHomePage);
        Assert.AreEqual("/users", responseHomePage!.RequestMessage!.RequestUri!.LocalPath);
        Assert.IsNotNull(value);
        Assert.IsTrue(value.FirstOrDefault()!.Contains(aspNetCookieName));


text:
Q: How is it possible to change whole style in different devices? I'm working on a web app using version 4 of Angular.
I want to show a different style for smaller devices and large screen devices. For example, when a user is browsing on mobile size device, the page will be very long which is not good in UX point, but it would be better if I could convert that long page to tabs that user can swipe between them (like menus). Is there any known way by bootstrap or any technique in Angular 4 to helps me for that?

A: You can use media query and either create a separate file for each:
//index.html

<link rel="stylesheet" media="(max-width: 360px)" href="mobile.css" />
<link rel="stylesheet" media="(min-width: 361px) and (max-width: 1080px)" href="tablet.css" />
<link rel="stylesheet" media="(min-width: 1081px)" href="desktop.css" />

or create everything in one file:
//style.css

@media (max-width: 360px) {
  //Mobile
}
@media (min-width: 361px) and (max-width: 1080px) {
  //Tablet
}
@media (min-width: 1081px) {
  //Desktop
}

See also: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries


text:
Q: Bounding the denominator in the canonical bundle formula My question concerns with Theorem 3.1 in the paper "A canonical bundle formula" by Fujino and Mori.
The theorem claims the following:
Suppose $X \to C$ is a fiberation whose general fiber $F$ has Kodaira dimension $0$ and suppose $b$ is the least integer such that $|bK_F| \neq 0$. Let $E \to F$ be the cyclic cover associated to the $b$-th root of the unique element of $|bK_F|$, and $\bar E$ be a smooth model of $E$. Let $B=h^{\dim E}(E, \mathbb C)$ be the middle Betti number, and $N={\rm lcm}\{y \in \mathbb Z_{> 0} \mid \phi(y) \leq B\}$, where $$\phi(y):=\#\{z \in \mathbb Z_{> 0}\mid z \leq y, {\rm gcd}(z,y)=1\}$$ is the Euler function. Then in the canonical bundle formula, the semistable part $L^{ss}_{X/C}$ (see Corollary 2.5 in loc.cit.) satisfies the property that $NL^{ss}_{X/C}$ is an integral divisor.
This result is proved roughly along the following lines (see 3.2-3.8 in loc.cit.):

*

*Cutting by hypersurfaces, we can assume $C$ is a curve.

*Let $\bar Z \to C$ be a smooth model such that the general fiber is $\bar E$.

*Let $\pi: C' \to C$ be a Galois cover with Galois group $G$, and $\bar Z \times_C C'$ has semistable resolution $\bar h': \bar Z' \to C'$.

*One knows that $\pi^*L_{Z/C}^{ss}$ is a Weil divisor and $\mathcal{O}(NL_{Z/C}^{ss})=\mathcal (\pi_*\mathcal{O}(N\pi^*L_{Z/C}^{ss}))^{G}$.

*For $P' \in C'$, let $G_{P'}$ be the stabilizer of $G$ and $G_{P'}$ acts on $\mathcal{O}(\pi^*L_{Z/C}^{ss})$ through a character $\chi_{P'}: G_{P'} \to \mathbb C^*$.

*Let $e$ be the ramification index at $P'$, then there exists a homomorphism $G_{P'} \to \mu_{e}$, where $\mu_e$ is the group of $e$-th root of unity. Let $H'$ be the canonical extension of $\mathcal{O}_{C_o'}\otimes (R^{m}(\bar{h}_o')_*{\mathbb C_{\bar{Z_o}'}})$, where $m=\dim E$ and $\bar C_o'=C'\backslash \{P'\}$, etc. Then there exists a $\mu_e$-equivariant injection $$\mathcal O(\pi^*L_{Z/C}^{ss}) \subset H' \otimes \mathbb C(P').$$
Finally, it is claimed that if $l$ is the order of the character $\chi_{P'}$, then $\phi(l) \leq B$. Form this fact, it is easy to get the desired result.
I could understand Step 1-5, and more or less understand
Step 6. However, I don't know how to deduce $\phi(l) \leq B$.
Another place uses this result appears in "Boundedness of log Calabi-Yau pairs of Fano type" by Hacon and Xu. Where it wrote (in page 9) "The eigenvalues of the corresponding action on $H^m(F', \mathbb Z)\otimes \mathbb C$ are always algebraic integers, thus we conclude $\phi(r) \leq \dim_{\mathbb C}(H^m(F', \mathbb Z)\otimes \mathbb C) = l$. " I don't see the relevant of algebraic integers to this question. Certainly $\mu_4$ can act on $\mathbb C$ by scaling, but $\phi(4)=2>\dim \mathbb C$.


text:
Q: Backhandler.removeeventlistener is invalid when using componentWillUnmount Why is BackHandler.removeEventListener invalid when using componentWillUnmount ?
componentWillUnmount(): void {
    console.log(1112223)
    BackHandler.removeEventListener("hardwareBackPress", () => {
        console.log(2222222222)
    });
    console.log(3333333)
 }

The last conslog will output,But the method in the second conslog, callback, did not execute

A: The second parameter is not a callback. It is the handler that you registered
componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
}

componentWillUmmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
}

handleBackPress = () => {
    // Handle your back press
}

Or you could use the result from BackHandler.addEventListener to unsubcribe it.
componentDidMount() {
    this.unsubcribe = BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
}

componentWillUmmount() {
    this.unsubcribe();
}


text:
Q: How to handle english UK and english US languages with i18next? My app is translated in several languages with i18next. Until now, I used only one English translation. But I'd like to have both en-GB and en-US. Truth is, text translations will be the same and the only reason I want both languages is for date formats.
More precisely, I want to pass the good date format to a MUI DatePicker component. Right now, English has MM-DD-YYYY format, unlike most other languages. Obviously, I'd like en-GB to have DD-MM-YYYY format.
Is this rather common use case built in i18next or should I use some kind of hack to avoid having two almost identical translation files to maintain ?


text:
Q: MongoDB C# 2.0 Driver: How many MongoClients respectively Sockets per Web Application?
Typically you only create one MongoClient instance for a given cluster
  and use it across your application. Creating multiple MongoClients
  will, however, still share the same pool of connections if and only if
  the connection strings are identical.

Source: http://mongodb.github.io/mongo-csharp-driver/2.0/getting_started/quick_tour/
Our situation is that we have two different "clusters".
We do not work with replication or sharding, but we have two different databases.
It means that some of our API functions will fetch data from one database, whereas other API functions get the data from the second database.
This is hard coded.
We created a SelectDatabase method in each class, which then creates a MongoClient with the given settings.
The same class will always access the same database.
I expected that the driver would handle then the number of seconds in an "optimum way".
But it turned out, that each time I refresh the browser, a new Web API Controller call is done and therefore also a new SelectDatabase call.
And that resulted in a new socket every time (checked with TCPView).
So of course each API Controller call should cause SelectDatabase, but I think it is an overkill to create a socket each time.
We are creating new MongoClients like this:
//Creating multiple MongoClients will, however, still share the same pool of connections
//if and only if the connection strings are identical.
MongoClientSettings clientSettings1 = new MongoClientSettings()
{
    Server = new MongoServerAddress(host, port),
    ClusterConfigurator = builder =>
    {
        builder.ConfigureCluster(settings => settings.With(serverSelectionTimeout: TimeSpan.FromSeconds(serverSelectionTimeoutInSeconds)));
    }
};

What is the optimum number of simultaneously opened Sockets (between Web Application and Database), respectively MongoClient instances, in our Project situation?

*

*Web Browser "Socket" Life cycle should only cause the Web application to create 1 socket to the database

*The Web Application should use just one socket, each per database, completely independent of how many Web Browser or Sockets are open to the web application.

*You should open a new connection each time you have a Web API call
I run some Postman test where I created a few hundred API calls and I saw that it was running out of resources respectively into timeouts. I saw that it run better, when I was choosing approach number 2 instead of 3.
But I am concerned that the different tasks created when the Web API gets called so often could interfere somehow then on a Socket level to make errors occur.
Update
I made two tests:
The first was based on the principle that on each request a new MongoClient is generated. TCPView showed me that a new socket is opened on each request.
The second test was with a singleton pattern which allows me to access every time the same two MongoClients. The second test only used two sockets.
I also need to say that I changed the asynchronous call so that the methods is blocked until it returns (for simplicity I did not want these Task return types in every method).

A: I made some trials and it turns out that creating multiple MongoClients will NOT share the same pool of connections if you used a MongoClientSettings object, even if the connection string parameters (host, port) are the same.
MongoDB documentation probably meant "connection strings" literally, that is, only strings.
In short, the following works as intended:
_client = new MongoClient("mongodb://localhost:27017");

But not the following:
MongoClientSettings clientSettings = new MongoClientSettings()
{
    Server = new MongoServerAddress(host, port),
    ClusterConfigurator = builder =>
    {
        builder.ConfigureCluster(settings => settings.With(serverSelectionTimeout: TimeSpan.FromSeconds(serverSelectionTimeoutInSeconds)));
    }
};

_client = new MongoClient(clientSettings);

Even if you used the very same MongoClientSettings object from a singleton, you still get different connection pools. I also verified that.

A: One MongoClient instance doesn't mean one socket, inside it has a pool of connections and you can control the minimum and maximum of the pool size. The default value of the maximum pool size is 100, which means it can grow up to 100 open connections/sockets.
Based on the documentation it doesn't matter how you create your MongoClient, because you should end up with 2 connection pools anyway, because you have 2 different connection strings. But I would go with number 2, one MongoClient instance per database because that is the recommended way to go for all mongo clients no matter the technology.
In your case when you ran the tests with Postman it is possible that the timeouts came from the web server? What is good about the mongodb .NET client is that it is exposing async methods so you can async all the way to the web api controller. This should make your web application scale because all the asp.net threads will be reused and not blocked on the IO.
And you should not worry about mixing sockets/connections because one MongoClient doesn't mean one socket. Underneath there are many connections being used and they are only reused when they finished their previous work. If you take a look at the code of the csharp-driver you can see it looks pretty professional :)


text:
Q: How do I display numbers in octal notation in java? I need to write a code for a project and part of the code needs to be able to do as follows:
Generate one random positive integer from 1 to 100, and then display all of the numbers in octal notation from 1 to the random integer.
Can someone please help me with this? (only the octal notation part)

A: You can print numbers in octal notation using the printf method with the %o formatter:
System.out.printf("Number in octal notation: %o", myNumber);

A: You can use Random.nextInt() for random number and Integer.toOctalString() for octal conversion.
Try this out.
import java.util.Random;

public class Main {
    public static void main(String[] args) {
        Random random = new Random();
        int number = random.nextInt(100) + 1;

        for(int i = 1; i < number; i++){
            System.out.println(Integer.toOctalString(i));
        }
    }
}

A: 1st generate a random number:
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1); // in your case min=1 and max=100;
and to convert above number to octal you can use toOctalString method.
String myOctNumber = Integer.toOctalString(randomNum);
 System.out.println("myOctNumber = "+myOctNumber);


text:
Q: mongodb find if hierarch exists With given below example
{ "_id" : 1, "name" : "Dev" }
{ "_id" : 2, "name" : "Eliot", "reportsTo" : "Dev" }
{ "_id" : 3, "name" : "Ron", "reportsTo" : "Eliot" }
{ "_id" : 4, "name" : "Andrew", "reportsTo" : "Eliot" }
{ "_id" : 5, "name" : "Asya", "reportsTo" : "Ron" }
{ "_id" : 6, "name" : "Dan", "reportsTo" : "Andrew" }

can I find whether "Dan" reports to "Ron". Here "Ron" is not immediate parent of "Dan" ? For this query, I should get empty response
For a query whether "Dan" reports to "Eliot", I should get the hierarchy between "Dan" and "Eliot" which obviously includes "Andrew"
I tried $graphlook where we are able to use "$match" for beginning the hierarchy. But dont know upto which level the query should run. I cannot hardcode "maxDepth"
Thanks

A: I think this is not possible during query time without using an $aggregation, which constructs the hierarchy for all documents. (Very slow)
Instead I'd suggest you store the hierarchy on every document:
{ "_id" : 1, "name" : "Dev" }
{ "_id" : 2, "name" : "Eliot", "reportsTo" : "Dev", reportChain: [1] }
{ "_id" : 3, "name" : "Ron", "reportsTo" : "Eliot", reportChain: [2, 1] }
{ "_id" : 4, "name" : "Andrew", "reportsTo" : "Eliot", reportChain: [2, 1] }
{ "_id" : 5, "name" : "Asya", "reportsTo" : "Ron", reportChain: [3, 2, 1] }
{ "_id" : 6, "name" : "Dan", "reportsTo" : "Andrew", reportChain: [4, 2, 1] }

This extra field makes your use-case possible and reads fast.
But you need to maintain it whenever creating, updating, deleting a document.


text:
Q: ms-access "show page margins" property does anyone know what this property does? i am tweaking it and i dont see anything changing on the report.

A: You really need to improve your questions. You didn't say what version of Access you're using, nor the context in which you're encountering it (report properties).
I guessed that you were using A2007 or A2010, and checked the properties of a report in A2007, and yes, that property is there.
With a little experimenting, it became obvious that it controls whether or not the page margins are displayed in layout view. It is true that there's not help topic for it, which seems like a bad thing to me, but it's pretty easy to figure it out.
Did you not try anything at all to answer the question?


text:
Q: iPhone backup & restore does not restore our app's data on rare occasions We have an iPhone app with several thousand users, and we've had one or two users saying that after a full backup & restore procedure within iTunes, the data for our app was lost.
All the data (photos & SQLite DB) are stored in the documents area of the app. I've tested this thoroughly with our devices and it works absolutely fine.
Can anyone think of a reason for this, or has anyone experienced this before?

A: I have this problem too - sometimes iTunes goes berserk and deletes data. Most apps are not important enough for people to complain, but if yours is you will hear about it. As it seems, you do.
My theory is that something goes wrong in iTunes and it uninstalls the app deleting the data, and then reinstalls it back - fresh and minty.
One thing I can suggest is storing data in both Keychain and Documents folder, and looking in both of these places. When an app is uninstalled the keychain is NOT cleaned up, at least not right away. However when backup is restored to a different device keychain is not carried along, so Documents is still a must.
The other option is to encourage online backup with user's permission. Of course you need to control access so that's a bit of a bother.

A: I have a fairly popular iPhone game, and every once in a while I'll hear from a user who has lost their data during a sync or backup just like this.
I've decided that iTunes syncing is just to volatile to rely on in the future. For my game, I've included an option for users to unlock the whole game all at once, so that it isn't as bad when they lose all their data. In future games and apps I'll be storing all user data in the cloud, which has a ton of benefits, and it'll fix/skip the whole iTunes sync issue.

A: If the backup is where it belongs (in the MobileSync folder) there should be a button "Restore from iPhone Backup" on the Summary page when you click on the iPhone's name in iTunes. You need the latest version of iTunes installed.
If iOS needs to be restored also restore it with the Restore iPhone button; when the restore is done it will restore any valid backups that are in the MobileSync folder.


text:
Q: Need to build a new array by randomly picking 18 numbers from another array and also having those same numbers be in the new array twice I am making a matching game for a group project in a JavaScript Jquery class. I have 36 images that I can use for the tiles. I want the game to randomly pick 18 of these and put them into a new array. I also need these 18 numbers in the new array twice, because that new array is going to be shuffled and then used the build the game board.
Here is my code:
let objects = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29','30', '31', '32', '33', '34', '35', '36'],

function cardList () {
    var cardList = [36];
    for (i = 0; i < cardList.length; i+=2) {
        cardList[i] = objects[Math.floor(Math.round((Math.random()*36)+1))];
        cardList[i+1] = cardList[i];
    }
    return cardList;
}

I tried to use the Chrome debugger on this and it this isn't creating all the numbers, it's just creating the two initial numbers.
There has got to be a better way to do this, I have looked at several examples of a matching game and most of those have the exact number of cards needs, which may be causing me problems.

A: Since you (probably) don't want items to appear more than twice in the result, you should choose items without replacement. This is how I would do it:

const objects = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29','30', '31', '32', '33', '34', '35', '36'];
const getList = () => {
  const objs = objects.slice(0);
  const selected = [];
  for (let i = 0; i < 18; i++) {
    const index = Math.floor(Math.random() * objs.length);
    const [num] = objs.splice(index, 1);
    selected.push(num, num);
  }
  return selected;
};
console.log(getList());

A: To pick the numbers I would simply shuffle the array and take 18 unique elements from it. The best method to shuffle an array is the Fisher-Yates shuffle, below implementation for the shuffle is taken from this answer. All you need to do then is to "concat the array with itself" and you got your starting array with 18 numbers that all exist twice in the array. You could obviously directly shuffle the resulting array then, and voila.

let array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29','30', '31', '32', '33', '34', '35', '36'];

function buildCardList(array) {
  const shuffled = shuffle(array).slice(0,18);
  return shuffle(shuffled.concat(shuffled));
}

console.log(buildCardList(array));

// Origin: https://stackoverflow.com/a/2450976/3993662
function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

A: See the following working code
I made two changes
1) Changed the line var cardList = [36]; to var cardList = Array(36);
2)  Changed cardList[i] = objects[Math.floor(Math.round((Math.random()*36)+1))]; to
let index = Math.floor((Math.random()*objects.length));
cardList[i] = objects[index];

And to avoid duplicates I added
objects.splice(index,1);

let objects = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29','30', '31', '32', '33', '34', '35', '36'];

function cardList () {
    var cardList = Array(36);
    for (i = 0; i < cardList.length; i+=2) {
        let index = Math.floor((Math.random()*objects.length));
        cardList[i] = objects[index];
        cardList[i+1] = cardList[i];
        objects.splice(index,1);
    }
    return cardList;
}

console.log(cardList());


text:
Q: Show only single toaster if there is any error in react I am new to react js. Here I am using react-redux-toaster.
Now, I have a following code .
else {
    dispatch({
        type: REQUEST_SUCCESSED
    })
    toastr.error("Error while Fetching the technologies,Please try again");
    if (response.status === "") {
        toastr.error('Our server is down. Please check again');
    }
    dispatch({
        type: FAILED_TEHNOLOGY_FETCHING,
        data: response.status,
    });
    if (response.status === 401) {
        toastr.error('Please Login Again');
        localStorage.clear();
        history.push('/');
    }
}

Now Here, I want to show only one toaster but what happens is that
when we hit request then if the server is down then it hits the request but still shows the other errors. can any one help me with this ?
How I will be able to show only one toaster ?

A: You didn't seem to check conditions

else {
    if (!response.status) {
        toastr.error('Our server is down. Please check again');
    }
    else if (response.status === 401) {
        toastr.error('Please Login Again');
        localStorage.clear();
        history.push('/');
    }
    else if (/* not sure on condition */) {
      toastr.error("Error while Fetching the technologies,Please try again");
      dispatch({
          type: FAILED_TEHNOLOGY_FETCHING,
          data: response.status,
      });
    } else {
      dispatch({
          type: REQUEST_SUCCESSED
      })
    }
}


text:
Q: Woocommerce update stock by ID after payment I created a custom product type for WooCommerce. With this product type it is possible to connect an other product that is exist by ID.
WooCommerce reduce the stock quantity automatically if an order is placed and the payment is successful.
For example I added a product with ID 4082 to the cart with a quantity from 3.
After place this order WooCommerce updated the stock from product 4082 with -3.
Ok back to my custom product type. As I said it is possible to connect another product by ID.
For example I connect product 4082 with product ID 10988.
If a customer add product 4082 to the cart and placed the order I want reduce the stock quantity from product ID 10988 and not from 4082.
<?php
add_action('woocommerce_checkout_order_processed', 'stocktest');

function stocktest($order_id){
    $order = wc_get_order( $order_id );
    $order_item = $order->get_items();
    foreach( $order_item as $product ) {
    //for the topic I programmed the IDs hardcoded
        if($product->ID == '4082'){
            wc_update_product_stock( 10998, $product['qty'], 'decrease', '' );
        }
    }
}
?>

I tried the code above and the stock from ID 10998 is correctly decreased but also the stock from ID 4082 is decreased.
Do I use the wrong hook? And how can I make the function correctly?
Hope somebody can help me with this.
Thanks a lot

A: Does wc_update_product_stock( 4082, $product['qty'], 'increase', '' ); not work?
That way, the stock should be adjusted for the 4082 product.
Also, there might be a potential issue with your snippet. The $product variable refers to the product object of 4082 product, not the 10998 product.
Maybe try something like this?
<?php
add_action('woocommerce_checkout_order_processed', 'stocktest');

function stocktest($order_id){
    $order = wc_get_order( $order_id );
    $order_item = $order->get_items();
    foreach( $order_item as $product ) {
    //for the topic I programmed the IDs hardcoded
        if($product->ID == '4082'){
            $connected_qty = get_post_meta( 10988, '_stock', true );
            wc_update_product_stock( 10998, $connected_qty, 'decrease', '' );
            wc_update_product_stock( 4082, $product['qty'], 'increase', '' );
        }
    }
}
?>

Instead of using the custom field query, you could use the WC_Product class:
$connected_product = wc_get_product(10998);
$connected_qty = $connected_product->get_stock_quantity();

A: I did some research on your question. WooCommerce called a lot of functions to update the stock af order / payment. If an order is placed the items become an status reduce_stock yes or no.
If is yes go further and update the stock of this item. After this WooCommerce created the e-mails and ordernotes.
All this functions worked together please be careful with changing the code in the file wc-stock-functions.php
If you want change and try something do this for example on a local testserver.
This are some functions in the file
<?php
wc_maybe_reduce_stock_levels();
wc_maybe_increase_stock_levels();
wc_reduce_stock_levels();
wc_trigger_stock_change_notifications();
?>