text:
Q: PySpark3 no attribute 'tzinfo' error when parsing yyyyMMddhhmmss into TimestampType() I have this csv file (test.csv) containing the following:

COLUMN_STRING;COLUMN_INT;COLUMN_TIMESTAMP
String_Value_1;123456;20131226224757
String_Value_2;234567;20141227234858
String_Value_3;345678;20151228214555

I'm trying to import the 3rd column timestamp yyyyMMddhhmmss into a TimestampType() with the following code:

from pyspark.sql.types import *
data = sc.textFile('test.csv')\
              .map(lambda s: s.split(";"))\
              .filter(lambda v: v[0] != 'COLUMN_STRING') \
              .map(lambda v: (v[0], int(v[1]), v[2]))

schema = StructType([StructField('COLUMN_STRING',StringType(),False),
             StructField('COLUMN_INT',IntegerType(),False),
             StructField('COLUMN_TIMESTAMP',TimestampType(),False)])

df = sqlContext.createDataFrame(data, schema)
df.take(2)

And when I run it in PySpark3 on a Spark 1.6.3 Cluster (HDP3.5), I get an error about the "'str' object has no attribute 'tzinfo'"...
This is a simplified example. I have to find how to import such yyyyMMddhhmmss as is in a TimestampType() without altering the original data, because this is a simplified test (my actual data is massive, so modifying source is NOT an option).
I included the error message below.
Any help appreciated / Thanks, MT

An error occurred while calling
z:org.apache.spark.sql.execution.EvaluatePython.takeAndServe.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 4 times, most recent failure: Lost task 0.3 in stage 0.0 (TID 3, 10.0.0.13): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/usr/hdp/current/spark-client/python/lib/pyspark.zip/pyspark/worker.py", line 111, in main
    process()
  File "/usr/hdp/current/spark-client/python/lib/pyspark.zip/pyspark/worker.py", line 106, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "/usr/hdp/current/spark-client/python/lib/pyspark.zip/pyspark/serializers.py", line 263, in dump_stream
    vs = list(itertools.islice(iterator, batch))
  File "/usr/hdp/current/spark-client/python/pyspark/sql/types.py", line 541, in toInternal
    return tuple(f.toInternal(v) for f, v in zip(self.fields, obj))
  File "/usr/hdp/current/spark-client/python/pyspark/sql/types.py", line 541, in <genexpr>
    return tuple(f.toInternal(v) for f, v in zip(self.fields, obj))
  File "/usr/hdp/current/spark-client/python/lib/pyspark.zip/pyspark/sql/types.py", line 435, in toInternal
    return self.dataType.toInternal(obj)
  File "/usr/hdp/current/spark-client/python/lib/pyspark.zip/pyspark/sql/types.py", line 190, in toInternal
    seconds = (calendar.timegm(dt.utctimetuple()) if dt.tzinfo
AttributeError: 'str' object has no attribute 'tzinfo'

    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:166)
    at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:207)
    at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:125)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:70)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:313)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:277)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:313)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:277)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:313)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:277)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:313)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:277)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:313)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:277)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
    at org.apache.spark.scheduler.Task.run(Task.scala:89)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:227)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1433)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1421)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1420)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1420)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:801)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:801)
    at scala.Option.foreach(Option.scala:236)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:801)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1642)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1601)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1590)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:622)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1831)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1844)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1857)
    at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:212)
    at org.apache.spark.sql.execution.EvaluatePython$$anonfun$takeAndServe$1.apply$mcI$sp(python.scala:126)
    at org.apache.spark.sql.execution.EvaluatePython$$anonfun$takeAndServe$1.apply(python.scala:124)
    at org.apache.spark.sql.execution.EvaluatePython$$anonfun$takeAndServe$1.apply(python.scala:124)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:56)
    at org.apache.spark.sql.DataFrame.withNewExecutionId(DataFrame.scala:2087)
    at org.apache.spark.sql.execution.EvaluatePython$.takeAndServe(python.scala:124)
    at org.apache.spark.sql.execution.EvaluatePython.takeAndServe(python.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:231)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:381)
    at py4j.Gateway.invoke(Gateway.java:259)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:209)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/usr/hdp/current/spark-client/python/lib/pyspark.zip/pyspark/worker.py", line 111, in main
    process()
  File "/usr/hdp/current/spark-client/python/lib/pyspark.zip/pyspark/worker.py", line 106, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "/usr/hdp/current/spark-client/python/lib/pyspark.zip/pyspark/serializers.py", line 263, in dump_stream
    vs = list(itertools.islice(iterator, batch))
  File "/usr/hdp/current/spark-client/python/pyspark/sql/types.py", line 541, in toInternal
    return tuple(f.toInternal(v) for f, v in zip(self.fields, obj))
  File "/usr/hdp/current/spark-client/python/pyspark/sql/types.py", line 541, in <genexpr>
    return tuple(f.toInternal(v) for f, v in zip(self.fields, obj))
  File "/usr/hdp/current/spark-client/python/lib/pyspark.zip/pyspark/sql/types.py", line 435, in toInternal
    return self.dataType.toInternal(obj)
  File "/usr/hdp/current/spark-client/python/lib/pyspark.zip/pyspark/sql/types.py", line 190, in toInternal
    seconds = (calendar.timegm(dt.utctimetuple()) if dt.tzinfo
AttributeError: 'str' object has no attribute 'tzinfo'

    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:166)
    at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:207)
    at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:125)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:70)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:313)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:277)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:313)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:277)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:313)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:277)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:313)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:277)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:313)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:277)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
    at org.apache.spark.scheduler.Task.run(Task.scala:89)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:227)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    ... 1 more

Traceback (most recent call last):
  File "/usr/hdp/current/spark-client/python/pyspark/sql/dataframe.py", line 306, in take
    self._jdf, num)
  File "/usr/hdp/current/spark-client/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py", line 813, in __call__
    answer, self.gateway_client, self.target_id, self.name)
  File "/usr/hdp/current/spark-client/python/pyspark/sql/utils.py", line 45, in deco
    return f(*a, **kw)
  File "/usr/hdp/current/spark-client/python/lib/py4j-0.9-src.zip/py4j/protocol.py", line 308, in get_return_value
    format(target_id, ".", name), value)
py4j.protocol.Py4JJavaError: An error occurred while calling z:org.apache.spark.sql.execution.EvaluatePython.takeAndServe.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 4 times, most recent failure: Lost task 0.3 in stage 0.0 (TID 3, 10.0.0.13): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/usr/hdp/current/spark-client/python/lib/pyspark.zip/pyspark/worker.py", line 111, in main
    process()
  File "/usr/hdp/current/spark-client/python/lib/pyspark.zip/pyspark/worker.py", line 106, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "/usr/hdp/current/spark-client/python/lib/pyspark.zip/pyspark/serializers.py", line 263, in dump_stream
    vs = list(itertools.islice(iterator, batch))
  File "/usr/hdp/current/spark-client/python/pyspark/sql/types.py", line 541, in toInternal
    return tuple(f.toInternal(v) for f, v in zip(self.fields, obj))
  File "/usr/hdp/current/spark-client/python/pyspark/sql/types.py", line 541, in <genexpr>
    return tuple(f.toInternal(v) for f, v in zip(self.fields, obj))
  File "/usr/hdp/current/spark-client/python/lib/pyspark.zip/pyspark/sql/types.py", line 435, in toInternal
    return self.dataType.toInternal(obj)
  File "/usr/hdp/current/spark-client/python/lib/pyspark.zip/pyspark/sql/types.py", line 190, in toInternal
    seconds = (calendar.timegm(dt.utctimetuple()) if dt.tzinfo
AttributeError: 'str' object has no attribute 'tzinfo'

    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:166)
    at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:207)
    at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:125)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:70)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:313)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:277)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:313)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:277)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:313)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:277)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:313)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:277)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:313)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:277)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
    at org.apache.spark.scheduler.Task.run(Task.scala:89)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:227)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1433)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1421)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1420)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1420)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:801)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:801)
    at scala.Option.foreach(Option.scala:236)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:801)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1642)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1601)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1590)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:622)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1831)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1844)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1857)
    at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:212)
    at org.apache.spark.sql.execution.EvaluatePython$$anonfun$takeAndServe$1.apply$mcI$sp(python.scala:126)
    at org.apache.spark.sql.execution.EvaluatePython$$anonfun$takeAndServe$1.apply(python.scala:124)
    at org.apache.spark.sql.execution.EvaluatePython$$anonfun$takeAndServe$1.apply(python.scala:124)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:56)
    at org.apache.spark.sql.DataFrame.withNewExecutionId(DataFrame.scala:2087)
    at org.apache.spark.sql.execution.EvaluatePython$.takeAndServe(python.scala:124)
    at org.apache.spark.sql.execution.EvaluatePython.takeAndServe(python.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:231)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:381)
    at py4j.Gateway.invoke(Gateway.java:259)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:209)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/usr/hdp/current/spark-client/python/lib/pyspark.zip/pyspark/worker.py", line 111, in main
    process()
  File "/usr/hdp/current/spark-client/python/lib/pyspark.zip/pyspark/worker.py", line 106, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "/usr/hdp/current/spark-client/python/lib/pyspark.zip/pyspark/serializers.py", line 263, in dump_stream
    vs = list(itertools.islice(iterator, batch))
  File "/usr/hdp/current/spark-client/python/pyspark/sql/types.py", line 541, in toInternal
    return tuple(f.toInternal(v) for f, v in zip(self.fields, obj))
  File "/usr/hdp/current/spark-client/python/pyspark/sql/types.py", line 541, in <genexpr>
    return tuple(f.toInternal(v) for f, v in zip(self.fields, obj))
  File "/usr/hdp/current/spark-client/python/lib/pyspark.zip/pyspark/sql/types.py", line 435, in toInternal
    return self.dataType.toInternal(obj)
  File "/usr/hdp/current/spark-client/python/lib/pyspark.zip/pyspark/sql/types.py", line 190, in toInternal
    seconds = (calendar.timegm(dt.utctimetuple()) if dt.tzinfo
AttributeError: 'str' object has no attribute 'tzinfo'

    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:166)
    at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:207)
    at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:125)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:70)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:313)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:277)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:313)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:277)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:313)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:277)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:313)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:277)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:313)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:277)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
    at org.apache.spark.scheduler.Task.run(Task.scala:89)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:227)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    ... 1 more

