问:
Multiple errors running Pyspark
I'm having issues running pyspark on an external server. Running pyspark results in multiple errors, and I can't seem to determine how to fix them. Here's the printout:

```<code>[root@spark-master ~]# pyspark
Python 3.6.0 |Anaconda 4.3.1 (64-bit)| (default, Dec 23 2016, 12:22:00)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
Using Spark's default log4j profile: org/apache/spark/log4j-
defaults.properties
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use
setLogLevel(newLevel).
17/05/26 21:19:10 WARN NativeCodeLoader: Unable to load native-hadoop
library for your platform... using builtin-java classes where applicable
17/05/26 21:19:10 WARN SparkContext: Another SparkContext is being
constructed (or threw an exception in its constructor).  This may indicate
an error, since only one SparkContext may be running in this JVM (see SPARK-
2243). The other SparkContext was created at:
org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:423)
py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
py4j.Gateway.invoke(Gateway.java:236)
py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
py4j.GatewayConnection.run(GatewayConnection.java:214)
java.lang.Thread.run(Thread.java:748)
Traceback (most recent call last):File "/usr/local/spark/spark/python/pyspark/shell.py", line 43, in <module>
    spark = SparkSession.builder\
  File "/usr/local/spark/spark/python/pyspark/sql/session.py", line 169, in getOrCreate
    sc = SparkContext.getOrCreate(sparkConf)
  File "/usr/local/spark/spark/python/pyspark/context.py", line 310, in getOrCreate
    SparkContext(conf=conf or SparkConf())
  File "/usr/local/spark/spark/python/pyspark/context.py", line 118, in __init__
    conf, jsc, profiler_cls)
  File "/usr/local/spark/spark/python/pyspark/context.py", line 182, in _do_init
    self._jsc = jsc or self._initialize_context(self._conf._jconf)
  File "/usr/local/spark/spark/python/pyspark/context.py", line 249, in _initialize_context
    return self._jvm.JavaSparkContext(jconf)
  File "/usr/local/spark/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1401, in __call__
  File "/usr/local/spark/spark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line 319, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling None.org.apache.spark.api.java.JavaSparkContext.
: java.lang.ExceptionInInitializerError
        at org.apache.spark.SparkContext.<init>(SparkContext.scala:397)
        at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:236)
        at py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
        at py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
        at py4j.GatewayConnection.run(GatewayConnection.java:214)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.UnknownHostException: spark-master: spark-master: Temporary failure in name resolution
        at java.net.InetAddress.getLocalHost(InetAddress.java:1505)
        at org.apache.spark.util.Utils$.findLocalInetAddress(Utils.scala:870)
        at org.apache.spark.util.Utils$.org$apache$spark$util$Utils$$localIpAddress$lzycompute(Utils.scala:863)
        at org.apache.spark.util.Utils$.org$apache$spark$util$Utils$$localIpAddress(Utils.scala:863)
        at org.apache.spark.util.Utils$$anonfun$localHostName$1.apply(Utils.scala:920)
        at org.apache.spark.util.Utils$$anonfun$localHostName$1.apply(Utils.scala:920)
        at scala.Option.getOrElse(Option.scala:121)
        at org.apache.spark.util.Utils$.localHostName(Utils.scala:920)
        at org.apache.spark.internal.config.package$.<init>(package.scala:189)
        at org.apache.spark.internal.config.package$.<clinit>(package.scala)
        ... 13 more
Caused by: java.net.UnknownHostException: spark-master: Temporary failure in name resolution
        at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
        at java.net.InetAddress$2.lookupAllHostAddr(InetAddress.java:928)
        at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1323)
        at java.net.InetAddress.getLocalHost(InetAddress.java:1500)
        ... 22 more

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/spark/spark/python/pyspark/shell.py", line 47, in <module>
    spark = SparkSession.builder.getOrCreate()
  File "/usr/local/spark/spark/python/pyspark/sql/session.py", line 169, in getOrCreate
    sc = SparkContext.getOrCreate(sparkConf)
  File "/usr/local/spark/spark/python/pyspark/context.py", line 310, in getOrCreate
    SparkContext(conf=conf or SparkConf())
  File "/usr/local/spark/spark/python/pyspark/context.py", line 118, in __init__
    conf, jsc, profiler_cls)
  File "/usr/local/spark/spark/python/pyspark/context.py", line 182, in _do_init
    self._jsc = jsc or self._initialize_context(self._conf._jconf)
  File "/usr/local/spark/spark/python/pyspark/context.py", line 249, in _initialize_context
    return self._jvm.JavaSparkContext(jconf)
  File "/usr/local/spark/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1401, in __call__
  File "/usr/local/spark/spark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line 319, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling None.org.apache.spark.api.java.JavaSparkContext.
: java.lang.NoClassDefFoundError: Could not initialize class org.apache.spark.internal.config.package$
        at org.apache.spark.SparkContext.<init>(SparkContext.scala:397)
        at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:236)
        at py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
        at py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
        at py4j.GatewayConnection.run(GatewayConnection.java:214)
        at java.lang.Thread.run(Thread.java:748)

>>>
</code>```

Any help would be greatly appreciated!

Edit: On other machines I'm attempting to run this on, I'm getting a similar set of errors but without the UnknownHostException.

```<code>pyspark
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
17/05/30 13:12:35 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/05/30 13:12:35 WARN SparkContext: Another SparkContext is being constructed (or threw an exception in its constructor).  This may indicate an error, since only one SparkContext may be running in this JVM (see SPARK-2243). The other SparkContext was created at:
org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:423)
py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
py4j.Gateway.invoke(Gateway.java:236)
py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
py4j.GatewayConnection.run(GatewayConnection.java:214)
java.lang.Thread.run(Thread.java:748)
Traceback (most recent call last):
  File "/usr/local/spark/python/pyspark/shell.py", line 47, in <module>
    spark = SparkSession.builder.getOrCreate()
  File "/usr/local/spark/python/pyspark/sql/session.py", line 169, in getOrCreate
    sc = SparkContext.getOrCreate(sparkConf)
  File "/usr/local/spark/python/pyspark/context.py", line 310, in getOrCreate
    SparkContext(conf=conf or SparkConf())
  File "/usr/local/spark/python/pyspark/context.py", line 118, in __init__
    conf, jsc, profiler_cls)
  File "/usr/local/spark/python/pyspark/context.py", line 182, in _do_init
    self._jsc = jsc or self._initialize_context(self._conf._jconf)
  File "/usr/local/spark/python/pyspark/context.py", line 249, in _initialize_context
    return self._jvm.JavaSparkContext(jconf)
  File "/usr/local/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1401, in __call__
  File "/usr/local/spark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line 319, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling None.org.apache.spark.api.java.JavaSparkContext.
: java.lang.NoClassDefFoundError: Could not initialize class org.apache.spark.internal.config.package$
        at org.apache.spark.SparkContext.<init>(SparkContext.scala:397)
        at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:236)
        at py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
        at py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
        at py4j.GatewayConnection.run(GatewayConnection.java:214)
        at java.lang.Thread.run(Thread.java:748)

>>>
</code>```

答:
What's tipping me off is the "Another spark context..." string.

Since you're running spark on an external server I'm assuming you're using Jupyter or another interactive markdown rather than batch-submit. If so, try stopping your sparkContext and restarting it. If you instantiated your sparkContext with sc, then run sc.stop() and then restart your Jupyter kernel.

I see a very similar error if I try to run the same sparkContext instantiation twice in the same notebook.

Title: Multiple errors running Pyspark

Body:
I'm having issues running pyspark on an external server. Running pyspark results in multiple errors, and I can't seem to determine how to fix them. Here's the printout:

[root@spark-master ~]# pyspark
Python 3.6.0 |Anaconda 4.3.1 (64-bit)| (default, Dec 23 2016, 12:22:00)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
Using Spark's default log4j profile: org/apache/spark/log4j-
defaults.properties
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use
setLogLevel(newLevel).
17/05/26 21:19:10 WARN NativeCodeLoader: Unable to load native-hadoop
library for your platform... using builtin-java classes where applicable
17/05/26 21:19:10 WARN SparkContext: Another SparkContext is being
constructed (or threw an exception in its constructor).  This may indicate
an error, since only one SparkContext may be running in this JVM (see SPARK-
2243). The other SparkContext was created at:
org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:423)
py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
py4j.Gateway.invoke(Gateway.java:236)
py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
py4j.GatewayConnection.run(GatewayConnection.java:214)
java.lang.Thread.run(Thread.java:748)
Traceback (most recent call last):File "/usr/local/spark/spark/python/pyspark/shell.py", line 43, in <module>
    spark = SparkSession.builder\
  File "/usr/local/spark/spark/python/pyspark/sql/session.py", line 169, in getOrCreate
    sc = SparkContext.getOrCreate(sparkConf)
  File "/usr/local/spark/spark/python/pyspark/context.py", line 310, in getOrCreate
    SparkContext(conf=conf or SparkConf())
  File "/usr/local/spark/spark/python/pyspark/context.py", line 118, in __init__
    conf, jsc, profiler_cls)
  File "/usr/local/spark/spark/python/pyspark/context.py", line 182, in _do_init
    self._jsc = jsc or self._initialize_context(self._conf._jconf)
  File "/usr/local/spark/spark/python/pyspark/context.py", line 249, in _initialize_context
    return self._jvm.JavaSparkContext(jconf)
  File "/usr/local/spark/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1401, in __call__
  File "/usr/local/spark/spark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line 319, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling None.org.apache.spark.api.java.JavaSparkContext.
: java.lang.ExceptionInInitializerError
        at org.apache.spark.SparkContext.<init>(SparkContext.scala:397)
        at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:236)
        at py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
        at py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
        at py4j.GatewayConnection.run(GatewayConnection.java:214)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.UnknownHostException: spark-master: spark-master: Temporary failure in name resolution
        at java.net.InetAddress.getLocalHost(InetAddress.java:1505)
        at org.apache.spark.util.Utils$.findLocalInetAddress(Utils.scala:870)
        at org.apache.spark.util.Utils$.org$apache$spark$util$Utils$$localIpAddress$lzycompute(Utils.scala:863)
        at org.apache.spark.util.Utils$.org$apache$spark$util$Utils$$localIpAddress(Utils.scala:863)
        at org.apache.spark.util.Utils$$anonfun$localHostName$1.apply(Utils.scala:920)
        at org.apache.spark.util.Utils$$anonfun$localHostName$1.apply(Utils.scala:920)
        at scala.Option.getOrElse(Option.scala:121)
        at org.apache.spark.util.Utils$.localHostName(Utils.scala:920)
        at org.apache.spark.internal.config.package$.<init>(package.scala:189)
        at org.apache.spark.internal.config.package$.<clinit>(package.scala)
        ... 13 more
Caused by: java.net.UnknownHostException: spark-master: Temporary failure in name resolution
        at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
        at java.net.InetAddress$2.lookupAllHostAddr(InetAddress.java:928)
        at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1323)
        at java.net.InetAddress.getLocalHost(InetAddress.java:1500)
        ... 22 more

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/spark/spark/python/pyspark/shell.py", line 47, in <module>
    spark = SparkSession.builder.getOrCreate()
  File "/usr/local/spark/spark/python/pyspark/sql/session.py", line 169, in getOrCreate
    sc = SparkContext.getOrCreate(sparkConf)
  File "/usr/local/spark/spark/python/pyspark/context.py", line 310, in getOrCreate
    SparkContext(conf=conf or SparkConf())
  File "/usr/local/spark/spark/python/pyspark/context.py", line 118, in __init__
    conf, jsc, profiler_cls)
  File "/usr/local/spark/spark/python/pyspark/context.py", line 182, in _do_init
    self._jsc = jsc or self._initialize_context(self._conf._jconf)
  File "/usr/local/spark/spark/python/pyspark/context.py", line 249, in _initialize_context
    return self._jvm.JavaSparkContext(jconf)
  File "/usr/local/spark/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1401, in __call__
  File "/usr/local/spark/spark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line 319, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling None.org.apache.spark.api.java.JavaSparkContext.
: java.lang.NoClassDefFoundError: Could not initialize class org.apache.spark.internal.config.package$
        at org.apache.spark.SparkContext.<init>(SparkContext.scala:397)
        at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:236)
        at py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
        at py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
        at py4j.GatewayConnection.run(GatewayConnection.java:214)
        at java.lang.Thread.run(Thread.java:748)

>>>

Any help would be greatly appreciated!

Edit: On other machines I'm attempting to run this on, I'm getting a similar set of errors but without the UnknownHostException.

pyspark
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
17/05/30 13:12:35 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/05/30 13:12:35 WARN SparkContext: Another SparkContext is being constructed (or threw an exception in its constructor).  This may indicate an error, since only one SparkContext may be running in this JVM (see SPARK-2243). The other SparkContext was created at:
org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:423)
py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
py4j.Gateway.invoke(Gateway.java:236)
py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
py4j.GatewayConnection.run(GatewayConnection.java:214)
java.lang.Thread.run(Thread.java:748)
Traceback (most recent call last):
  File "/usr/local/spark/python/pyspark/shell.py", line 47, in <module>
    spark = SparkSession.builder.getOrCreate()
  File "/usr/local/spark/python/pyspark/sql/session.py", line 169, in getOrCreate
    sc = SparkContext.getOrCreate(sparkConf)
  File "/usr/local/spark/python/pyspark/context.py", line 310, in getOrCreate
    SparkContext(conf=conf or SparkConf())
  File "/usr/local/spark/python/pyspark/context.py", line 118, in __init__
    conf, jsc, profiler_cls)
  File "/usr/local/spark/python/pyspark/context.py", line 182, in _do_init
    self._jsc = jsc or self._initialize_context(self._conf._jconf)
  File "/usr/local/spark/python/pyspark/context.py", line 249, in _initialize_context
    return self._jvm.JavaSparkContext(jconf)
  File "/usr/local/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1401, in __call__
  File "/usr/local/spark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line 319, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling None.org.apache.spark.api.java.JavaSparkContext.
: java.lang.NoClassDefFoundError: Could not initialize class org.apache.spark.internal.config.package$
        at org.apache.spark.SparkContext.<init>(SparkContext.scala:397)
        at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:236)
        at py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
        at py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
        at py4j.GatewayConnection.run(GatewayConnection.java:214)
        at java.lang.Thread.run(Thread.java:748)

>>>


来源: stackexchange

问:
How to convert RDD[GenericRecord] to dataframe in scala?
I get tweets from kafka topic with Avro (serializer and deserializer).
Then i create a spark consumer which extracts tweets in Dstream of RDD[GenericRecord].
Now i want to convert each rdd to a dataframe to analyse these tweets via SQL.
Any solution to convert RDD[GenericRecord] to dataframe please ?</p>

答:
Even though something like this may help you,

```<code>val stream = ...

val dfStream = stream.transform(rdd:RDD[GenericRecord]=>{
     val df = rdd.map(_.toSeq)
              .map(seq=> Row.fromSeq(seq))
              .toDF(col1,col2, ....)

     df
})
</code>```

I'd like to suggest you an alternate approach. With Spark 2.x you can skip the whole process of creating DStreams. Instead, you can do something like this with structured streaming,

```<code>val df = ss.readStream
  .format("com.databricks.spark.avro")
  .load("/path/to/files")
</code>```

This will give you a single dataframe which you can directly query. Here, ss is the instance of spark session. /path/to/files is the place where all your avro files are being dumped from kafka.

PS: You may need to import spark-avro

```<code>libraryDependencies += "com.databricks" %% "spark-avro" % "4.0.0"
</code>```

Hope this helped. Cheers

ContentLicense: CC BY-SA 3.0

Body:
Even though something like this may help you,

val stream = ...

val dfStream = stream.transform(rdd:RDD[GenericRecord]=>{
     val df = rdd.map(_.toSeq)
              .map(seq=> Row.fromSeq(seq))
              .toDF(col1,col2, ....)

     df
})

I'd like to suggest you an alternate approach. With Spark 2.x you can skip the whole process of creating DStreams. Instead, you can do something like this with structured streaming,

val df = ss.readStream
  .format("com.databricks.spark.avro")
  .load("/path/to/files")

This will give you a single dataframe which you can directly query. Here, ss is the instance of spark session. /path/to/files is the place where all your avro files are being dumped from kafka.

PS: You may need to import spark-avro

libraryDependencies += "com.databricks" %% "spark-avro" % "4.0.0"

Hope this helped. Cheers


问:
How to check if empty and display rich text field (HTML) in Hippo CMS template
I have a project built using the Hippo CMS Java framework. I have created a new document type which contains a rich text field. In the document type bean I have a property of type HippoHtml:

```<code>@HippoEssentialsGenerated(internalName = "acm:abstract")
public HippoHtml getAbstract() {
    return getHippoHtml("acm:abstract");
}
</code>```

Other fields of String type work fine:

```<code>@HippoEssentialsGenerated(internalName = "acm:title")
public String getTitle() {
    return getProperty("acm:title");
}
</code>```

In the JSP template I can check and display simple properties like this:

```<code><c:if test="${ not empty result.title  }">
  <h1>${ result.title }</h1>
</c:if>
</code>```

However, for the HippoHtml property, I cannot get the template to recognize the field. I have tried the following:

```<code><%--@elvariable id="result" type="org.acm.beans.CustomDocument"--%>

<c:if test="${ not empty result.abstract}">
  ${ result.abstract}
</c:if>
...
<c:if test="${ not empty result.abstract  }">
  <hst:html hippohtml="${ result.abstract }"/>
</c:if>
...
<c:if test="${ not empty result.html.abstract  }">
  <hst:html hippohtml="${ result.html.abstract }"/>
</c:if>
...
<c:if test="${ not empty result.html.content}">
  <hst:html hippohtml="${ result.html.content}"/>
</c:if>
</code>```

I would like to investigate the HippoHtml type. Where in the project files (or online) can I find a class definition for org.hippoecm.hst.content.beans.standard.HippoHtml in order to see the object properties and methods?

How do I check if the document property acm:abstract has a value, then display it in my template?

答:
Check the code:
https://code.onehippo.org/

Or the api:
http://javadoc.onehippo.org/11.1/hippo-site-toolkit/

Or a more general overview page which includes the above links:
https://www.onehippo.org/library/about/developer-info.html

To see if it is empty you can call

```<code><hst:html hippohtml="${ result.abstract}" var="foo"/>
</code>```

And then test if foo exists.

Body:
I have a project built using the Hippo CMS Java framework. I have created a new document type which contains a rich text field. In the document type bean I have a property of type HippoHtml:

@HippoEssentialsGenerated(internalName = "acm:abstract")
public HippoHtml getAbstract() {
    return getHippoHtml("acm:abstract");
}

Other fields of String type work fine:

@HippoEssentialsGenerated(internalName = "acm:title")
public String getTitle() {
    return getProperty("acm:title");
}

In the JSP template I can check and display simple properties like this:

<c:if test="${ not empty result.title  }">

${ result.title }

</c:if>

However, for the HippoHtml property, I cannot get the template to recognize the field. I have tried the following:

<%--@elvariable id="result" type="org.acm.beans.CustomDocument"--%>

<c:if test="${ not empty result.abstract}">
  ${ result.abstract}
</c:if>
...
<c:if test="${ not empty result.abstract  }">
  <hst:html hippohtml="${ result.abstract }"/>
</c:if>
...
<c:if test="${ not empty result.html.abstract  }">
  <hst:html hippohtml="${ result.html.abstract }"/>
</c:if>
...
<c:if test="${ not empty result.html.content}">
  <hst:html hippohtml="${ result.html.content}"/>
</c:if>

I would like to investigate the HippoHtml type. Where in the project files (or online) can I find a class definition for org.hippoecm.hst.content.beans.standard.HippoHtml in order to see the object properties and methods?

How do I check if the document property acm:abstract has a value, then display it in my template?

Body:
Check the code:
https://code.onehippo.org/

Or the api:
http://javadoc.onehippo.org/11.1/hippo-site-toolkit/

Or a more general overview page which includes the above links:
https://www.onehippo.org/library/about/developer-info.html

To see if it is empty you can call