A: Schema should reflect the types you have so if you want to use RDD you should parse it first:
.map(lambda v: (
  v[0], int(v[1]), datetime.datetime.strptime(v[2], "%Y%m%d%H%M%S")))


text:
Q: Using the value from one column to slice the value of another column to generate a new column in Pandas My real pandas dataframe has 500,000 rows and 20 columns. I want to use the information from one column to slice the values from another column and return a new column with this information. Below is a simplified version of my dataframe and desired output. I need to use the value held in 'location' to know where to slice 'sentence' to return the information I am seeking to analyze 'animal'. For simplicity the location value and the location value minus 3 gives the splicing coordinates: for location value of 6 desired information (animal) is sentence[3:6].
I have been struggling with different methods including iteration (iterrows and itertuples) over the rows (which someone metioned is "rarely correct"), but I am concerned that I do not know how to do this properly as other say "NEVER iterate" and stress issues with it, and to "exhaust other options".  But I do not know the options and as far as I gotten so far, slicing is not as straight forward? What is the safest way and most professional way to do this? I don't care about speed.  I care about accuracy.
my_dict = {'sentence': [ 'Thedogwearsred', 'Thatcatatethebird', 'Thebigratstruggledwithpandas', 'Thebestdogwassmall'], 'location' = [6, 7, 9, 10]}
df = pd.DataFrame(my_dict)
Out[50]:
                       sentence  location
0                Thedogwearsred         6
1             Thatcatatethebird         7
2  Thebigratstruggledwithpandas         9
3            Thebestdogwassmall        10

Desired output:
Out[52]:
                       sentence  location animal
0                Thedogwearsred         6    dog
1             Thatcatatethebird         7    cat
2  Thebigratstruggledwithpandas         9    rat
3            Thebestdogwassmall        10    dog

A: Try:
df['animal'] = df.apply(lambda x: x['sentence'][x['location'] - 3 : x['location']], axis=1)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I configure a JDBC data source in JBoss AS 5.1.0.GA? Could somebody point me at or post an example of configuring a data source for JBoss 5.1.0.GA?
I am getting the following error when I try to hook up a data source to my web application in JBoss 5.1.0.GA using JNDI.

startup failed due to previous errors java.lang.RuntimeException: mapped-name is required for jdbc/jos of deployment jos-services-1.0.0-SNAPSHOT.war

My /WEB-INF/web.xml contains the following resource reference:
<resource-ref>
    <res-ref-name>jdbc/jos</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

I have configured /META-INF/jboss-web.xml as follows:
<?xml version="1.0" encoding="UTF-8"?>
<jboss-web
    xmlns="http://www.jboss.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.jboss.com/xml/ns/javaee
        http://www.jboss.org/j2ee/schema/jboss-web_5_1.xsd"
    version="5.1">
    <context-root>/services</context-root>
    <resource-ref>
        <res-ref-name>jdbc/jos</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <jndi-name>java:jos</jndi-name>
    </resource-ref>
</jboss-web>

And the jos-ds.xml file that defines the data source is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE datasources
    PUBLIC "-//JBoss//DTD JBOSS JCA Config 5.0//EN"
    "http://www.jboss.org/j2ee/dtd/jboss-ds_5_0.dtd">
<datasources>
    <xa-datasource>
        <jndi-name>jos</jndi-name>
        <xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class>
        <xa-datasource-property name="URL">${ie.courts.jos.datasource.url}</xa-datasource-property>
        <user-name>${ie.courts.jos.datasource.username}</user-name>
        <password>${ie.courts.jos.datasource.password}</password>
        <transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation>
        <min-pool-size>5</min-pool-size>
        <max-pool-size>100</max-pool-size>
        <blocking-timeout-millis>2000</blocking-timeout-millis>
        <idle-timeout-minutes>2</idle-timeout-minutes>
        <track-connection-by-tx />
        <valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name>
        <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
        <!--new-connection-sql></new-connection-sql-->
        <!--check-valid-connection-sql></check-valid-connection-sql-->
        <metadata>
            <type-mapping>mySQL</type-mapping>
        </metadata>
    </xa-datasource>
</datasources>

The stack trace that I get is:

14:17:17,573 ERROR [StandardContext] Context [/jos-services-1.0.0-SNAPSHOT] startup failed due to previous errors java.lang.RuntimeException: mapped-name is required for jdbc/jos of deployment jos-services-1.0.0-SNAPSHOT.war
       at org.jboss.web.tomcat.service.injection.WebResourceHandler.loadXmlResourceRefs(WebResourceHandler.java:178)
       at org.jboss.web.tomcat.service.injection.WebResourceHandler.loadXml(WebResourceHandler.java:327
       at org.jboss.web.tomcat.service.TomcatInjectionContainer.processMetadata(TomcatInjectionContainer.java:550)
       at org.jboss.web.tomcat.service.WebCtxLoader.start(WebCtxLoader.java:158)
       at org.apache.catalina.core.StandardContext.start(StandardContext.java:4272)
       at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeployInternal(TomcatDeployment.java:310)>
       at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeploy(TomcatDeployment.java:142)
       at org.jboss.web.deployers.AbstractWarDeployment.start(AbstractWarDeployment.java:461)
       at org.jboss.web.deployers.WebModule.startModule(WebModule.java:118)
       at org.jboss.web.deployers.WebModule.start(WebModule.java:97)
       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
       at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
       at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
       at java.lang.reflect.Method.invoke(Method.java:592)
       at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:157)
       at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96)
       at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
       at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
       at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:668)
       at org.jboss.system.microcontainer.ServiceProxy.invoke(ServiceProxy.java:206)
       at $Proxy38.start(Unknown Source)
       at org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:42)
       at org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:37)
       at org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62)
       at org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71)
       at org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51)
       at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
       at org.jboss.system.microcontainer.ServiceControllerContext.install(ServiceControllerContext.java:286)
       at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
       at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
       at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
       at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
       at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
       at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
       at org.jboss.system.ServiceController.doChange(ServiceController.java:688)
       at org.jboss.system.ServiceController.start(ServiceController.java:460)
       at org.jboss.system.deployers.ServiceDeployer.start(ServiceDeployer.java:163)
       at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:99)
       at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:46)
       at org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer.internalDeploy(AbstractSimpleRealDeployer.java:62)
       at org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:50)
       at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:171)
       at org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1439)
       at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1157)
       at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1178)
       at org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1098)
       at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
       at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
       at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
       at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
       at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
       at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
       at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
       at org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:781)
       at org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:702)
       at org.jboss.system.server.profileservice.repository.MainDeployerAdapter.process(MainDeployerAdapter.java:117)
       at org.jboss.system.server.profileservice.repository.ProfileDeployAction.install(ProfileDeployAction.java:70)
       at org.jboss.system.server.profileservice.repository.AbstractProfileAction.install(AbstractProfileAction.java:53)
       at org.jboss.system.server.profileservice.repository.AbstractProfileService.install(AbstractProfileService.java:361)
       at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
       at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
       at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
       at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
       at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
       at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
       at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
       at org.jboss.system.server.profileservice.repository.AbstractProfileService.activateProfile(AbstractProfileService.java:306)
       at org.jboss.system.server.profileservice.ProfileServiceBootstrap.start(ProfileServiceBootstrap.java:271)
       at org.jboss.bootstrap.AbstractServerImpl.start(AbstractServerImpl.java:461)
       at org.jboss.Main.boot(Main.java:221)
       at org.jboss.Main$1.run(Main.java:556)
       at java.lang.Thread.run(Thread.java:595)

A: That error is misleading, at least in my case, and the actual culprit being the XSD version. Change the XSD 5.1 to DTD 5.0 and it no more complain about the mapped-name.
Below is the WEB-INF/jboss-web.xml I m using now: (jboss-web.xml needs to be WEB-INF of your webapp)
<?xml version="1.0"?>
<!DOCTYPE jboss-web PUBLIC
        "-//JBoss//DTD Web Application 5.0//EN"
        "http://www.jboss.org/j2ee/dtd/jboss-web_5_0.dtd">
<jboss-web>
<context-root>/context_name</context-root>
    <resource-ref>
        <res-ref-name>jdbc/jndi_name</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <jndi-name>java:jndi_name</jndi-name>
    </resource-ref>
</jboss-web>

Though this is some what old question, I m mentioning how I solved the same issue with JBoss 5.1.0 GA, so that someone may find it useful

A: Souldn't you use such JNDI name (in jboss-web.xml  file):
<jndi-name>java:/jos</jndi-name>

A: Your jboss-web should look like:
<jboss-web>
    <!-- ... -->
    <resource-ref>
        <res-ref-name>jdbc/jos</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <jndi-name>java:/jos</jndi-name>
    </resource-ref>
</jboss-web>

Reference: http://docs.redhat.com/docs/en-US/JBoss_Enterprise_Application_Platform/5/html-single/Administration_And_Configuration_Guide/index.html Figure 6.14


text:
Q: Pygame and Open AI implementation Me and my classmate have decided to try and implement and AI agent into our own game. My friend have done most of the code, based on previous projects, and I was wondering how PyGame and OpenAI would work together. Have tried to do some research but can't really find any useful information about this specific topic. Some have said that it is hard to implement but some say it works. Either way, I'd like your opinion on this project and how you'd approach this if it was you.
The game is very basic (only has one input) and a linear difficulty. Basically you just try to dodge the green squares that spawn with the character (you) being centered to the screen. The space between the green squares are the same which means the spawn rate is exactly the same. Here's the code but it's not very well cleaned nor polished but our first example:
    import pygame
    import time

    start_time = time.time()
    pygame.init()

    win_dim = 800
    win = pygame.display.set_mode((win_dim, win_dim))

    class Char:

       def __init__(self, x, y, dim, score):

           self.x = x
           self.y = y

           self.dim = dim
           self.score = score

           self.vsp = 0

       def draw_char(self, color):

           pygame.draw.rect(win, (color[0], color[1], color[2]), (self.x, self.y, self.dim, self.dim))

       def jump(self):

           keys = pygame.key.get_pressed()

           if keys[pygame.K_SPACE] and self.y == 400:
               self.vsp = 5

           self.y -= self.vsp

           if self.y < 400:
               self.vsp -= 0.15
           else:
               self.y = 400

    class Cactus:

        def __init__(self, dim):

           self.dim = dim

           self.cac = []
           self.speed = 0

        def startcac(self, x):

           if x % 100 == 0:

               stop_time = time.time()
               self.cac.append(801)

           for i in range(0, len(self.cac)):

               if self.speed < 4:
                   self.speed = 1 + x * 0.0005
               else:
                   self.speed == 10

               self.cac[i] -= self.speed
               pygame.draw.rect(win, (0, 200, 0), (self.cac[i], 400, 20, 20))

           try:
               if self.cac[0] < 0:
                   self.cac.pop(0)
           except IndexError:
               pass

        def collision(self, blob_cords):

           if any(i in [int(i) for i in self.cac] for i in [i for i in range(380, 421)]) and blob_cords[1] >= 380:
               self.cac = []

           dist = 0

           if len(self.cac) >= 2:
               # print(self.cac[-1] - self.cac[-2], blob.x - 1)
               for i in self.cac:
                   if i > 400 + 20:
                       dist = (i - 400 - 20) / (self.cac[-1] - self.cac[-2])

                       break

           if dist <= 1:
               print(dist)
               print(self.speed / 4)

    blob = Char(400, 400, 20, 0)
    # "player"
    cac = Cactus(20)
    # obstacle

    x = 1

    if __name__ == '__main__':

       game = True
       while game:
           pygame.time.delay(1)

           for event in pygame.event.get():
               if event.type == pygame.QUIT:
                   game = False

           # Draws things on screen

           win.fill((0, 0, 0))
           blob.jump()
           blob.draw_char([150, 0, 0])
           cac.startcac(x)
           x += 1
           cac.collision((blob.x, blob.y))

           # Updates movements and events

           # Update display

           pygame.display.update()

       pygame.QUIT()

Really sorry for the sloppy code, if even needed, but some guidance to just start or revamp the project would be much appreciated.
Thanks!

A: PyGame and OpenAI-Gym work together fine. I can't comment on the game code you posted, that's up to you really. If the game works it works.
But to create an AI agent with PyGame you need to first convert your environment into a Gym environment. This can be done by following this guide.
Afterwards you can use an RL library to implement your agent. My recommendation is Stable-Baselines which is a great fork off of openai-baselines that's a lot easier to work with.
If you want something as reference for your assignment maybe check out this little project I did a while ago. I created a rendition of the BlockDude game and converted it to OpenAI Gym. I then used stable-baselines on it in this colab notebook.


text:
Q: How Do I Create a Sub-Folder via PHP? I am trying to create a directory that is inside of a folder called upload.  Here is my current simple code that I tried to get this done:
<?php

$thisdir = getcwd();
$new_dir = '145';

if(mkdir("/upload/" . $newdir, 0777))
{
echo "Directory has been created successfully...";
}
else
{
echo "Failed to create directory...";
}
?>

There must be some simple fix that I am missing.  Can you place it?  Thanks.

A: /upload/ is almost certainly wrong. It points to the "upload" directory in the root directory, where you most likely don't have the right to create one.
You probably mean upload/.

A: Your php daemon will not have permission, by default, to write inside a folder called /upload (/ being the root directory). You would need to make this folder write accessible for this command to work.
However, saying this, surely this problem is resulting from an error with your code and you aren't working within your current directory. I am guessing your code should read...
if(mkdir($thisdir . "/upload/" . $newdir, 0777))

In which case it should work fine.

A: //new folder  you want to create
$newfolder="145";
//get the current working directory.
$curdir= getcwd();
//append the "upload" folder which already exits in ur working directory alog with the new directory name  "$newfolder"
$dir= $curdir."\uploads"."/$newfolder";
//check if directory exits
if(is_dir($dir))
{
    echo " Directory exists";
}
else
{
    //create new directory recursively
    mkdir($dir,0777,true);
    echo " Directory Created";
}


text:
Q: Reference of Reference in C++ I see code on StackOverflow every once in a while, asking about some overload ambiguity with something involving a function like:
void foo(int&& param);

My question is: Why does this even come up? Or rather, when would you ever have "a reference to a reference"? How is that any different from a plain old reference? I've never run across this in real-world code, so I'm curious as to what kind of code would need this.

A: It's an rvalue reference. Note that the && token used for Boolean AND and rvalue references, and the & token used for bitwise AND and normal references, are different "words" as far as the language can tell.
An rvalue reference is (usually) bound to an object which may be left in an indeterminate state after the rvalue reference is finished, presumably because the object will then be destroyed.
Simply put, binding a variable to an rvalue reference is the usually the last thing you do to it.
Unlike a regular reference but like a const & reference, an rvalue reference can bind to an rvalue (an expression whose address cannot be directly taken). Like a regular reference but unlike a const & reference, an rvalue reference can be used to modify its object.

A: It's a rvalue reference, Bjarne describes it here.
Shameless copying ("quoting"):

The rvalue reference
An rvalue reference is a compound type
  very similar to C++'s traditional
  reference. To better distinguish these
  two types, we refer to a traditional
  C++ reference as an lvalue reference.
  When the term reference is used, it
  refers to both kinds of reference:
  lvalue reference and rvalue reference.
An lvalue reference is formed by
  placing an & after some type.
A a; A& a_ref1 = a;  // an lvalue reference

An rvalue reference is formed by
  placing an && after some type.
A a; A&& a_ref2 = a;  // an rvalue reference

An rvalue reference behaves just like
  an lvalue reference except that it can
  bind to a temporary (an rvalue),
  whereas you can not bind a (non const)
  lvalue reference to an rvalue.
A&  a_ref3 = A();  // Error!
A&& a_ref4 = A();  // Ok

A: It isn't a reference to a reference:  such a thing does not exist.
It is an rvalue reference, a new feature added in C++11.


text:
Q: Create new rows in Pandas Dataframe from cells like "A BCD 1-5" I have a CSV file that contains product inventory information. Currently some of the products are listed as groups of five, such as "A BCD 1-5", "A BCD 6-10", etc. I need to turn these groupings into 5 rows, so that each row would be in the format "A BCD 1", "A BCD 2", "A BCD 3", etc. I'm thinking that I'll need to use a bunch of different regular expressions to find the "1-5", "6-10" and create new rows from that, but am a bit stuck getting started.
df = pd.DataFrame([{'var1': 'a', 'var2': '1-5'},
           {'var1': 'b', 'var2': '6-10'}])

From this:
|Name|Inventory Number|
|:---|---:|
|x|A BCD 1-5|
|x|A BCD 6-10|

To This:
|Name|Inventory Number|
|:---|---:|
|x|A BCD 1|
|x|A BCD 2|
|x|A BCD 3|
|x|A BCD 4|
|x|A BCD 5|
|x|A BCD 6|
|x|A BCD 7|
|x|A BCD 8|
|x|A BCD 9|
|x|A BCD 10|

A: Here's one way:
df[['Inventory Name', 'var2']] = df.pop(
    'Inventory Number').str.rsplit(' ', n=1, expand=True)
df = df.assign(var2=df.var2.str.split(
    '-').apply(lambda x: np.arange(int(x[0]), int(x[1])+1))).explode('var2')
df = df.astype(str).set_index('Name').agg(
    ' '.join, 1).reset_index(name='Inventory Number')

A: Another way:
>>>  df['Inventory Number'].str.extract(r'(.*) (\d+)-(\d+)') \
                           .dropna(how='all') \
                           .apply(lambda x: [f'{x[0]} {i}'
                                      for i in np.arange(int(x[1]), int(x[2])+1)],
                                  axis='columns').explode()

0     A BCD 1
0     A BCD 2
0     A BCD 3
0     A BCD 4
0     A BCD 5
1     A BCD 6
1     A BCD 7
1     A BCD 8
1     A BCD 9
1    A BCD 10
dtype: object


text:
Q: delete вызывает исключение #include<iostream>
#include<time.h>

using namespace std;

struct film {
    char name[150];
    char director[50];
    char genre[80];
    float rating;
    float price;
};

void show_info(film film);
void show_all(film arr[], int& length);
void surch_name(film arr[], int& length);
void surch_genre(film arr[], int& length);
void surch_director(film arr[], int& length);
film* most_rating_in_genre(film arr[], int& length);
film* append_film(film arr[], int& length);
void menu(film* arr, int& length);