<hst:html hippohtml="${ result.abstract}" var="foo"/>

And then test if foo exists.


问:
How to integrate USPS DelivConfirmCertifyV4Request API to print label into our web application
I am working in ASP.Net with C# and i am new to Integrate USPS. so any one please tell me how to integrate USPS in my web site. here i am using this sample. it always return error :

Authorization failure. DeliveryConfirmationV4 is not a valid API name for this protocol.

http://production.shippingapis.com/ShippingAPITest.dll?API=DeliveryConfirmationV4&XML=" + xml + "";

答:
You are using the wrong URL.  The URL is https://secure.shippingapis.com/ShippingAPI.dll

Also be careful with the API name - it's a bit confusing.  The API DelivConfirmCertifyV4 (used in the question title) is a test API.  The production API is DeliveryConfirmationV4.

Here's an example with some code that works that does this: USPS API - After creating labels retrieving Tracking Number C#


问:
What is wrong with this function call
Behold the code:

```<code>QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_Indexed8);
ui->viewLabel->setPixmap(QPixmap::fromImage(qi,Qt::AutoColor));
</code>```

Why does this give me an error? What is it trying to get me to change the qi argument to in the call to fromImage? I am relatively new to C++ and it seems like I am setting this up correctly. It works if I change the line to

```<code>QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_Indexed8);
    ui->viewLabel->setPixmap(QPixmap::fromImage(qi[0],Qt::AutoColor));
</code>```

But is that the correct way to do this?

答: It looks like QPixmap::fromImage takes a QImage as first argument, not a pointer to a QImage.

ContentLicense: CC BY-SA 2.5

Title: What is wrong with this function call

Body:
Behold the code:

QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_Indexed8);
ui->viewLabel->setPixmap(QPixmap::fromImage(qi,Qt::AutoColor));

Why does this give me an error? What is it trying to get me to change the qi argument to in the call to fromImage? I am relatively new to C++ and it seems like I am setting this up correctly. It works if I change the line to

QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_Indexed8);
    ui->viewLabel->setPixmap(QPixmap::fromImage(qi[0],Qt::AutoColor));

But is that the correct way to do this?


问:
csv import into django models
My python csv import script creates an extra empty entry in the database model every time I load data. I have tried to work around various ways but I still get one empty entry plus the actual data am loading from the csv.Here is what my script is like. Please your help will be of great achievment.    </p>

```<code>class CsvUploadView(LoginRequiredMixin, FormView):
form_class = CsvAttendeeForm
template_name = 'attendee/upload_attendee_csv.html'
success_url = reverse_lazy('home')

def post(self, request, *args, **kwargs):

    form_class = self.get_form_class()
    form = self.get_form(form_class)
    file = request.FILES.get('file')
    if form.is_valid():
        if file:
            reader = csv.reader(file, delimiter=',')
            next(reader)
            attendee_instance = Attendee()
            Attendee.objects.bulk_create(
                [Attendee(firstname=row[0],
                          surname=row[1],
                          email=row[2],
                          )
                 for row in reader])

            attendee_instance.save()

        return self.form_valid(form)

    else:
        return self.form_invalid(form)
</code>```

答:
It looks like you are initializing and saving an empty instance in addition to the bulk_create

```<code> # This line shouldn't be needed
 attendee_instance = Attendee()
 Attendee.objects.bulk_create(
      [Attendee(firstname=row[0],
           surname=row[1],
           email=row[2],
       )
       for row in reader])

# Nor should this line.
attendee_instance.save()
</code>```

Title: csv import into django models

Body:
My python csv import script creates an extra empty entry in the database model every time I load data. I have tried to work around various ways but I still get one empty entry plus the actual data am loading from the csv.Here is what my script is like. Please your help will be of great achievment.

class CsvUploadView(LoginRequiredMixin, FormView):
form_class = CsvAttendeeForm
template_name = 'attendee/upload_attendee_csv.html'
success_url = reverse_lazy('home')

def post(self, request, *args, **kwargs):

    form_class = self.get_form_class()
    form = self.get_form(form_class)
    file = request.FILES.get('file')
    if form.is_valid():
        if file:
            reader = csv.reader(file, delimiter=',')
            next(reader)
            attendee_instance = Attendee()
            Attendee.objects.bulk_create(
                [Attendee(firstname=row[0],
                          surname=row[1],
                          email=row[2],
                          )
                 for row in reader])

            attendee_instance.save()

        return self.form_valid(form)

    else:
        return self.form_invalid(form)

Body:
It looks like you are initializing and saving an empty instance in addition to the bulk_create

 # This line shouldn't be needed
 attendee_instance = Attendee()
 Attendee.objects.bulk_create(
      [Attendee(firstname=row[0],
           surname=row[1],
           email=row[2],
       )
       for row in reader])

# Nor should this line.
attendee_instance.save()


问:
input does not autofocus when doing validation
I'm validating an input #rut_usu. I am looking for, if the value entered already exists in the database, if it exists, I show a message, this is done correctly once it is out of focus, the idea is that in doing so the other elements of the form are blocked, and it is autofocused again #rut_usu I have managed to self-only, if, when it is out of focus, when clicking out of the form, it does not, if it does in another input, that is the problem.

Javascript

```<code>$("#rut_usu").focusout(function(){
var parametros = {"rut_usu" : $("#rut_usu").val()};
//search
$.ajax({
    type: "post",
    url: '<?php echo base_url();?>C_Usuarios/consultar_rut',
    data: parametros,
    dataType: "html",
    error: function(){
        alert("error petición ajax");
    },success: function(data){
      if(data){
             window.document.r_usuarios.rut_usu.focus();
             window.document.r_usuarios.rut_usu.select();
            $('#btn_insert').attr('disabled', 'disabled');
            $('#resultado').html('<span style="font-weight:bold;color:red;">that RUT already exists in the Database</span>');
        }
        else{  $("#resultado").addClass("hide"); return true;

        }
       }
      });
    });

   $("#name_user").keypress(function(){

   $("#name_user").removeClass("blanco");
   $("#msg_nom").addClass("hide");
  });
  $("#name_user").focusout(function(){
  if($("#name_user").val().length<1){
     $("#name_user").addClass("blanco");
     $("#msg_nom").removeClass("hide");
        window.document.r_usuarios.name_user.focus();
        window.document.r_usuarios.name_user.select();
        return false;
       }
       return true;
     })
</code>```

With these lines, I have the field autofocus according to if, and the form is blocked. But in the case of #rut_usu, if I add the true or false, the function is not executed.name_user is another input with a similar validation, but if its value is blank, it works correctly. If anyone knows any other way to do it, I would still like it, thank you.

```<code>window.document.name_form.name_input.focus();
window.document.name_form.name_input.select();
return false;
</code>```

答:
Use <code>$("#name_user").focus()</code> instead of </p>

```<code>    window.document.r_usuarios.name_user.focus();
    window.document.r_usuarios.name_user.select();
</code>```

Body:
I'm validating an input #rut_usu. I am looking for, if the value entered already exists in the database, if it exists, I show a message, this is done correctly once it is out of focus, the idea is that in doing so the other elements of the form are blocked, and it is autofocused again #rut_usu I have managed to self-only, if, when it is out of focus, when clicking out of the form, it does not, if it does in another input, that is the problem.

Javascript

$("#rut_usu").focusout(function(){
var parametros = {"rut_usu" : $("#rut_usu").val()};
//search
$.ajax({
    type: "post",
    url: '<?php echo base_url();?>C_Usuarios/consultar_rut',
    data: parametros,
    dataType: "html",
    error: function(){
        alert("error petición ajax");
    },success: function(data){
      if(data){
             window.document.r_usuarios.rut_usu.focus();
             window.document.r_usuarios.rut_usu.select();
            $('#btn_insert').attr('disabled', 'disabled');
            $('#resultado').html('that RUT already exists in the Database');
        }
        else{  $("#resultado").addClass("hide"); return true;

        }
       }
      });
    });

   $("#name_user").keypress(function(){

   $("#name_user").removeClass("blanco");
   $("#msg_nom").addClass("hide");
  });
  $("#name_user").focusout(function(){
  if($("#name_user").val().length<1){
     $("#name_user").addClass("blanco");
     $("#msg_nom").removeClass("hide");
        window.document.r_usuarios.name_user.focus();
        window.document.r_usuarios.name_user.select();
        return false;
       }
       return true;
     })

With these lines, I have the field autofocus according to if, and the form is blocked. But in the case of #rut_usu, if I add the true or false, the function is not executed.name_user is another input with a similar validation, but if its value is blank, it works correctly. If anyone knows any other way to do it, I would still like it, thank you.

window.document.name_form.name_input.focus();
window.document.name_form.name_input.select();
return false;

Body:
Use $("#name_user").focus() instead of

    window.document.r_usuarios.name_user.focus();
    window.document.r_usuarios.name_user.select();


问:
Django - get param from request.get and add it with another number
I have following code. I want to get values from from request and add it to another float number. I tried this code but gives me error :unsupported operand type(s) for +: 'float' and 'NoneType'

```<code>class RatingsUpdateView(UpdateAPIView):

    serializer_class = serializers.RatingsSerializer

    queryset = models.Ratings.objects.all()

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        #average =
        instance.total_number = instance.total_number + 1
        instance.sum_of_all_ratings =instance.sum_of_all_ratings + request.data.get("rating_give_by_user")

        instance.save()
</code>```

Look at the line where i am getting value 'request.data.get("rating_give_by_user")_give_by_user'. This value us NoneType but i want to add it to another float number. What is the solution and best practice. Thanks.

答:
You must check get param exists, try this:</p>

```<code>rating = request.GET.get("rating_give_by_user", None)
if rating:
    instance.sum_of_all_ratings = instance.sum_of_all_ratings + rating
</code>```

Body:
I have following code. I want to get values from from request and add it to another float number. I tried this code but gives me error :unsupported operand type(s) for +: 'float' and 'NoneType'

class RatingsUpdateView(UpdateAPIView):

    serializer_class = serializers.RatingsSerializer

    queryset = models.Ratings.objects.all()

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        #average =
        instance.total_number = instance.total_number + 1
        instance.sum_of_all_ratings =instance.sum_of_all_ratings + request.data.get("rating_give_by_user")

        instance.save()