int main() {
    setlocale(LC_ALL, "rus");
    film men_in_black = { "Men in black","Barry Sonnenfeld", "Advanture , Comedy",7.3f,8.9f };
    film star_wars_3 = { "Star Wars. Episode 3: Revenge of the Sith","George Lucas", "Fantasy, Adventure",7.5f,7.5f };
    film lord_of_the_rings_tfotr = { "Lord of the rings: The feelowship of the ring","Peter Jackson", "Advanture, Drama",8.8f,8.9f };
    film home_alone_1 = { "Home alone","Chris Columbus", "Comedy, Family",7.6f,10.9f };
    film it = { "It","Andy Muschietti","Horror",7.3f,6.9f };
    int length = 5;
    film* arr = new film[length]{
    men_in_black,
    star_wars_3,
    lord_of_the_rings_tfotr,
    home_alone_1,
    it };
    cout << "Добро пожаловать\n";

    menu(arr, length);

    return 0;
}

void show_info(film film) {
    cout << "Name - " << film.name << "\nDirector - " << film.director << "\nGenre - "
        << film.genre << "\nRating - " << film.rating << "\nPrice - " << film.price
        << "\n----------------------------------------------------------------------------------\n";
}

void show_all(film arr[], int& length) {
    for (int i = 0; i < length; i++)
    {
        show_info(arr[i]);
    }
}

void surch_name(film arr[], int& length) {

    char* name_usr = new char[150];
    char* name_arr = new char[150];
    cout << "Введите имя фильма :";
    cin>> name_usr;
    for (int i = 0; i < length; i++)
    {
        if (strstr(arr[i].name, name_usr) != NULL) {
            show_info(arr[i]);
        }
    }
}

void surch_genre(film arr[], int& length) {
    char genre[150];
    cout << "\nВведите имя режиссер : ";
    cin >> genre;
    for (int i = 0; i < length; i++)
    {
        if (strstr(arr[i].genre, genre) != NULL) {
            show_info(arr[i]);
        }
    }
}

void surch_director(film arr[], int& length) {
    char director[150];
    cout << "\nВведите имя режиссер : ";
    cin >> director;
    for (int i = 0; i < length; i++)
    {
        if (strstr(arr[i].director, director)) {
            show_info(arr[i]);
        }
    }
}

film* most_rating_in_genre(film arr[], int& length) {
    film* most_rating = nullptr;
    char genre[80];
    cout << "Введите жанр :";
    cin >> genre;
    for (int i = 0; i < length; i++)
    {
        if (strstr(arr[i].genre, genre) != NULL && arr[i].rating > most_rating->rating) {
            most_rating = &arr[i];
        }
    }
    return most_rating;
}

film* append_film(film arr[], int& length) {
    film* arr1 = new film[length + 1];
    for (int i = 0; i < length; i++)
    {
        arr1[i] = arr[i];
    }

    length++;
    film new_film;
    cout << "Введите название фильма : ";
    cin >> new_film.name;
    cout << "\nВведите имя режиссер : ";
    cin >> new_film.director;
    cout << "\nВведите название жанра : ";
    cin >> new_film.genre;
    cout << "\nВведите рейтинг фильма : ";
    cin >> new_film.rating;
    cout << "\nВведите цену фильма (m.q) : ";
    cin >> new_film.price;
    arr1[length] = new_film;
    cout << "\nФильм добавлен успешно";
    delete[] arr1;
    return arr1;
}

void menu(film* arr, int& length) {
    int choice;
    cout << "\n1.Показать все фильмы\n";
    cout << "2.Поиск фильма по имени\n";
    cout << "3.Поиск фильма по режисеру\n";
    cout << "4.Поиск фильма по жанру\n";
    cout << "5.Лучший фильм в жанре\n";
    cout << "6.Добавить фильм\n";
    cout << "0. Выйти\n\n";
    cout << "Введите пункт :";
    cin >> choice;
    switch (choice)
    {
    case 1:
        system("cls");
        show_all(arr, length);
        break;
    case 2:
        system("cls");
        surch_name(arr, length);//dodelar
        break;
    case 3:
        system("cls");
        surch_director(arr, length);
        break;
    case 4:
        system("cls");
        surch_genre(arr, length);
        break;
    case 5:
        system("cls");
        show_info(*most_rating_in_genre(arr,
            length));
        break;
    case 6:
        system("cls");
        arr = append_film(arr, length); //error
        break;
    case 0:

        return;
    default:

        break;
    }
    menu(arr, length);
}

На 130 строке вызывается исключение.Я не понимаю,почему оно возникает

A: Посмотрите на эти строки
delete[] arr1;
return arr1

после удаления массива, Вы его возвращаете. Круто. Вот только указатель после удаления "невалидный". Скорее всего хотелось удалить arr (без 1)
Теперь осмотрим чуточку глобальнее
film* append_film(film arr[], int& length) {
    film* arr1 = new film[length + 1]; // выделили массив
    for (int i = 0; i < length; i++)
    {
        arr1[i] = arr[i];
    }

    length++; // теперь length - размер массива arr1
    film new_film;
    /*[удалил, так как не важно]*/
    arr1[length] = new_film; // И запишем за пределы массива.
    cout << "\nФильм добавлен успешно";
    delete[] arr1;
    return arr1;
}

Явно увеличение length лишнее.
Может использовать вектор?

A: Выделили length+1 элемент. Т.е. последний - с индексом length.
film* arr1 = new film[length + 1];

Увеличили. Теперь последний с индексом length-1:
length++;

arr1[length] = new_film;

И куда вы пишете? За пределы массива. Как минимум, UB — все, что угодно...
delete[] arr1;
return arr1;

Ну, а уж это вообще ни в какие ворота — вернуть указатель на освобожденную память. Зачем?..


text:
Q: How to substitute table name I need to create a "common" grid with parameters.
The problem is that in the Delete action I cannot refer to the table as a variable
I use edmx model.
public ActionResult PartialView_GridCommonDelete(System.Int64 data_autoinc)
{
    var table = ViewBag.CurrentTable;
    var key= ViewBag.Key;

    if (data_autoinc != null)
    {
        try
        {
            //ERROR HERE
            var item = **ent.table**.FirstOrDefault(it => it.product_autoinc == data_autoinc);
            if (item != null)
                ent.tabla.Remove(item);
            ent.SaveChanges();
        }
        catch (Exception e)
        {
            ViewData["EditError"] = e.Message;
        }
    }

    return PartialView("PartialView_GridCommon", ViewBag.CurrentSql);
}

How can I dynamically substitute the table name so as I can use it with many tables?
Thank you

A: What you are trying to do is not achievable by ORM i.e. defining Table at runtime.
What you can try is:
context.Database.ExecuteSqlCommand("TRUNCATE TABLE [TableName]");

You can explicitly pass table name and fire your sql query
Give it a try.
Thanks
Nipun


text:
Q: Problem with magic_quotes_gpc in PHP symfony I am using Symfony 1.4 and ORM as Propel, to create my project. Last time i have upgraded my server's PHP version from 5.2 to 5.3, from that time i am getting the error as

PHP Deprecated:  Directive 'magic_quotes_gpc' is deprecated in PHP 5.3 and greater in Unknown on line 0
PHP Fatal error:  Class 'PDO' not found in /usr/local/lib/php/symfony/plugins/sfPropelPlugin/lib/vendor/propel/util/PropelPDO.php on line 42
PHP Warning:  Module 'PDO' already loaded in Unknown on line 0
PHP Warning:  Module 'pdo_sqlite' already loaded in Unknown on line 0
PHP Warning:  Module 'SQLite' already loaded in Unknown on line 0

Is there any thing i can do in code, or turn off 'magic_quotes_gpc' in php.ini?
please help!

A: First error can be just silenced by disabling E_DEPRECATED in error_reporting().
(Note: in general, silencing error messages is not a good way of dealing with errors - proper way of dealing with this error is to upgrade your scipts to version that supports PHP 5.3)
However you have four more much more serious errors, which I'm not really sure about.


text:
Q: LOAD DATA INFILE in phpMyAdmin 4.2.10.1 don't work #7890 i'm really disappointed that only one person have some idea how to solve my problem!!!
I already have try to find thoroughly (2 hours!) the answer in all the other discussion, but nothing compare to my challenge!
I work with a hosted phpmyadmin installation with Win 10 and I try to load a file in a table.
When I start the import function of phpmyadmin, the sql-script will be found and started, but I get allways the
error #7890 – can't find file 'D:\Loader\doshas.txt'.
'load.sql':
LOAD DATA LOCAL INFILE "D:\Loader\doshas.txt" INTO TABLE doshas terminated by ',';
The file 'load.sql' is  in the same folder as doshas.txt!
What's wrong?
Regards and thanks

A: Probably you haven't specified special characters.
I believe better way is to use LOAD DATA INFILE.
Let's say you want to load the file doshas.txt to my_table with columns col_a, col_b, col_c.
Put the txt file in the path of mysql of phpadmin ex.For XAMPP is xamp\mysql\data
Then in phpmyadmin -> code SQL write
LOAD DATA INFILE 'doshas.txt' INTO TABLE `my_table`
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(col_a, col_b, col_c);


text:
Q: Prediction failed: unknown error I'm using Google Cloud Machine Learning to predict images with labels.
I've trained my model, named flower and I see the API end point at Google API Exporer but, when I call the API at API Explorer, I get the following error:
Image Error
I can't understanding why.
Thanks
Ibere

A: I guess you followed the tutorial from https://github.com/GoogleCloudPlatform/cloudml-samples/tree/master/flowers?
I had the exact same problem but with some trial and errors I succeeded with the payload:
{"instances":[{"image_bytes": {"b64": "/9j/4AAQ...rest of the base64..."}, "key": "0"}]}


text:
Q: Cannot read property 'headers' of undefined even tho property has been defined So I came across this code and  wanted to combine it with a table that I created. I coped and pasted it to break apart and understand it. But I keep running into this issue, "Cannot read property 'headers' of undefined". I'm still new to react, but I have done this type of thing many of time and I just stomped to why this happening
code:
const TableDnD = (superclass) => class extends superclass {

constructor() {
    super();
    this.state = this.state || {};
    this.state.columnX = 0;
    this.state.columnY = 0;
    this.state.dragging = false;
}

dragHandle(children) {
    return (

        {children}

    )
}

dragContainer(children) {
    const dragColumn = this.state.dragging ? this._renderDragColumn() : null;
    const styles = {
    position: "relative"
    };
    return (

 this.container = container}
      >
        {children}
        {dragColumn}

    )
}

   // Bunch of code for drag and drop table
}

class Table extends TableDnD(Component) {

constructor(props) {
    super(props);

    this.state = {
        headers: this.props.headers, // right here the error haapens
        data: this.props.data,
    }
}

// other code
// render the component
render() {
   const headers = this.renderHeaders();
   const data = this.renderRows();
   // And finally, the table must be wrapped in the dragContainer method. That's it!
   return this.dragContainer(

                   {headers}

          {data}

    );
  }
}

export default Table

Right at 'headers: this.props.headers' and same with data. The error: Cannot read property 'headers' of undefined.
Even I declared the header property.
Am I missing something?

A: Should be props.headers, not this.props.headers.
Same thing will happen on the next line with data


text:
Q: jboss 5 changing default port I am trying to change the default port on my jboss server to port 80.
i have had a look around the web and i have had suggestions of editing this file jboss5\server\default\deploy\jbossweb.sar\server.xml  which is fine. changing this file alone still does not fix the issue.
There have also been suggestion to also change this file:
jboss5\server\default\conf\bootstrap\bindings.xml  Only problem is that i cant find this binding.xml
Is the binding.xml file a standard in JBoss 5?  Or has it been renamed or changes location in JBoss 5.
Does anyone have any clear steps on changing the the default port from 8080 to 80.

A: You are probably after jboss-5.1.0.GA/server/standard/deploy/jbossweb.sar/server.xml
See
<Connector protocol="HTTP/1.1" port="8080" address="${jboss.bind.address}"

               connectionTimeout="20000" redirectPort="8443" />

Don't forget that ports below 1024 are generally reserved, and can only be claimed by privileged users (root). Depending on your situation, it may be useful to put an apache reverse proxy in between.

A: Change the bindings-jboss-beans in jboss/server//conf/bindingservice.beans/META-INF

               jboss.web:service=WebServer
               8080
Change the port 8080 to 80 or any other that you wish.

A: In my case, I am running custom server (openmobster) under jboss 5.1 GA on Ubuntu 10.04 and i solved it as following

*

*edit PATH_JBOSS_HOME/server/openmobster/deploy/jbossweb.sar/server.xml and change port in following line to your desired port (e.g. change 8080 to 8090)

<Connector protocol="HTTP/1.1" port="8080" address="${jboss.bind.address}"
               connectionTimeout="20000" redirectPort="8443" />

*

*edit PATH_JOBSS_HOME/server/openmobster/conf/bindingservice.beans/META-INF/bindings-jboss-beans.xml and change value 8080 to your desired port (8090)

<property name="serviceName">jboss.web:service=WebServer</property>
               <property name="port">8080</property>
and restart the server. It started successfully on http://HOST:8090/


text:
Q: how to open camera with qr code scanner? I have an applicaton and on its main activity there is a button, clicking on which opens a fragment at the center of the screen.
I have working code which opens camera at center as explained but  I want that simple camera view to change into qr scanner.I now have added zxing library dependency. and how to make it work when opening camera? can't arrange code. (in oncreate view) .
Any help would be great please.
//method in scan.java
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_scan, container, false);

        if(checkCameraHardware(getActivity().getApplicationContext())){
zXingScannerView  = new ZXingScannerView(getActivity().getApplicationContext());

            //zXingScannerView.startCamera(); I tried something like this

            mCamera = Camera.open();
            mCamera.setDisplayOrientation(90);
            Camera.Parameters params = mCamera.getParameters();
           params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
            mCamera.setParameters(params);
            mPreview = new CameraPreview(this.getActivity(), mCamera);

            //container.addView(mPreview);--->Remove this line
            //Add this line

            FrameLayout preview =(FrameLayout)view.findViewById(R.id.camera_preview);
            preview.addView(mPreview);
        }
        // Inflate the layout for this fragment
        return view;
    }

//fragment_scan.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    tools:context="layout.scan"
    android:layout_centerInParent="true"
android:layout_marginTop="@dimen/nav_header_height"
android:layout_marginBottom="@dimen/fab_margin"
    android:layout_marginLeft="@dimen/fab_margin"

    >
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/camera_preview"
    >

    </FrameLayout>
</LinearLayout>

A: I have Button to scan qr code and access the contact number.
    contacts.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            enable = "contacts";
            pickBankData(enable);
        }
    });
 private void pickBankData(String val) {

 if (enable.equals("scanqr")) {
        IntentIntegrator integrator = new IntentIntegrator(this);
        integrator.setPrompt("Scan a Qrcode");
        integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
        integrator.setCameraId(0);  // Use a specific camera of the device
        integrator.setBeepEnabled(false);
        integrator.setBarcodeImageEnabled(true);
        integrator.initiateScan();          //  accno.setEnabled(false);
        // ifsc.setEnabled(false);

    } }

and in the onactivity result the value is parsed.
 switch (requestCode) {
        case IntentIntegrator.REQUEST_CODE:
            IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode,
                    resultCode, data);
            if (scanResult == null) {
                return;
            }
            final String result = scanResult.getContents();
            if (result != null) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //  tx.setText(result);
                        try {
                            String qrInputText = result;
                            String[] array = qrInputText.split(":", -1);
                            String usertype = array[0];
                            String mobilenumber = array[1];

                            String MMid = array[2];
                            String Name = array[3];
                            if (mobilenumber.equals("")) {

                            }
                            if (enable.equals("scanqr")) {
                                nameedit.setText(Name);
                                mobnum.setText(mobilenumber);

                            }

A: @Nimra better you can use custom Lib, for qr code scaning lot of new lib found in github, Use QReader Lib simple and best.
QReaderLib Github Link
Implementation,
In Gradle,
compile 'com.github.nisrulz:qreader:{latest version}'//start from 1.0.4 version

Add a SurfaceView to your layout
  <SurfaceView
  android:id="@+id/camera_view"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:layout_above="@+id/info"
  />

Setup SurfaceView and QREader in onCreate()
 // QREader
private SurfaceView mySurfaceView;
private QREader qrEader;
..

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

  // Setup SurfaceView
  // -----------------
  mySurfaceView = (SurfaceView) findViewById(R.id.camera_view);

  // Init QREader
  // ------------
  qrEader = new QREader.Builder(this, mySurfaceView, new QRDataListener() {
    @Override
    public void onDetected(final String data) {
      Log.d("QREader", "Value : " + data);
      text.post(new Runnable() {
        @Override
        public void run() {
          text.setText(data);
        }
      });
    }
  }).facing(QREader.BACK_CAM)
      .enableAutofocus(true)
      .height(mySurfaceView.getHeight())
      .width(mySurfaceView.getWidth())
      .build();

}

A: This simple alteration in my code worked well to open qr scanner in my code.  Below is the code. If needed by any body.
zXingScannerView  = new ZXingScannerView(getActivity().getApplicationContext());
zXingScannerView.startCamera();

FrameLayout preview =(FrameLayout)view.findViewById(R.id.camera_preview);
preview.addView(zXingScannerView);


text:
Q: When Talking to a sensor IoT device from Bluemix Node-RED, what is the reasoning for registering a device? I want to set up Node-RED in bluemix to talk (2 ways) to my Arduino Uno with a temperature sensor.  What is the reasoning for registering the Arduino device?

A: When a device is registered with IotF, it then has its own topic space and credentials.  Using those credentials it can connect to IoTF and publish events and receive commands.  Only that particular device and applications with API keys can publish the events or receive commands sent to it.


text:
Q: ViewPager2 Exception: java.lang.IllegalStateException: Design assumption violated I can't reproduce this issue myself but I notice this issue in production with Xiaomi MI 9 running Android 10. Here are the ViewPager2 and RecyclerView versions I use:
androidx.recyclerview:recyclerview:1.1.0
androidx.viewpager2:viewpager2:1.0.0