Look at the line where i am getting value 'request.data.get("rating_give_by_user")_give_by_user'. This value us NoneType but i want to add it to another float number. What is the solution and best practice. Thanks.

Body:
You must check get param exists, try this:

rating = request.GET.get("rating_give_by_user", None)
if rating:
    instance.sum_of_all_ratings = instance.sum_of_all_ratings + rating


答:
Your problem is with this (cropped) section:

```<code>attendee_instance = Attendee()

Attendee.objects.bulk_create(
                [Attendee(firstname=row[0],
                          surname=row[1],
                          email=row[2],
                          )
attendee_instance.save()
</code>```

With the first attendee_instance, you're creating a blank Attendee object.  You later save this blank object with attendee_instance.save().

The line in the middle - Attendee.objects.bulk_create... - you're passing in a single item list to bulk_create, so it creates the object (with data) there. You don't need both.

What you want is probably:

```<code>Attendee.objects.create(firstname=row[0],
                          surname=row[1],
                          email=row[2],
                          )
</code>```

You don't need the bulk_create unless you're creating more than one object, you can just use straight-up create.  Similarly, you don't need to create the object by attendee_instance=Attendee() and then manually change the attributes, when you can do it all in one go as described above.

It's worth noting the caveats on the limitations of bulk create, particularly if you're not using Postgres, and also if you get to the point of using post_save and pre_save signals.  The create method does trigger those save signals, so just make sure that you use the most appropriate one for your use case

Title: csv import into django models

Body:
Your problem is with this (cropped) section:

attendee_instance = Attendee()