And here's the stacktrace:
Fatal Exception: java.lang.IllegalStateException: Design assumption violated.
       at androidx.viewpager2.adapter.FragmentStateAdapter.placeFragmentInViewHolder(FragmentStateAdapter.java:287)
       at androidx.viewpager2.adapter.FragmentStateAdapter.onViewAttachedToWindow(FragmentStateAdapter.java:276)
       at androidx.viewpager2.adapter.FragmentStateAdapter.onViewAttachedToWindow(FragmentStateAdapter.java:67)
       at androidx.recyclerview.widget.RecyclerView.dispatchChildAttached(RecyclerView.java:7556)
       at androidx.recyclerview.widget.RecyclerView$5.addView(RecyclerView.java:860)
       at androidx.recyclerview.widget.ChildHelper.addView(ChildHelper.java:107)
       at androidx.recyclerview.widget.RecyclerView$LayoutManager.addViewInt(RecyclerView.java:8601)
       at androidx.recyclerview.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:8559)
       at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1643)
       at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
       at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:675)
       at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
       at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
       at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4404)
       at android.view.View.layout(View.java:21963)
       at android.view.ViewGroup.layout(ViewGroup.java:6317)
       at androidx.viewpager2.widget.ViewPager2.onLayout(ViewPager2.java:527)
       at android.view.View.layout(View.java:21963)
       at android.view.ViewGroup.layout(ViewGroup.java:6317)
       at androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1915)
       at android.view.View.layout(View.java:21963)
       at android.view.ViewGroup.layout(ViewGroup.java:6317)
       at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
       at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
       at android.view.View.layout(View.java:21963)
       at android.view.ViewGroup.layout(ViewGroup.java:6317)
       at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
       at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
       at android.view.View.layout(View.java:21963)
       at android.view.ViewGroup.layout(ViewGroup.java:6317)
       at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
       at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
       at android.view.View.layout(View.java:21963)
       at android.view.ViewGroup.layout(ViewGroup.java:6317)
       at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1829)
       at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1673)
       at android.widget.LinearLayout.onLayout(LinearLayout.java:1582)
       at android.view.View.layout(View.java:21963)
       at android.view.ViewGroup.layout(ViewGroup.java:6317)
       at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
       at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
       at com.android.internal.policy.DecorView.onLayout(DecorView.java:803)
       at android.view.View.layout(View.java:21963)
       at android.view.ViewGroup.layout(ViewGroup.java:6317)
       at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:3144)
       at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2654)
       at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1782)
       at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7785)
       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1031)
       at android.view.Choreographer.doCallbacks(Choreographer.java:854)
       at android.view.Choreographer.doFrame(Choreographer.java:789)
       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1016)
       at android.os.Handler.handleCallback(Handler.java:883)
       at android.os.Handler.dispatchMessage(Handler.java:100)
       at android.os.Looper.loop(Looper.java:224)
       at android.app.ActivityThread.main(ActivityThread.java:7520)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

I'm not sure where this is triggered from my code since the stacktrace is not very clear. Also, as per Google Issuetracker, this has been solved in viewpager2:1.0.0-beta03: https://issuetracker.google.com/issues/134246546 with the commit here but not quite in my case. And here's another post with the same issue with not many helpful answers: FragmentStateAdapter throws java.lang.IllegalStateException: Design assumption violated after configuration change. It'd be great if anyone knows why this occurs or how it can be solved.

A: If you override getItemId() make sure you also override containsItem().

A: I tried everything for the solution but it did not work. I removed the getItemId  in the fragmentStateAdapter and it is working fine now.


text:
Q: sns unable to trigger lambda when created using cloudformation I have gone through many blogs but none of them solves my issue. SNS created by cloudformation is unable to trigger the lambda created by the same cloudformation, I see the trigger as sns in lambda but it didn't trigger it, below is the code.
Tried all solution suggested like using only SourceArn in lambda permission instead of SourceAccountId and all
LambdaBasicExecutionRole:
    Type: "AWS::IAM::Role"
    Properties:
      RoleName: "LambdaBasicExecutionRole"
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          -
            Effect: "Allow"
            Principal:
              Service:
                - "lambda.amazonaws.com"
            Action:
              - "sts:AssumeRole"
      Path: "/"
      Policies:
        -
          PolicyName: "LambdaPolicyEC2KeyPair"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              -
                Effect: "Allow"
                Action:
                  - "kms:ListGrants"
                  - "kms:CreateGrant"
                  - "kms:Encrypt"
                  - "kms:Decrypt"
                Resource: "arn:aws:kms:*:*:*"
              -
                Effect: "Allow"
                Action:
                  - "logs:CreateLogGroup"
                  - "logs:CreateLogStream"
                  - "logs:PutLogEvents"
                Resource: "arn:aws:logs:*:*:*"
              -
                Effect: "Allow"
                Action: "ec2:CreateKeyPair"
                Resource: "*"
              -
                Effect: "Allow"
                Action: "ssm:PutParameter"
                Resource: "*"

  LambdaFunctionEC2KeyPair:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: LambdaFunctionEC2KeyPair
      Description: "Lambda Function to create EC2 KeyPair and storing it's private key securely to paramater store"
      Handler: index.handler
      Runtime: python3.6
      Role: !GetAtt LambdaBasicExecutionRole.Arn
      Code:
        ZipFile: |
          import boto3, os, botocore, cfnresponse

          client = boto3.client('ec2')
          ssm = boto3.client("ssm")

          def handler(event, context):
            ###############################
            # Variable Defination from CF #
            ###############################

            IIS = ['service', 'engine', 'micro']

            namespace = "IIS"
            keyid = os.environ['kmsid']
            env = os.environ['env']

            for iis_tier in IIS:
              keyname = 'IIS-EC2-KeyPair-'+iis_tier+'-'+env
              try:
                response = client.create_key_pair(
                  KeyName=keyname
                )

              except botocore.exceptions.ClientError as e:
                if e.response['Error']['Code'] == 'InvalidKeyPair':
                  print ("Invalid Key Pair Duplicate Error")
                  continue
                else:
                  continue

              try:
                ssm_response = ssm.put_parameter(
                  Name=f"/{namespace}/{env}/EC2-KeyPair/{iis_tier}",
                  Value=response['KeyMaterial'],
                  Type="SecureString",
                  KeyId=keyid,
                  Description='Private key for '+iis_tier+' '+env+' EC2 instance for ssh connection, one would need it for making ssh connection with the instance for administrative purposes'
                )
              except botocore.exceptions.ClientError as e:
                if e.response['Error']['Code'] == 'AccessDeniedException':
                  print ("Access Denied Error")
                  continue
                else:
                  continue
            cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData, physicalResourceId )
            return

      Environment:
        Variables:
          env: !Ref Environment
          kmsid: !Ref kmsKeyIIS
    DependsOn: LambdaBasicExecutionRole

  EC2KeyPair:
    Type: Custom::EC2KeyPairResource
    Properties:
      ServiceToken: !GetAtt LambdaFunctionEC2KeyPair.Arn

A: It appears that you are wanting to trigger an AWS Lambda function when the CloudFormation stack deploys.
You can do this with an AWS Lambda-backed Custom Resource.
The template should include:

*

*The Lambda function

*A Custom:: entry to trigger your Lambda function

The Lambda function will need to signal back when it is complete. There is a cfn-response Module provided to assist with this. It is available for Node.js and Python.
Here is a basic CloudFormation template that deploys and runs a Custom Resource:
AWSTemplateFormatVersion: 2010-09-09

Resources:

  LambdaBasicExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: MyLambdaRole
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          -
            Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

  LambdaFunctionTest:
    Type: AWS::Lambda::Function
    DependsOn: LambdaBasicExecutionRole
    Properties:
      FunctionName: LambdaFunctionTest
      Description: Lambda Function to test that Custom Resource works
      Handler: index.handler
      Runtime: python3.6
      Role: !GetAtt LambdaBasicExecutionRole.Arn
      Code:
        ZipFile: |
          import boto3
          import cfnresponse

          def handler(event, context):
            print('This is in the handler')

            responseData = {}
            cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
            return

  CustomFunctionTest:
    Type: Custom::CustomFunctionTest
    Properties:
      ServiceToken: !GetAtt LambdaFunctionTest.Arn

A: I have AWS::Serverless::Function and there's Events attribute in the its properties. If you had that, then your configuration would be something like this:
LambdaFunctionEC2KeyPair:
  Type: AWS::Lambda::Function
  Properties:
    FunctionName: LambdaFunctionEC2KeyPair
    Description: "Lambda Function to create EC2 KeyPair and storing it's private key securely to paramater store"
    Handler: index.handler
    Runtime: python3.6
    Role: !GetAtt LambdaBasicExecutionRole.Arn
    Code:
      ZipFile: |
        My code

    Environment:
      Variables:
        env: !Ref Environment
        kmsid: !Ref kmsKeyIIS
    Events:
      SNSTopicMessage:
        Type: SNS
        Properties:
          Topic:
            Fn::Join:
              - ':'
              - - arn
                - Ref: AWS::Partition
                - sns
                - Ref: AWS::Region
                - Ref: AWS::AccountId
                - SNSTopicLambdaInvoke
  DependsOn: LambdaBasicExecutionRole

I am checking about your use case having AWS::Lambda::Function.
You can check this example.
About the difference between a Serverless Function, and a Lambda Function
you can check in this answer:  What is the difference between a Serverless Function, and a Lambda Function


text:
Q: How to Remove Duplicate entries from an array in Android
Possible Duplicate:
Java Remove Duplicates from an Array?

String={3333,4444,5555,5555,1111}

Using Delimiter i have put the String values in an array[]..
Now, How can i remove the same entries in an Array???

A: Use Set instead, Or use temporarily Set and get the unique result back to array
See

*

*What interface in Java can I use to store unique objects?


text:
Q: WAMP - mod_rewrite fails with incomplete local path I'm trying to set up my PHP project on Windows & WAMP, but I ran into a very strange roadbump.
In my .htaccess I have the following catch-all redirection:
RewriteRule ^(.*)$ index.php?$1 [PT,L]

On Linux & Apache this works fine, for example: /some_alias/items redirects succesfully to my index.php file which handles the page request from that on.
However, with Windows, I get the following when accessing http://xx.xx.xx.xx/some_alias/index
Not Found

The requested URL /Users/username/workspace/project/some_alias/index.php was not found on this server.

My alias file is as follows:
Alias /some_alias/ "c:/users/username/workspace/project/some_alias/"
<Directory "c:/users/username/workspace/project/some_alias/">

AllowOverride all
Order allow,deny
Allow from all
</Directory>

What's going on?


text:
Q: How do I prevent component shaking with GridBagLayout? I have a GUI with four components laid out next to each other with GridBagLayout. When I resize the window to the right, the leftmost component shakes, when I resize to the left, the rightmost.
Here is an example:
import javax.swing.*;
import java.awt.*;