Attendee.objects.bulk_create(
                [Attendee(firstname=row[0],
                          surname=row[1],
                          email=row[2],
                          )
attendee_instance.save()

With the first attendee_instance, you're creating a blank Attendee object.  You later save this blank object with attendee_instance.save().

The line in the middle - Attendee.objects.bulk_create... - you're passing in a single item list to bulk_create, so it creates the object (with data) there. You don't need both.

What you want is probably:

Attendee.objects.create(firstname=row[0],
                          surname=row[1],
                          email=row[2],
                          )

You don't need the bulk_create unless you're creating more than one object, you can just use straight-up create.  Similarly, you don't need to create the object by attendee_instance=Attendee() and then manually change the attributes, when you can do it all in one go as described above.

It's worth noting the caveats on the limitations of bulk create, particularly if you're not using Postgres, and also if you get to the point of using post_save and pre_save signals.  The create method does trigger those save signals, so just make sure that you use the most appropriate one for your use case


问:
Creating subset list , in a list based on length of words
I have this code here: which takes user input and adds it to a list until they input to stop. At that point, it sorts the list items based on length.

What I am trying to do is put each word the user enters into a list of words with the same length. Like 2-letter words are put into one list, 3-letter words are put into another list.

When complete, I'm trying to return a list containing all of the individual word lists that were created.

So far all I have achieved is organizing them and then adding them to another list that outputs the list as many time as word entered.

```<code>def wordsList():
    stop = "stop"

    sentence = []
    sentence2 = []
    while True:
        word = input("Enter a word: ")
        if word == stop:
            # exit the loop
            break
        sentence.append(word)

        sentence.sort(key=len)
        cat= len(sentence)
        for sublist in sentence:

            sentence.append(sentence)
            # sublist.insert(sentence)
        # sentence2=[sentence]

    # print(" ".join(sentence)) # Goes through the list and finds a smaller word and convert the list of words into a single string, each word separated by a space.
    print(sentence)

wordsList()
</code>```

答:
This is what itertools.groupby is made for. First you'll need a function that gets the length of one word, which is built-in as len. Then you can sort using that keyfunction, and group using it too.

```<code>import itertools

some_lst = [...]  # user list of various length words
some_lst.sort(key=len)
groups = itertools.groupby(some_lst, key=len)
</code>```

This builds groups into a list of tuples. Each tuple has format:

```<code>(len(words), words_with_that_len)
</code>```

you're only really interested in the second element of each tuple, so pull that out.

```<code>result = [list(sublst) for _, sublst in groups]
</code>```

You could also build this yourself with collections.defaultdict

```<code>import collections

result_dict = collections.defaultdict(list)

for word in some_lst:
    result_dict[len(word)].append(word)
</code>```

result_dict is now a dictionary of lists. To get a sorted list of lists you can run it through a list comprehension with sorted and dict.items

```<code>result = [v for _,v in sorted(result_dict.items())]
</code>```

Body:
I have this code here: which takes user input and adds it to a list until they input to stop. At that point, it sorts the list items based on length.

What I am trying to do is put each word the user enters into a list of words with the same length. Like 2-letter words are put into one list, 3-letter words are put into another list.

When complete, I'm trying to return a list containing all of the individual word lists that were created.

So far all I have achieved is organizing them and then adding them to another list that outputs the list as many time as word entered.

def wordsList():
    stop = "stop"

    sentence = []
    sentence2 = []
    while True:
        word = input("Enter a word: ")
        if word == stop:
            # exit the loop
            break
        sentence.append(word)

        sentence.sort(key=len)
        cat= len(sentence)
        for sublist in sentence:

            sentence.append(sentence)
            # sublist.insert(sentence)
        # sentence2=[sentence]

    # print(" ".join(sentence)) # Goes through the list and finds a smaller word and convert the list of words into a single string, each word separated by a space.
    print(sentence)

wordsList()

Body:
This is what itertools.groupby is made for. First you'll need a function that gets the length of one word, which is built-in as len. Then you can sort using that keyfunction, and group using it too.

import itertools

some_lst = [...]  # user list of various length words
some_lst.sort(key=len)
groups = itertools.groupby(some_lst, key=len)

This builds groups into a list of tuples. Each tuple has format:

(len(words), words_with_that_len)

you're only really interested in the second element of each tuple, so pull that out.

result = [list(sublst) for _, sublst in groups]

You could also build this yourself with collections.defaultdict

import collections

result_dict = collections.defaultdict(list)

for word in some_lst:
    result_dict[len(word)].append(word)

result_dict is now a dictionary of lists. To get a sorted list of lists you can run it through a list comprehension with sorted and dict.items

result = [v for _,v in sorted(result_dict.items())]


问:
Saved file using AudioKit AKOfflineRenderNode not right
I am using AudioKit to mix WAV files together with MIDI files.
I also need to save the result in a separate file.

To mix the WAVs and MIDIs I am using an AKMIDISampler with an AKSequencer like this:

```<code>func add(track: MixerTrack) -> Bool {
    do{
        let trackSampler = AKMIDISampler()
        try trackSampler.loadWav(track.instrument.fileName)
        trackSampler.connect(to: mixer)

        let sequencer = AKSequencer(filename: track.midi.fileName)
        sequencer.setTempo(Double(tempo))
        sequencer.setRate(rate)
        sequencer.setGlobalMIDIOutput(trackSampler.midiIn)
        sequencer.enableLooping()
        sequencer.enableLooping()
        sequencers.append(sequencer)
        tracks.append(track)

        return true
    } catch {
        return false
    }
}
</code>```

I am using the SongProcessor example from AudioKit's examples for ideas on how to use AKOfflineRenderNode.

The thing is the example works with AKAudioPlayer instances and not sequencers as I am using. I believe I cannot use players because I need to mix the WAV and MIDI files, and I was only able to achieve that using sequencers.

My first question is: Is it possible to create files from sequencers the same way it is done in SongProcessor with players?

I was able to save an m4a file but the result is weird. First, if I don't set the rate manually to a number like 40, it is veeery slow to play all the notes. And when I set ti to a value like that,I can hear the sequence playing but at wrong rates. At some moments the beats play correctly but they often start playing too slow or too fast at different times.

Is there something I am doing wrong? Is this a bug with AKOfflineRenderNode or is it just not mean to be used like this?

Here is the code I use to save the mix to disk:

```<code>    func saveMixToDisk() -> URL? {
    do {
        let fileManager = FileManager.default
        let name = UUID().uuidString.appending(".m4a")
        let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
        let fileURL = documentDirectory.appendingPathComponent(name)

        offlineRender.internalRenderEnabled = false

        let duration = sequencers.first!.length.seconds
        for sequencer in sequencers {
            sequencer.stop()
            sequencer.setTime(AKDuration(seconds: 0).musicTimeStamp)
            sequencer.rewind()
        }

        for sequencer in sequencers {
            sequencer.setRate(40) // I would like to find a way to avoid having to set this, since this value is hardcoded and I don't know how to find the correct one. (When I only play through the sequencer inside the app the rate is perfect, but it gets messed up when rendering to URL)
            sequencer.play()
        }

        try offlineRender.renderToURL(fileURL, seconds: duration * 10)

        for sequencer in sequencers {
            sequencer.stop()
            sequencer.setTime(AKDuration(seconds: 0).musicTimeStamp)
            sequencer.rewind()
        }

        offlineRender.internalRenderEnabled = true

        return fileURL
    } catch let error {
        print(error)
        return nil
    }
}
</code>```

Any help is very much appreciated. I can't seem to be able to get this to work, and sadly I don't know of any other options in iOS to achieve what I need.

答: Instead of using AKOfflineRender, try the new AudioKit.renderToFile in AudioKit 4.0.4:  https://github.com/AudioKit/AudioKit/commit/09aedf7c119a399ab00026ddfb91ae6778570176</p>

Body:
I am using AudioKit to mix WAV files together with MIDI files.
I also need to save the result in a separate file.

To mix the WAVs and MIDIs I am using an AKMIDISampler with an AKSequencer like this:

func add(track: MixerTrack) -> Bool {
    do{
        let trackSampler = AKMIDISampler()
        try trackSampler.loadWav(track.instrument.fileName)
        trackSampler.connect(to: mixer)

        let sequencer = AKSequencer(filename: track.midi.fileName)
        sequencer.setTempo(Double(tempo))
        sequencer.setRate(rate)
        sequencer.setGlobalMIDIOutput(trackSampler.midiIn)
        sequencer.enableLooping()
        sequencer.enableLooping()
        sequencers.append(sequencer)
        tracks.append(track)

        return true
    } catch {
        return false
    }
}

I am using the SongProcessor example from AudioKit's examples for ideas on how to use AKOfflineRenderNode.

The thing is the example works with AKAudioPlayer instances and not sequencers as I am using. I believe I cannot use players because I need to mix the WAV and MIDI files, and I was only able to achieve that using sequencers.

My first question is: Is it possible to create files from sequencers the same way it is done in SongProcessor with players?

I was able to save an m4a file but the result is weird. First, if I don't set the rate manually to a number like 40, it is veeery slow to play all the notes. And when I set ti to a value like that,I can hear the sequence playing but at wrong rates. At some moments the beats play correctly but they often start playing too slow or too fast at different times.

Is there something I am doing wrong? Is this a bug with AKOfflineRenderNode or is it just not mean to be used like this?

Here is the code I use to save the mix to disk:

    func saveMixToDisk() -> URL? {
    do {
        let fileManager = FileManager.default
        let name = UUID().uuidString.appending(".m4a")
        let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
        let fileURL = documentDirectory.appendingPathComponent(name)

        offlineRender.internalRenderEnabled = false

        let duration = sequencers.first!.length.seconds
        for sequencer in sequencers {
            sequencer.stop()
            sequencer.setTime(AKDuration(seconds: 0).musicTimeStamp)
            sequencer.rewind()
        }

        for sequencer in sequencers {
            sequencer.setRate(40) // I would like to find a way to avoid having to set this, since this value is hardcoded and I don't know how to find the correct one. (When I only play through the sequencer inside the app the rate is perfect, but it gets messed up when rendering to URL)
            sequencer.play()
        }

        try offlineRender.renderToURL(fileURL, seconds: duration * 10)

        for sequencer in sequencers {
            sequencer.stop()
            sequencer.setTime(AKDuration(seconds: 0).musicTimeStamp)
            sequencer.rewind()
        }

        offlineRender.internalRenderEnabled = true

        return fileURL
    } catch let error {
        print(error)
        return nil
    }
}

Any help is very much appreciated. I can't seem to be able to get this to work, and sadly I don't know of any other options in iOS to achieve what I need.


问:
compare arrays with repetitive elements and add the elements not present to the respective arrays including the repetitive elements
I am working on a program where we compare two strings and add the characters that are not present in one string to the other string and vice versa.
For example: String 1- aabccd
             String 2- acccdd
The output should be- Characters to be added to String 1- cd
                      Characters to be added to String 2- ab
I am able to achieve it when the characters are not repeating,
For example: String 1- mango
             String 2- anglo
The output is- Characters to be added to String 1- l
               Characters to be added to String 2- m
but could not get it when the characters are repeating.

Here is the code that I have written-

```<code>import java.util.Scanner;

public class Test {

public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);

        String S1, S2;

        System.out.println("Enter String 1: ");
        S1 = user_input.next();

        System.out.println("Enter String 2: ");
        S2 = user_input.next();

        user_input.close();

        char[] S1Array = S1.toLowerCase().toCharArray();
        char[] S2Array = S2.toLowerCase().toCharArray();
        charAddition(S1Array, S2Array);
        charAdditionReverse(S2Array,S1Array);
}
private static void charAddition(char[] n, char[] S1Array) {
for (char n1 : n) {
            if (!isPresent(n1, S1Array)) {
                System.out.println("character to be added to S2Array
is: " + n1);
            }
        }
}
private static void charAdditionReverse(char[] n, char[] S1Array) {
for (char n1 : n) {
            if (!isPresent(n1, S1Array)) {
                System.out.println("character to be added to S1Array
is: " + n1);

            }
        }
}

    private static boolean isPresent(char n, char[] S1Array) {
        for (char i : S1Array) {
            if (n == i) {
                return true;
            }
        }
        return false;
    }
}
</code>```

答:
Here is your solution:

```<code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

public class Test {

    public static void main(String[] args) {
        Scanner user_input = new Scanner(System.in);

        String S1, S2;

        System.out.println("Enter String 1: ");
        S1 = user_input.next();

        System.out.println("Enter String 2: ");
        S2 = user_input.next();

        user_input.close();

        char[] S1Array = S1.toLowerCase().toCharArray();
        char[] S2Array = S2.toLowerCase().toCharArray();
        charAddition(S1Array, S2Array,false);
        charAddition(S2Array,S1Array,true);
    }
    private static void charAddition(char[] n, char[] S1Array,boolean isreverse)
    {

        List<char[]> asList = Arrays.asList(S1Array); // because this DOES compile.

        List<Character> wordlist = new ArrayList<Character>();
        for (char c : S1Array) {
            wordlist.add(c);
        }

        for (char n1 : n)
        {
            if (!isPresent(n1, wordlist))
            {
                if(!isreverse)
                {
                    System.out.println("character to be added to S2Arrayis: " + n1);

                }else
                {
                    System.out.println("character to be added to S1Arrayis: " + n1);
                }
            }
        }
    }

    private static boolean isPresent(char n, List<Character> S1Array)
    {
        boolean flag ;
        for (Iterator<Character> it = S1Array.iterator(); it.hasNext();)
        {
            char i = it.next();
            if (n == i)
            {
                it.remove();
                return true;
            }
        }
        return false;
    }
}
</code>```

To solve above problem, you have to check how many times a specific character repeats. that's why I created new array list from array passed ArrayList to the function and removed the elements which are already matched. I have changed 2 function into one as i felt it is better way to write code.

Body:
I am working on a program where we compare two strings and add the characters that are not present in one string to the other string and vice versa.
For example: String 1- aabccd
             String 2- acccdd
The output should be- Characters to be added to String 1- cd
                      Characters to be added to String 2- ab
I am able to achieve it when the characters are not repeating,
For example: String 1- mango
             String 2- anglo
The output is- Characters to be added to String 1- l
               Characters to be added to String 2- m
but could not get it when the characters are repeating.

Here is the code that I have written-

import java.util.Scanner;

public class Test {

public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);

        String S1, S2;

        System.out.println("Enter String 1: ");
        S1 = user_input.next();

        System.out.println("Enter String 2: ");
        S2 = user_input.next();

        user_input.close();

        char[] S1Array = S1.toLowerCase().toCharArray();
        char[] S2Array = S2.toLowerCase().toCharArray();
        charAddition(S1Array, S2Array);
        charAdditionReverse(S2Array,S1Array);
}
private static void charAddition(char[] n, char[] S1Array) {
for (char n1 : n) {
            if (!isPresent(n1, S1Array)) {
                System.out.println("character to be added to S2Array
is: " + n1);
            }
        }
}
private static void charAdditionReverse(char[] n, char[] S1Array) {
for (char n1 : n) {
            if (!isPresent(n1, S1Array)) {
                System.out.println("character to be added to S1Array
is: " + n1);

            }
        }
}

    private static boolean isPresent(char n, char[] S1Array) {
        for (char i : S1Array) {
            if (n == i) {
                return true;
            }
        }
        return false;
    }
}

Body:
Here is your solution:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

public class Test {

    public static void main(String[] args) {
        Scanner user_input = new Scanner(System.in);

        String S1, S2;

        System.out.println("Enter String 1: ");
        S1 = user_input.next();

        System.out.println("Enter String 2: ");
        S2 = user_input.next();

        user_input.close();

        char[] S1Array = S1.toLowerCase().toCharArray();
        char[] S2Array = S2.toLowerCase().toCharArray();
        charAddition(S1Array, S2Array,false);
        charAddition(S2Array,S1Array,true);
    }
    private static void charAddition(char[] n, char[] S1Array,boolean isreverse)
    {

        List<char[]> asList = Arrays.asList(S1Array); // because this DOES compile.

        List<Character> wordlist = new ArrayList<Character>();
        for (char c : S1Array) {
            wordlist.add(c);
        }

        for (char n1 : n)
        {
            if (!isPresent(n1, wordlist))
            {
                if(!isreverse)
                {
                    System.out.println("character to be added to S2Arrayis: " + n1);

                }else
                {
                    System.out.println("character to be added to S1Arrayis: " + n1);
                }
            }
        }
    }

    private static boolean isPresent(char n, List<Character> S1Array)
    {
        boolean flag ;
        for (Iterator<Character> it = S1Array.iterator(); it.hasNext();)
        {
            char i = it.next();
            if (n == i)
            {
                it.remove();
                return true;
            }
        }
        return false;
    }
}

To solve above problem, you have to check how many times a specific character repeats. that's why I created new array list from array passed ArrayList to the function and removed the elements which are already matched. I have changed 2 function into one as i felt it is better way to write code.


问:
Editing .sol-files
I am looking for a way to edit .sol-files (LSO/Local Shared Object). I have tried searching quite a bit, but I have not been able to find any program that can edit AS3-files properly. Is there a solution for me out there?</p>

答:
ActionScript Viewer includes SOL Viewer and Editor which can view/edit these files.

http://www.buraks.com/asv/tools/sve.html

ASV SOL Viewer and Editor adds 'View and Edit SOL Files' option to ASV.

SOL (Local Shared Object) files are created by SWF files to store persistent data on the user's computer, similar to a cookie.

With ASV SOL Viewer and Editor you can,

Open and view SOL files,

Edit contents of SOL files,

Create new SOL files.

Title: Editing .sol-files


问:
strange misalignment between divs container due to internal font-size elements
I'm experiencing a little problem, probably trivial, that I can't really solve. I've two div's, each containing a div with some text inside.
I noticed that changing the font height within those two inner containers, misaligns the outer ones. I know i could probably play with absolute positions, but can someone tell me why?

body {
  margin: 0;
}

.outBox {
  width: 300px;
  height: 300px;
  background: rgb(173, 247, 136);
  display: inline-flex;
  align-items: center;
}

.inBox {
  width: 120px;
  background: rgba(53, 186, 222, 1);
  margin: 0 auto;
  text-align: center;
  padding: 5px;
}

.inBox h2 {
  margin: 0;
  font-size: 16px;
  color: white;
}

.inBox p {
  margin: 0;
  font-size: 18px;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outBox">
  <div class="inBox">
    <h2>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</h2>
  </div>
</div>
<div class="outBox">
  <div class="inBox">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
  </div>
</div></code>```

答: I'm sure someone will come along who can explain why inline-flex on an element differs to flex on the parent (I don't fully understand it), but I do know that if you take off the "display: inline-flex" on your outBox, and put them inside a container element with "display: flex" (or put that on the body), it will solve your problem.</p>

Body:
I'm experiencing a little problem, probably trivial, that I can't really solve. I've two div's, each containing a div with some text inside.
I noticed that changing the font height within those two inner containers, misaligns the outer ones. I know i could probably play with absolute positions, but can someone tell me why?

body {
  margin: 0;
}

.outBox {
  width: 300px;
  height: 300px;
  background: rgb(173, 247, 136);
  display: inline-flex;
  align-items: center;
}

.inBox {
  width: 120px;
  background: rgba(53, 186, 222, 1);
  margin: 0 auto;
  text-align: center;
  padding: 5px;
}

.inBox h2 {
  margin: 0;
  font-size: 16px;
  color: white;
}

.inBox p {
  margin: 0;
  font-size: 18px;
  color: white;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

Lorem ipsum dolor sit amet, consectetur adipisicing elit.


问:
Understanding how for Loops works when we have ArrayObject(p + j);
I am trying to understand this piece of code

```<code>for (int j = 0; j < outputArray.size() - 5 -1; j++) {
                double sum = 0;
                for (p = 0; p < 5; p++) {
                    //weighted sum
                    sum += weights[p] * outputArray.get(p + j);
                }
</code>```

In the line Sum where there is (P +J) how does it work?
Now I think every weight ranging from o - 5 is multiplied by outputArray from 0-5 respectively, I mean weight 0 * outputArray[0] etc , so what is the role of j?

答:
For each loop in the first loop do a loop in the second one (in the second one the value of j will be keep)

Try it out to see what happens:

```<code>for (int j = 0; j < 3; j++) {
    for (int p = 0; p < 3; p++) {
        System.out.println(j + "<j:p>" + p);
    }
}
</code>```

That will print:

```<code>0<j:p>0
0<j:p>1
0<j:p>2
1<j:p>0
1<j:p>1
1<j:p>2
2<j:p>0
2<j:p>1
2<j:p>2
</code>```

In your case:

```<code>sum += weights[p] * outputArray.get(p + j);
</code>```

Will be executed outputArraySize (outer loop) * 5 (inner loop) and the values of p and p + j will range like: (assuming j = 2 and p <= 2 to make it easy)

```<code>p=0 j=0 p+j= 0
p=0 j=1 p+j= 1
p=1 j=0 p+j= 1
p=1 j=1 p+j= 2
p=2 j=0 p+j= 2
p=2 j=1 p+j= 3
</code>```

Body:
I am trying to understand this piece of code

for (int j = 0; j < outputArray.size() - 5 -1; j++) {
                double sum = 0;
                for (p = 0; p < 5; p++) {
                    //weighted sum
                    sum += weights[p] * outputArray.get(p + j);
                }

In the line Sum where there is (P +J) how does it work?
Now I think every weight ranging from o - 5 is multiplied by outputArray from 0-5 respectively, I mean weight 0 * outputArray[0] etc , so what is the role of j?

Body:
For each loop in the first loop do a loop in the second one (in the second one the value of j will be keep)

Try it out to see what happens:

for (int j = 0; j < 3; j++) {
    for (int p = 0; p < 3; p++) {
        System.out.println(j + "<j:p>" + p);
    }
}

That will print:

0<j:p>0
0<j:p>1
0<j:p>2
1<j:p>0
1<j:p>1
1<j:p>2
2<j:p>0
2<j:p>1
2<j:p>2

In your case:

sum += weights[p] * outputArray.get(p + j);

Will be executed outputArraySize (outer loop) * 5 (inner loop) and the values of p and p + j will range like: (assuming j = 2 and p <= 2 to make it easy)

p=0 j=0 p+j= 0
p=0 j=1 p+j= 1
p=1 j=0 p+j= 1
p=1 j=1 p+j= 2
p=2 j=0 p+j= 2
p=2 j=1 p+j= 3


问:
How to remove beginning-digits only in R
I have some strings with digits and alpha characters in them. Some of the digits are important, but the ones at the beginning of the string (and only these) are unimportant. This is due to a peculiarity in how email addresses are stored. So the best example is:

x<-'12345johndoe23@gmail.com'
Should be transformed to johndoe23@gmail.com

unfortunately there are no spaces. I have tried gsub('[[:digit:]]+', '', x) but this removes all numbers, not just the beginning-ones

Edit: I have found some solutions in other languages: Python: Remove numbers at the beginning of a string

答:
Another  regex is : </p>

```<code>sub('^\\d+','',x)
</code>```

Body:
Another  regex is :

sub('^\\d+','',x)


问:
Unexpected result using AVG() on negative floats in mySQL
This query

```<code>SELECT *
FROM `rounds`
WHERE `user` = 18956 AND `handicapDifferential` IS NOT NULL
ORDER BY `handicapDifferential` DESC, `date` DESC
LIMIT 0, 2
</code>```

Gives expected result of two rows with -1.4 and -5.1 in handicapDifferential.  The field datatype is FLOAT.

Using AVG() on the same result with this query

```<code>SELECT AVG(`handicapDifferential`) as `avg`
FROM `rounds`
WHERE `user` = 18956 AND `handicapDifferential` IS NOT NULL
ORDER BY `handicapDifferential` DESC, `date` DESC
LIMIT 0, 2
</code>```

Gives -9.485714214188713 where I expect -3.25.

Here is a fiddle demonstrating the result and the issue:  http://sqlfiddle.com/#!9/32acd/3

What am I doing incorrectly here?

答:
Alter your query to

```<code>SELECT
  AVG(items.avg)
FROM
  (SELECT
    `handicapDifferential` AS `avg`
  FROM
    `rounds`
  WHERE `user` = 18956
    AND `handicapDifferential` IS NOT NULL
  ORDER BY `handicapDifferential` DESC,
    `date` DESC
  LIMIT 0, 2) items
</code>```

refer link

Explanation : AVG is a an aggregate keyword in MySQL and you should have given a result set as the input as per your requirement. But u called AVG as a member in your query.

Body:
This query

SELECT *
FROM `rounds`
WHERE `user` = 18956 AND `handicapDifferential` IS NOT NULL
ORDER BY `handicapDifferential` DESC, `date` DESC
LIMIT 0, 2

Gives expected result of two rows with -1.4 and -5.1 in handicapDifferential.  The field datatype is FLOAT.

Using AVG() on the same result with this query

SELECT AVG(`handicapDifferential`) as `avg`
FROM `rounds`
WHERE `user` = 18956 AND `handicapDifferential` IS NOT NULL
ORDER BY `handicapDifferential` DESC, `date` DESC
LIMIT 0, 2

Gives -9.485714214188713 where I expect -3.25.

Here is a fiddle demonstrating the result and the issue:  http://sqlfiddle.com/#!9/32acd/3

What am I doing incorrectly here?

Body:
Alter your query to

SELECT
  AVG(items.avg)
FROM
  (SELECT
    `handicapDifferential` AS `avg`
  FROM
    `rounds`
  WHERE `user` = 18956
    AND `handicapDifferential` IS NOT NULL
  ORDER BY `handicapDifferential` DESC,
    `date` DESC
  LIMIT 0, 2) items

refer link

Explanation : AVG is a an aggregate keyword in MySQL and you should have given a result set as the input as per your requirement. But u called AVG as a member in your query.


问:
how can i mix or and and in an if statement in bash?
i have this function that accepts 3 parameters , ech one contain of 4 numbers and a capital letter for example : "1234A"
and i want to print 1 if the second parameter is bigger than the third one and smaller than the first one ,
i wrote this function that i cutted the 4 numbers in a parameter for each parameter and the letter in diffrent paramater for each one and i began to compare
but the problem it print nothing !!

anyone know how to do things  in one if statement rather than two if statements ??

what i did :

```<code>function check {
    curr_letter=`echo "$1" | cut -c5`
    min_letter=`echo "$3" | cut -c5`
    sm_letter=`echo "$2" | cut -c5`
    curr_nums=`echo "$1" | cut -c1-4`
    min_nums=`echo "$3" | cut -c1-4`
    sm_nums=`echo "$2" | cut -c1-4`
    if [[ sm_nums -eq curr_nums && sm_letter < curr_letter ]] ; then
      if [[ sm_nums -eq min_nums && sm_letter > min_letter ]] ; then
        echo 1
      fi
      if [[ sm_nums > min_nums ]] ; then
        echo 1
      fi
    fi

    if [[ sm_nums < curr_nums ]] ; then
      if [[ sm_nums -eq min_nums && sm_letter > min_letter ]] ; then
        echo 1
      fi
      if [[ sm_nums > min_nums ]] ; then
        echo 1
      fi
    fi
}
</code>```

i get nothing when i test this in bash , i get an empty line..
this is how i tested it :

```<code>p=`check "1617B" "1617A" "0000A"` echo $p
</code>```

答:
You can omit the $ in variable names within arithmetic context ((...)).
Within [[ ... ]] you cannot omit it.

Instead of calling echo ... | cut -c..., you can easily extract substrings using Bash's very own syntax {var:start:length}.

Within a [[ ... ]] or ((...)),
use == instead of -eq.

Note however that < and > operators sort lexicographically within a [[ ... ]], but numerically in arithmetic context ((...)).
Therefore the string-valued variables (named *_letter in your example)
should be compared within [[ ... ]], the numeric variables (named *_nums in your example) should be compared within ((...)).

Like this:

```<code>function check() {
    curr_letter=${1:4:1}
    min_letter=${3:4:1}
    sm_letter=${2:4:1}
    curr_nums=${1:0:4}
    min_nums=${3:0:4}
    sm_nums=${2:0:4}

    if (( sm_nums == curr_nums )) && [[ $sm_letter < $curr_letter ]]; then
        if (( sm_nums == min_nums )) && [[ $sm_letter > $min_letter ]] ; then
            echo 1
        fi
        if (( sm_nums > min_nums )) ; then
            echo 1
        fi
    fi

    if (( sm_nums < curr_nums )) ; then
        if (( sm_nums == min_nums )) && [[ $sm_letter > $min_letter ]] ; then
            echo 1
        fi
        if (( sm_nums > min_nums )) ; then
            echo 1
        fi
    fi
}
</code>```

Lastly, instead of p=`check "1617B" "1617A" "0000A"`; echo $p,
better write like this:

```<code>echo $(check "1617B" "1617A" "0000A")
</code>```

Body:
i have this function that accepts 3 parameters , ech one contain of 4 numbers and a capital letter for example : "1234A"
and i want to print 1 if the second parameter is bigger than the third one and smaller than the first one ,
i wrote this function that i cutted the 4 numbers in a parameter for each parameter and the letter in diffrent paramater for each one and i began to compare
but the problem it print nothing !!

anyone know how to do things  in one if statement rather than two if statements ??

what i did :

function check {
    curr_letter=`echo "$1" | cut -c5`
    min_letter=`echo "$3" | cut -c5`
    sm_letter=`echo "$2" | cut -c5`
    curr_nums=`echo "$1" | cut -c1-4`
    min_nums=`echo "$3" | cut -c1-4`
    sm_nums=`echo "$2" | cut -c1-4`
    if [[ sm_nums -eq curr_nums && sm_letter < curr_letter ]] ; then
      if [[ sm_nums -eq min_nums && sm_letter > min_letter ]] ; then
        echo 1
      fi
      if [[ sm_nums > min_nums ]] ; then
        echo 1
      fi
    fi

    if [[ sm_nums < curr_nums ]] ; then
      if [[ sm_nums -eq min_nums && sm_letter > min_letter ]] ; then
        echo 1
      fi
      if [[ sm_nums > min_nums ]] ; then
        echo 1
      fi
    fi
}

i get nothing when i test this in bash , i get an empty line..
this is how i tested it :

p=`check "1617B" "1617A" "0000A"` echo $p

Body:
You can omit the $ in variable names within arithmetic context ((...)).
Within [[ ... ]] you cannot omit it.

Instead of calling echo ... | cut -c..., you can easily extract substrings using Bash's very own syntax {var:start:length}.

Within a [[ ... ]] or ((...)),
use == instead of -eq.

Note however that < and > operators sort lexicographically within a [[ ... ]], but numerically in arithmetic context ((...)).
Therefore the string-valued variables (named *_letter in your example)
should be compared within [[ ... ]], the numeric variables (named *_nums in your example) should be compared within ((...)).

Like this:

function check() {
    curr_letter=${1:4:1}
    min_letter=${3:4:1}
    sm_letter=${2:4:1}
    curr_nums=${1:0:4}
    min_nums=${3:0:4}
    sm_nums=${2:0:4}

    if (( sm_nums == curr_nums )) && [[ $sm_letter < $curr_letter ]]; then
        if (( sm_nums == min_nums )) && [[ $sm_letter > $min_letter ]] ; then
            echo 1
        fi
        if (( sm_nums > min_nums )) ; then
            echo 1
        fi
    fi

    if (( sm_nums < curr_nums )) ; then
        if (( sm_nums == min_nums )) && [[ $sm_letter > $min_letter ]] ; then
            echo 1
        fi
        if (( sm_nums > min_nums )) ; then
            echo 1
        fi
    fi
}

Lastly, instead of p=`check "1617B" "1617A" "0000A"`; echo $p,
better write like this:

echo $(check "1617B" "1617A" "0000A")


答:
Try wrapping the divs in a "wrapper" with it display set to "flex"

```<code>.wrapper {
</code>```

display: flex;
}

body {
        margin: 0;
      }

.wrapper {
  display: flex;

}
      .outBox {
        width: 300px;
        height: 300px;
        background: rgb(173, 247, 136);
        display: inline-flex;
        align-items: center;

      }

      .inBox {
        width: 120px;
        background: rgba(53, 186, 222, 1);
        margin: 0 auto;
        text-align: center;
        padding: 5px;
      }

      .inBox h2 {
        margin: 0px;
        font-size: 16px;

        color: white;

      }

      .inBox p {
        margin: 0px;
        font-size: 18px;
        color: white;
      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">

  <div class="outBox">

  <div class="inBox">
    <h2>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</h2>
  </div>

</div>

<div class="outBox">

  <div class="inBox">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
  </div>

</div>

</div></code>```

Title: strange misalignment between divs container due to internal font-size elements

Body:
Try wrapping the divs in a "wrapper" with it display set to "flex"

.wrapper {

display: flex;
}

body {
        margin: 0;
      }

.wrapper {
  display: flex;

}
      .outBox {
        width: 300px;
        height: 300px;
        background: rgb(173, 247, 136);
        display: inline-flex;
        align-items: center;

      }

      .inBox {
        width: 120px;
        background: rgba(53, 186, 222, 1);
        margin: 0 auto;
        text-align: center;
        padding: 5px;
      }

      .inBox h2 {
        margin: 0px;
        font-size: 16px;

        color: white;

      }

      .inBox p {
        margin: 0px;
        font-size: 18px;
        color: white;
      }

<div class="wrapper">

  <div class="outBox">

  <div class="inBox">
    <h2>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</h2>
  </div>

</div>

<div class="outBox">

  <div class="inBox">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
  </div>

</div>

</div>


问:
Approximating a sphere in OpenGL
I am trying to approximate a sphere using the instructions at http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/sphere_cylinder/, but it doesn't look right at all. This is my code:

```<code>def draw_sphere(facets, radius=100):
    """approximate a sphere using a certain number of facets"""

    dtheta = 180.0 / facets
    dphi = 360.0 / facets

    global sphere_list
    sphere_list = glGenLists(2)
    glNewList(sphere_list, GL_COMPILE)

    glBegin(GL_QUADS)

    for theta in range(-90, 90, int(dtheta)):
        for phi in range(0, 360, int(dphi)):
            print theta, phi
            a1 = theta, phi
            a2 = theta + dtheta, phi
            a3 = theta + dtheta, phi + dphi
            a4 = theta, phi + dphi

            angles = [a1, a2, a3, a4]

            print 'angles: %s' % (angles)

            glColor4f(theta/360.,phi/360.,1,0.5)

            for angle in angles:
                x, y, z = angle_to_coords(angle[0], angle[1], radius)
                print 'coords: %s,%s,%s' % (x, y, z)
                glVertex3f(x, y, z)

    glEnd()

    glEndList()

def angle_to_coords(theta, phi, radius):
    """return coordinates of point on sphere given angles and radius"""

    x = cos(theta) * cos(phi)
    y = cos(theta) * sin(phi)
    z = sin(theta)

    return x * radius, y * radius, z * radius
</code>```

It seems that some of the quads aren't simple, i.e. the edges are crossing, but changing the order of the vertices doesn't seem to make any difference.

答:
I don't have a system here that can run Python and OpenGL together, but I can see a few issues anyway:

You're rounding dphi and dtheta in the range statements.  This means that the facets will always start on a whole degree, but then when you add the unrounded delta values the far edge isn't guaranteed to do so.  This is the probable cause of your overlaps.

It would be better to have your range values go from 0 .. facets-1 and then multiply those indices by 360 / facets (or 180 for the latitude lines) exactly.  This would avoid the rounding errors, e.g.:

```<code>dtheta = 180.0 / facets
dphi = 360.0 / facets

for y in range(facets):
    theta = y * dtheta - 90
    for x in range(facets):
        phi = x * dphi
        ...
</code>```

Also, are you converting to radians somewhere else?   Python's default trig functions take radians rather than degrees.

Title: Approximating a sphere in OpenGL

Body:
I am trying to approximate a sphere using the instructions at http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/sphere_cylinder/, but it doesn't look right at all. This is my code:

def draw_sphere(facets, radius=100):
    """approximate a sphere using a certain number of facets"""

    dtheta = 180.0 / facets
    dphi = 360.0 / facets

    global sphere_list
    sphere_list = glGenLists(2)
    glNewList(sphere_list, GL_COMPILE)

    glBegin(GL_QUADS)

    for theta in range(-90, 90, int(dtheta)):
        for phi in range(0, 360, int(dphi)):
            print theta, phi
            a1 = theta, phi
            a2 = theta + dtheta, phi
            a3 = theta + dtheta, phi + dphi
            a4 = theta, phi + dphi

            angles = [a1, a2, a3, a4]

            print 'angles: %s' % (angles)

            glColor4f(theta/360.,phi/360.,1,0.5)

            for angle in angles:
                x, y, z = angle_to_coords(angle[0], angle[1], radius)
                print 'coords: %s,%s,%s' % (x, y, z)
                glVertex3f(x, y, z)

    glEnd()

    glEndList()

def angle_to_coords(theta, phi, radius):
    """return coordinates of point on sphere given angles and radius"""

    x = cos(theta) * cos(phi)
    y = cos(theta) * sin(phi)
    z = sin(theta)

    return x * radius, y * radius, z * radius

It seems that some of the quads aren't simple, i.e. the edges are crossing, but changing the order of the vertices doesn't seem to make any difference.

Body:
I don't have a system here that can run Python and OpenGL together, but I can see a few issues anyway:

You're rounding dphi and dtheta in the range statements.  This means that the facets will always start on a whole degree, but then when you add the unrounded delta values the far edge isn't guaranteed to do so.  This is the probable cause of your overlaps.

It would be better to have your range values go from 0 .. facets-1 and then multiply those indices by 360 / facets (or 180 for the latitude lines) exactly.  This would avoid the rounding errors, e.g.:

dtheta = 180.0 / facets
dphi = 360.0 / facets

for y in range(facets):
    theta = y * dtheta - 90
    for x in range(facets):
        phi = x * dphi
        ...

Also, are you converting to radians somewhere else?   Python's default trig functions take radians rather than degrees.


问:
PHP - Store a SELECT Query and use it inside a INSERT query
Hi i'm having trouble using the data from a select query inside a insert query.

This is my php code -

```<code>   <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbName = "arestaurant";

    $ID = $_GET["Id"];
    $QUANTITY = $_GET["Quantity"];
    $TABLE = $_GET["Table"];

    //Make connection
    $conn = new mysqli($servername,$username,$password,$dbName);
    // check connection
    if(!$conn) {
        die("Connection Failed. ".mysqli_connect_error());
    }

    $sql = "INSERT INTO tableorders (tableNumber,isPaid)
            VALUES ('".$TABLE."','0')";
    $result = mysqli_query($conn,$sql);

    $y = "SELECT orderId from tableorders WHERE tableNumber='$TABLE' ORDER by orderDate DESC limit 1 offset 0 ";
    $resulty = mysqli_query($conn,$y);

    if ($resulty !== false) {
    $value = mysqli_fetch_field($resulty);
    $orderid = $value['orderId']; < --  error

}

    $sqlquery = "INSERT INTO orderitems (orderId, productId, quantity)
            VALUES ('".$orderid."','".$ID."','".$QUANTITY."')";
    $result2 = mysqli_query($conn,$sqlquery);

?>
</code>```

but im getting -

Fatal error: Cannot use object of type stdClass as array on line 30.

I have several ways in storing it and then using it again, but i can seem to find the solution.

please help?

答:
The best solution is this:

https://dev.mysql.com/doc/refman/5.7/en/insert-select.html

You don't need to pull the data out to insert it back. Let the MySQL do it for you.

This is my take on the combined insert-select statement. Would you try it?

```<code>$sqlquery = "INSERT INTO orderitems (orderId, productId, quantity)
SELECT orderId, $ID, $QUANTITY from tableorders WHERE tableNumber='$TABLE' ORDER by orderDate DESC limit 1";
</code>```

I drop the offset because I didn't see the purpose of it.

Here is an example:

Imagine that there is table called tasks with many rows and we want to select an id value from it and insert it into this test table together with some external values.

```<code>mysql> create table test (id int, order_id int, product_id int);
Query OK, 0 rows affected (0.09 sec)

mysql> describe test;
+------------+---------+------+-----+---------+-------+
| Field      | Type    | Null | Key | Default | Extra |
+------------+---------+------+-----+---------+-------+
| id         | int(11) | YES  |     | NULL    |       |
| order_id   | int(11) | YES  |     | NULL    |       |
| product_id | int(11) | YES  |     | NULL    |       |
+------------+---------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> insert into test select id, 5, 6 from tasks order by id asc limit 1;
Query OK, 1 row affected (0.06 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> select * from test;
+------+----------+------------+
| id   | order_id | product_id |
+------+----------+------------+
|    1 |        5 |          6 |
+------+----------+------------+
1 row in set (0.00 sec)

mysql> insert into test(id, order_id, product_id) select id, 5, 6 from tasks order by id asc limit 1;
Query OK, 1 row affected (0.04 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> select * from test;
+------+----------+------------+
| id   | order_id | product_id |
+------+----------+------------+
|    1 |        5 |          6 |
|    1 |        5 |          6 |
+------+----------+------------+
2 rows in set (0.00 sec)

mysql>
</code>```

I hope that it shed some lights on the possibilities of the insert-select method

Body:
Hi i'm having trouble using the data from a select query inside a insert query.

This is my php code -

   <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbName = "arestaurant";

    $ID = $_GET["Id"];
    $QUANTITY = $_GET["Quantity"];
    $TABLE = $_GET["Table"];

    //Make connection
    $conn = new mysqli($servername,$username,$password,$dbName);
    // check connection
    if(!$conn) {
        die("Connection Failed. ".mysqli_connect_error());
    }

    $sql = "INSERT INTO tableorders (tableNumber,isPaid)
            VALUES ('".$TABLE."','0')";
    $result = mysqli_query($conn,$sql);

    $y = "SELECT orderId from tableorders WHERE tableNumber='$TABLE' ORDER by orderDate DESC limit 1 offset 0 ";
    $resulty = mysqli_query($conn,$y);

    if ($resulty !== false) {
    $value = mysqli_fetch_field($resulty);
    $orderid = $value['orderId']; < --  error

}

    $sqlquery = "INSERT INTO orderitems (orderId, productId, quantity)
            VALUES ('".$orderid."','".$ID."','".$QUANTITY."')";
    $result2 = mysqli_query($conn,$sqlquery);

?>

but im getting -

Fatal error: Cannot use object of type stdClass as array on line 30.

I have several ways in storing it and then using it again, but i can seem to find the solution.

please help?

Body:
The best solution is this:

https://dev.mysql.com/doc/refman/5.7/en/insert-select.html

You don't need to pull the data out to insert it back. Let the MySQL do it for you.

This is my take on the combined insert-select statement. Would you try it?

$sqlquery = "INSERT INTO orderitems (orderId, productId, quantity)
SELECT orderId, $ID, $QUANTITY from tableorders WHERE tableNumber='$TABLE' ORDER by orderDate DESC limit 1";

I drop the offset because I didn't see the purpose of it.

Here is an example:

Imagine that there is table called tasks with many rows and we want to select an id value from it and insert it into this test table together with some external values.

mysql> create table test (id int, order_id int, product_id int);
Query OK, 0 rows affected (0.09 sec)

mysql> describe test;
+------------+---------+------+-----+---------+-------+
| Field      | Type    | Null | Key | Default | Extra |
+------------+---------+------+-----+---------+-------+
| id         | int(11) | YES  |     | NULL    |       |
| order_id   | int(11) | YES  |     | NULL    |       |
| product_id | int(11) | YES  |     | NULL    |       |
+------------+---------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> insert into test select id, 5, 6 from tasks order by id asc limit 1;
Query OK, 1 row affected (0.06 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> select * from test;
+------+----------+------------+
| id   | order_id | product_id |
+------+----------+------------+
|    1 |        5 |          6 |
+------+----------+------------+
1 row in set (0.00 sec)

mysql> insert into test(id, order_id, product_id) select id, 5, 6 from tasks order by id asc limit 1;
Query OK, 1 row affected (0.04 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> select * from test;
+------+----------+------------+
| id   | order_id | product_id |
+------+----------+------------+
|    1 |        5 |          6 |
|    1 |        5 |          6 |
+------+----------+------------+
2 rows in set (0.00 sec)

mysql>

I hope that it shed some lights on the possibilities of the insert-select method


问:
Vue js toggle class inside a loop
I have a template like this :

```<code><div id="vue-instance">
  <ul>
    <li v-for="item in inventory" v-on:click="say()" v-bind:class="{active:isActive}" > {{ item.name }} - ${{ item.price }}
    </li>
  </ul>
</div>
</code>```

And from my "controller" :

```<code>var vm = new Vue({
 el: '#vue-instance',
  data: {
    inventory: [
      {name: 'MacBook Air', price: 1000},
      {name: 'MacBook Pro', price: 1800},
      {name: 'Lenovo W530', price: 1400},
      {name: 'Acer Aspire One', price: 300}
   ],
    isActive : false
 },
  methods: {
    say: function () {
      this.isActive = !this.isActive
    }
 }
</code>```

});

With this when i click one item from the list, all items are affected to active class. My question is how to toggle individual element?

Thank you.

答:
You need a active flag on each item to be able to track them individually.

For example:

```<code>{name: 'MacBook Air', price: 1000, isActive: false},
{name: 'MacBook Pro', price: 1800, isActive: true}
</code>```

You will then will be able to bind the class and click event to item.isActive by doing something like this:

```<code><li v-for="item in inventory" v-on:click="item.isActive = !item.isActive" v-bind:class="{active:item.isActive}" > {{ item.name }} - ${{ item.price }}
</li>
</code>```

Title: Vue js toggle class inside a loop

Body:
I have a template like this :

 {{ item.name }} - ${{ item.price }}

And from my "controller" :

var vm = new Vue({
 el: '#vue-instance',
  data: {
    inventory: [
      {name: 'MacBook Air', price: 1000},
      {name: 'MacBook Pro', price: 1800},
      {name: 'Lenovo W530', price: 1400},
      {name: 'Acer Aspire One', price: 300}
   ],
    isActive : false
 },
  methods: {
    say: function () {
      this.isActive = !this.isActive
    }
 }

});

With this when i click one item from the list, all items are affected to active class. My question is how to toggle individual element?

Thank you.

Body:
You need a active flag on each item to be able to track them individually.

For example:

{name: 'MacBook Air', price: 1000, isActive: false},
{name: 'MacBook Pro', price: 1800, isActive: true}

You will then will be able to bind the class and click event to item.isActive by doing something like this:

<li v-for="item in inventory" v-on:click="item.isActive = !item.isActive" v-bind:class="{active:item.isActive}" > {{ item.name }} - ${{ item.price }}
</li>


问:
using while loop does not save data to file in c
I want take input from user and then save that input into the file. In my below code if I remove my while loop then the file is appended but I want this loop so that user can enter data upto 500 characters.</p>

```<code>int main()
{
    char Buffer1[5];

    FILE *ot;
    fopen_s(&ot, "D:\\export1.txt", "a+");

    fseek(ot, 0L, SEEK_END);

    int sz = ftell(ot);

    printf("Enter Data.\n");

    while (sz<500) {

        for (int i = 0; i < 5; i++) {
            scanf_s("%c", &Buffer1[i]);
        }

        // write data to file

        for (int i = 0; i < 5; i++) {
            fputc(Buffer1[i], ot);
        }

         sz = ftell(ot);
    }

    fclose(ot);
    _gettch();
    return 0;
}
</code>```

答:
This implementation only works if the user appends exactly the amount of bytes necessary to make 500 bytes in total.

It might be easier to first check the filesize, then let the user enter at most 500 - filesize characters, and only after that append the userinput to the file.

Body:
I want take input from user and then save that input into the file. In my below code if I remove my while loop then the file is appended but I want this loop so that user can enter data upto 500 characters.

int main()
{
    char Buffer1[5];

    FILE *ot;
    fopen_s(&ot, "D:\\export1.txt", "a+");

    fseek(ot, 0L, SEEK_END);

    int sz = ftell(ot);

    printf("Enter Data.\n");

    while (sz<500) {

        for (int i = 0; i < 5; i++) {
            scanf_s("%c", &Buffer1[i]);
        }

        // write data to file

        for (int i = 0; i < 5; i++) {
            fputc(Buffer1[i], ot);
        }

         sz = ftell(ot);
    }

    fclose(ot);
    _gettch();
    return 0;
}