public class GBLShakeTest extends JPanel {
    public static void main(String[] args) {
        JFrame frame = new JFrame("GBLShakeTest");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setPreferredSize(new Dimension(500, 500));
        frame.add(new GBLShakeTest());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public GBLShakeTest() {
        super(new GridBagLayout());
        add(new JTextArea("component 1"), new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
        add(new JTextArea("component 2"), new GridBagConstraints(1, 0, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
        add(new JTextArea("component 3"), new GridBagConstraints(2, 0, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
        add(new JTextArea("component 4"), new GridBagConstraints(3, 0, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
    }
}

It even happens with the GridBagLayout demo from oracle which uses only JButtons. Resizing to the right is fine, but when you enlarge the window leftwards, the right Button shakes.
Does anyone know how to fix this?

A: This is definitely a bug in GridBagLayout.  I can't find a workaround for it, at least not using GridBagLayout.
What seems to happen is that GridBagLayout changes the first component's X coordinate from 0 to 1, for some container sizes.  If only the first component has a nonzero weightx, the problem doesn't occur (which makes me suspect that it's an issue with the inaccuracy of floating-point weightx values, but I haven't tried digging into the GridBagLayout source to confirm that).
One alternative is to use SpringLayout.  SpringLayout is difficult to use, but it can do many of the things GridBagLayout can, with some work.  (People who have written code that uses Motif's XmForm widget will recognize the use of attachments to other components, though SpringLayout does not work in exactly the same manner.)
SpringLayout layout = new SpringLayout();
setLayout(layout);

add(new JTextArea("component 1"));
add(new JTextArea("component 2"));
add(new JTextArea("component 3"));
add(new JTextArea("component 4"));

Component previous = null;
for (Component c : getComponents()) {
    // Attach component to top and bottom of container.
    layout.putConstraint(
        SpringLayout.NORTH, c, 0, SpringLayout.NORTH, this);
    layout.putConstraint(
        SpringLayout.SOUTH, c, 0, SpringLayout.SOUTH, this);

    if (previous != null) {
        // Attach component's left (west) edge to previous component's
        // right(east) edge.
        layout.putConstraint(
            SpringLayout.WEST, c, 0, SpringLayout.EAST, previous);
    }

    previous = c;
}

// Bind this container's right (east) edge to the right (east) edge
// of the rightmost child component.
Component lastComponent = getComponent(getComponentCount() - 1);
layout.putConstraint(
    SpringLayout.EAST, this, 0, SpringLayout.EAST, lastComponent);


text:
Q: How to disable DatePicker interaction(for selecting date) for one textfield in swift" I am using datePicker for fromDateTf and toDateTf  textfields.. now i need to make toDateTf's date picker interaction disable(means date shouldn't select) if fromDateTf textfield text is empty.. how?
for datepicker
let screenWidth = UIScreen.main.bounds.width

let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 216))

class PostServiceRequestVC: UIViewController, UITextViewDelegate {

@IBOutlet weak var toDateTf: UITextField!
@IBOutlet weak var fromDateTf: UITextField!

 override func viewDidLoad() {
    super.viewDidLoad()

    fromDateTf.addInputViewDatePicker(target: self, selector: #selector(doneButtonPressed), tag: 0)
    toDateTf.addInputViewDatePicker(target: self, selector: #selector(doneButtonPressed), tag: 1)

}

@objc func doneButtonPressed(_ sender: UIBarButtonItem) {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let arr = [fromDateTf,toDateTf]

    let current = arr[sender.tag]
    if let datePicker = current?.inputView as? UIDatePicker {
        current?.text = dateFormatter.string(from: datePicker.date)

        current?.resignFirstResponder()
    }

}

extension UITextField {

func addInputViewDatePicker(target: Any, selector: Selector, tag: Int) {

    datePicker.datePickerMode = .date
    self.inputView = datePicker

    if #available(iOS 13.4, *) {
        datePicker.preferredDatePickerStyle = .wheels
        datePicker.sizeToFit()
    }
    let todaysDate = Date()

    datePicker.minimumDate = todaysDate

    let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 44))
    let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    let cancelBarButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelPressed))
    let doneBarButton = UIBarButtonItem(title: "Done", style: .plain, target: target, action: selector)
    toolBar.setItems([cancelBarButton, flexibleSpace, doneBarButton], animated: false)

    doneBarButton.tag = tag

    self.inputAccessoryView = toolBar
}

@objc func cancelPressed() {
    self.resignFirstResponder()
}
}

with the above code i am able to select dates for two textfields.. but
here fromDateTf.text is empty so want to disable interaction for toDateTf's datepicker

i want user should select fromdate first.. without fromdate i do not want to give access  to select todate how?... please help me
EDIT: according to below answer if i add that code in viewDidLoad then all the time toDateTf stopping me to show datepicker and select date
so i have added that code in  doneButtonPressed so here for the first time i am bale to show datepicker and select date.. but from the 2nd time if the fromDateTf is empty then working.. but its not working for the 1st time.. for first time also if fromDateTf is empty then toDateTf.isEnabled = false should work.. how to achieve please do help.
   @objc func doneButtonPressed(_ sender: UIBarButtonItem) {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let arr = [fromDateTf,toDateTf]

    let current = arr[sender.tag]
    if let datePicker = current?.inputView as? UIDatePicker {

        if fromDateTf.text?.isEmpty ?? true {

               toDateTf.isEnabled = false

            } else {
               toDateTf.isEnabled = true
        }
        current?.text = dateFormatter.string(from: datePicker.date)

        current?.resignFirstResponder()
    }

}

A: You could make a function that checks whether or not the fromDateTf is empty, and adjust the UI accordingly:
func checkForText() {

     if fromDateTF.text == "" { //you can also use .isEmpty if you'd rather

        toDateTf.isEnabled = false

     } else {

        toDateTf.isEnabled = true

     }

Then, you can call this function in your ViewDidLoad and any subsequent time you change anything with your textboxes. It'll be a good idea to add in the else part of it so that when you fill in your fromDateTf, it reEnables the other one.


text:
Q: Conditions on $f$ for $f(X_1),\dots,f(X_n)$ to be iid Let $X_1,\dots,X_n$ be iid non negative random variables.
What is are necessary and sufficient conditions of a function $f$ for the random variables $f(X_1),\dots,f(X_n)$ to be iid?
For example is it true if $f$ is non negative and continuous?

A: It is sufficient that $f$ is measurable. That is the inverse of an open subset of $\mathbb{R}$ is a measurable subset of $\mathbb{R}$.
In particular, if $f$ is continuous it is measurable so it will definitely work for continuous functions $f$.


text:
Q: pick specific columns from multiple csv files in python pandas I am trying to create a modified CSV file from multiple small csv files. There is one column common in field1.csv and field2.csv. The final csv file final.csv will contain column["NAME"], column["ACC"] from field1.csv and column1["SCORE"], column["TEAM"] from field2.csv where column["ID"] from field1.csv is euqal to column["ID"] from field2.csv. If there is no value then it should be blank. I am using Python pandas.
field1.csv :-
"ID","NAME","ACC","POINT"
"123","TRR","OOP","64"
"124","DEE","OOP","78"
"125","EWR","PLO","98"

field2.csv :-
"ID","SCORE","TEAM","END"
"111","92","BCC","0"
"121","80","CSS","1"
"123","87","BCC","0"

final.csv :-
"NAME","ACC","SCORE","TEAM"
"TRR","OOP","87","BCC"
"DEE","OOP","",""
"EWR","PLO","",""

Python code that I am trying,
import pandas as pd

df1 = pd.read_csv("field1.csv", index_col=[1], index_col=[2])

df2 = pd.read_csv("field2.csv", index_col=[1], index_col=[2])

finaldf = pd.concat([df1, df2])

print(finaldf)

finaldf.to_csv('final.csv')

A: I think need one parameter index_col for convert first column to index with filter columns by usecols with join by default left join:
df1 = pd.read_csv("field1.csv", index_col=[0], usecols=["ID","NAME","ACC"])

df2 = pd.read_csv("field2.csv", index_col=[0], usecols=["ID","SCORE","TEAM"])

finaldf = df1.join(df2)
print (finaldf)
    NAME  ACC  SCORE TEAM
ID
123  TRR  OOP   87.0  BCC
124  DEE  OOP    NaN  NaN
125  EWR  PLO    NaN  NaN

Another possible solution is filter columns before join by subsets:
df1 = pd.read_csv("field1.csv", index_col=[0])

df2 = pd.read_csv("field2.csv", index_col=[0])

finaldf = df1[["NAME","ACC"]].join(df2[["SCORE","TEAM"]])

Last write to file with omit index:
finaldf.to_csv('final.csv', index=False)


text:
Q: Sort on click of Button, If again pressed then order to be changed to default sort order in Oracle Forms ii)    Sort Button : this new button needs to be introduced to change the default sort order , once this button is clicked or pressed then records should be sorted based on ascending order of Policy Number
    Note: If this button is pressed again then sort order should be changed to default sort order (same as it exists in current functionality)
****Sort Button Code below:
====================**

Declare
    chk varchar2(100);
Begin
    if :global.chk_stat  = 1 then
        chk:= 'status';
        SET_BLOCK_PROPERTY('BLOCK1',ORDER_BY,chk);
        go_block('block1');
        Execute_query(all_records);
        :global.chk_stat := 2;
    Else
        SET_BLOCK_PROPERTY('BLOCK1',ORDER_BY,:cntrl.default_sort);
        go_block('block1');
        Execute_query(all_records);
        :global.chk_stat := 1;
    End If;
End;

**Code in New form Instance Trigger
====================================**

:cntrl.default_sort := GET_BLOCK_PROPERTY('BLOCK1',ORDER_BY);

A: Think the current status for ordering dependent on what Get_Block_Property method brings :
Begin
    If  Get_Block_Property('block1',Order_By) = ' Policy Desc' Then
    -- presuming the above one is your default "Order By Clause"
        Set_Block_Property('block1',Order_By,' Policy ');
        :global.chk_stat := 2;
    Else
        Set_Block_Property('block1',Order_By,' Policy Desc');
        :global.chk_stat := 1;
    End If;
        Go_Block('block1');
        Execute_query;
End;

Perhaps you use at some other part. So, :global.chk_stat assignments still remain.


text:
Q: Intersection theory for $G$-varieties - an action on the chow ring? Let $G$ be a reductive algebraic group. Let $X$ be a $G$-variety and consider any closed subvariety $Z$ of $X$. Since any $g\in G$ acts as an automorphism, we know that $g.Z$ is again a closed subvariety of $X$. This yields an action of $G$ on the free module of cycles of $X$ which should induce an action of $G$ on the Chow ring of $X$. The invariants of this ring should be precisely the classes that correspond to linear combinations of $G$-orbits.
Has this action been studied before? Any kind of reference would be very welcome. Thanks!
Edit: It looks like my above idea is rather futile, so let me ask more broadly: Are there any techniques or results in intersection theory specifically on $G$-varieties? Could you name some references?

A: If you are interested in intersection theory of varieties with $G$-actions, then you want to study equivariant intersection theory.  This theory exploits the $G$-action in a way that leads to deeper invariants than ordinary intersection theory.  The three references I would recommend if you are first learning the subject are:
Fulton's lectures notes on equivariant cohomology (compiled by Dave Anderson)
Equivariant Cohomology and Equivariant Intersection Theory by Michel Brion
Equivariant Chow Groups for Torus Actions by Michel Brion

A: I assume that you are over an algebraically closed field. If $G$ is connect, the action is trivial, because any affine algebraic group is rational, so every point can be connected via a chain of open subsets of $\mathbb A^1$ to the identity.


text:
Q: How to return from a python list containing strings and integers def days_in_month(m):
    for m in range (January,December):
        return (month_days[0],month_days[11])

    month_days= [('January'[31]), ('February'[28,29]), ('March'[31]), ('April'[30]), ('May'[31]), ('June'[30]), ('July'[31]), ('August'[31]), ('September'[30]), ('October'[31]), ('November'[30]), ('December'[31])]
    day_names=['Monday' 'Tuesday' 'Wednesday' 'Thursday' 'Friday' 'Saturday' 'Sunday']

I am supposed to use a python list to store the names of every month and the   number of days in each, my program should accept one argument (a month) and return   the set number of days in that specific month. I am having problems returning the
 number of days in each specified month, I have tried searching for answers
  everywhere but nothing. Please help. Thanks in advance.

A: I would recommend using a dictionary for month_days
def days_in_month(m):
    return month_days[m]

month_days= {'January':31, 'February':[28,29] etc...}
day_names=['Monday' 'Tuesday' 'Wednesday' 'Thursday' 'Friday' 'Saturday' 'Sunday']

I don't exactly understand what you want to return here. But this code will return the number stored in the dictionary.
So month('January') will return 31


text:
Q: Saving bought date and adding X time to it I am creating a node app where a user can select a bought date using the HTML input of: <input placeholder="Date Bought" class="textbox-n form-control" type="text" onfocus="(this.type='date')" onblur="(this.type='text')" id="bought" name="bought">
This is then stored to a mongodb using var bought = req.body.bought; and the user inputs a number of months into another HTML input that has name="warranty" I need to convert to a date using the bought date and then warranty months. How can I add these? I have tried this:
  var bought = req.body.bought;
  var warrantyMonths = req.body.warranty;
  var warranty = bought.setMonth(bought.getMonth()+ warrantyMonths);

As per this guide

A: Try using Moment.js
If warranty months is an integer you can:
var bought = moment(req.body.bought);
var warrantyMonths = req.body.warranty;
var warranty = moment(bought).add(warrantyMonths, "month");

Moment is just a wrapper for the JS date object so it's seamless and easy to use. You can install it as an npm package, import it to your page, and pass it different formatted date strings (see the docs) or any valid javascript date object. I can't work with dates without moments anymore, imo it should be part of the standard library.

A: Go through the code and comments to understand why your code was not working properly

function calculateWarranty() {
  // get the date text and convert into date Object
  var bought = new Date(document.getElementById('bought').value);
  // get the number of warranty months and convert to integer (second arguments ensures that the integer is base 10)
  // if you do not convert the number, it will do String concatenation while calling dateObj.setMonth(getMonth_int + warrant_string )
  // for example: 2017-10-21 will give bought.getMonth() === 9 + "1", which will equal 91 instead of 10
  var warrantyMonths = parseInt(document.getElementById('warranty').value, 10);

  // display in console for debugging
  console.log(bought);
  console.log(warrantyMonths);

  var boughtMonth = bought.getMonth();

  // add bought month and warranty month (both should be integer as stated earlier)
  var warrantyMonth = boughtMonth + warrantyMonths;

  // set the month to bought object
  bought.setMonth(warrantyMonth);

  // result
  console.log(bought);
}

// adding event listeners on the input boxes
document.querySelector('#bought').addEventListener('change', calculateWarranty);
document.querySelector('#warranty').addEventListener('change', calculateWarranty);
<input id="bought" name="bought" class="textbox-n form-control" type="text" placeholder="Date Bought" onfocus="(this.type='date')" onblur="(this.type='text')" />

<input id="warranty" name="warranty" class="textbox-n form-control" type="number" value="1" />

You also need to add some error handling to the code.


text:
Q: Computing cohomology of certain sheaf on a $K3$ surface Let $E$ be a vector bundle over a $K3$ surface $X$ which is globally generated away from finitely many points,then I want to show that $H^1((H^0(E)^* \otimes  \mathcal O_X) /E^*) =0 $.Let's denote the sheaf inside cohomology notation by $\mathcal F$
My guess : By Serre duality we have,  $ (H^1(\mathcal F))^* = Ext^1(\mathcal F, \mathcal O_X)$ .
I hope that the last expression is trivial because of the the following proposition in Hathshorne's book (page $237$, proposition $6.10(b)$), which says the following : for a ring $A$ and for a $A$ module $M$, we have $M$ is projective iff  $Ext^1(M,N) =0$ for all $A$ module $N$.
Doubts : I am nowhere using the facts $(1)$ $X$ is a$K3$ surface ,i.e $H^1(X, O_X)=0$ and $(2)$ $E$ is globally generated away from finitely many points.
Please correct me if the argument that I have given is wrong.
Any help from anyone is welcome.

A: I am not sure I understand your argument, but here is an argument.
You have the exact sequence $0\to E^*\to H^0(E)^*\otimes O_X\to F\to 0$. Taking cohomologies, you get $H^1(H^0(E)^*\otimes O_X)\to H^1(F)\to H^2(E^*)\to H^2(H^0(E)^*\otimes O_X)$. The first term is zero since $H^1(O_X)=0$. The last map is an inclusion, since by dulity, it is dual to $H^0(H^0(E)\otimes O_X)\to H^0(E)$, which is an isomorphism. Thus, $H^1(F)=0$.


text:
Q: Delimiter coming in data I have the below code in a batch file.
Here MYDB is the database, Activity_Inc.sql is the script file and ST_Activity- is the csv file generated with the data. | is used as the delimiter. Now, the problem is with few records where the data is also having the | in it. Due to this the generated file is failing to be integrated with the target system.
I need to enclose the field with the double quotes where ever the data is having | in it.
Please suggest a way for this.
sqlcmd -S . -d MYDB -E -s"|" -W -i D:\Activity_Inc.sql | findstr /V /C:"-" /B > D:\ST_Activity-%date:~6,4%%date:~3,2%%date:~0,2%%time:~0,2%%time:~3,2%.csv


text:
Q: function inside window.onload I have an external js file that contains window.onload at top. I want to call control.next() function inside window.onload when I click the button that is in a separate HTML file.
window.onload = function() {

 control = {

    margin: function(n) {
        sliderContent.style.marginLeft = '-' + n + '00%';
    },

    prev: function() {
        (n === 0) ? n = (slideCount - 1) : n--;
        control.margin(n);
    },

    next: function() {
        alert("next");
        (n < slideCount - 1) ? n++ : n = 0;
        control.margin(n);
    },

    slide: function() {
        move = setInterval(function(){
            (n < slideCount - 1) ? n++ : n = 0;
            control.margin(n);
        }, 4000)
    }
 }

}

Button code is:
<button class="xy" onclick="">next</button>

you can also check fiddle at  http://jsfiddle.net/gLPhr/2/

A: What you are trying to do is not possible since the controls scope is inside the anonymouys function. I dont see a that you need the onload event, remove it and your code should work fine.

A: You just need to expose the control object, yes?
var control;

window.onload = function() {

 control = {
...

Otherwise, control is scoped to window.onload, and nothing outside can see it.
Btw, not sure that fiddle is where you want it.

A: Keep the control variable external, and just call the method you need in the onload handler.

var control = {
margin: function(n) {
    sliderContent.style.marginLeft = '-' + n + '00%';
},

prev: function() {
    (n === 0) ? n = (slideCount - 1) : n--;
    control.margin(n);
},

next: function() {
    alert("next");
    (n < slideCount - 1) ? n++ : n = 0;
    control.margin(n);
},

slide: function() {
    move = setInterval(function(){
        (n < slideCount - 1) ? n++ : n = 0;
        control.margin(n);
    }, 4000)
}

}
window.onload = control.next