问:
SQL Combining Two Totally seperate tables to one
I am VERY new to SQL and self taught.  I have two SQL that I stuggled through but got working.  Now I need to combine them into one and I'm lost.

```<code>SELECT
    s.lastfirst,
    s.student_number,
    SUM(tr.howmany)
FROM
    students s
JOIN
    truancies tr ON s.id = tr.studentid
WHERE
    s.enroll_status = 0 AND
    s.schoolid = ~(curschoolid)
GROUP BY
    s.lastfirst, s.student_number
HAVING
    SUM(tr.howmany) > 0
ORDER BY
    s.lastfirst
</code>```

And this table:

```<code>SELECT
    S.DCID as DCID,
    S.LASTFIRST as LASTFIRST,
    S.STUDENT_NUMBER as STUDENT_NUMBER,
    S2.FC_SRVC_HRS_DUE as FC_SRVC_HRS_DUE,
    CASE
       WHEN S2.FC_SRVC_HRS_COMPLETED IS NULL
          THEN '0'
          ELSE S2.FC_SRVC_HRS_COMPLETED
    END AS FC_SRVC_HRS_COMPLETED,
    S2.FC_SRVC_HRS_BUYOUT as FC_SRVC_HRS_BUYOUT,
    CASE
       WHEN S2.FC_SRVC_HRS_COMPLETED IS NULL
          THEN S2.FC_SRVC_HRS_DUE * S2.FC_SRVC_HRS_BUYOUT
          ELSE ((S2.FC_SRVC_HRS_DUE - S2.FC_SRVC_HRS_COMPLETED) * S2.FC_SRVC_HRS_BUYOUT)
    END as Balance_Due
FROM
    STUDENTS S, U_STUDENTSUSERFIELDS S2
WHERE
    S.DCID = S2.STUDENTSDCID AND
    s.enroll_status = 0 AND
    s.schoolid = ~(curschoolid) AND
    (((S2.FC_SRVC_HRS_DUE - S2.FC_SRVC_HRS_COMPLETED) * S2.FC_SRVC_HRS_BUYOUT) > 0 OR
    ((S2.FC_SRVC_HRS_DUE - S2.FC_SRVC_HRS_COMPLETED) * S2.FC_SRVC_HRS_BUYOUT) IS NULL) AND
    S2.FC_SRVC_HRS_DUE >.1
ORDER BY
    s.lastfirst
</code>```

What I am really looking for are the totals of both of these. I want the SUM(tr.howmany) from the first table and the balance due of the second BUT I need the filters that are in there. This would be sorted by student. I hope I am making sense. Any assistance would be appreciated.

答:
You can join together 2 separate SQL select statements:

```<code>Eg:
Select A.id, A.value, B.value
From   (select id, count(*) as value from TableA ...) AS A
join   (select id, sum(field) as value from TableB ...) AS B
on   A.id = B.id
order by A.id
</code>```

As long as you have a common field to join on this would work.  In your case the student_number looks like a good candidate.  You will have to do the ordering outside of your subqueries.

Body:
I am VERY new to SQL and self taught.  I have two SQL that I stuggled through but got working.  Now I need to combine them into one and I'm lost.

SELECT
    s.lastfirst,
    s.student_number,
    SUM(tr.howmany)
FROM
    students s
JOIN
    truancies tr ON s.id = tr.studentid
WHERE
    s.enroll_status = 0 AND
    s.schoolid = ~(curschoolid)
GROUP BY
    s.lastfirst, s.student_number
HAVING
    SUM(tr.howmany) > 0
ORDER BY
    s.lastfirst

And this table:

SELECT
    S.DCID as DCID,
    S.LASTFIRST as LASTFIRST,
    S.STUDENT_NUMBER as STUDENT_NUMBER,
    S2.FC_SRVC_HRS_DUE as FC_SRVC_HRS_DUE,
    CASE
       WHEN S2.FC_SRVC_HRS_COMPLETED IS NULL
          THEN '0'
          ELSE S2.FC_SRVC_HRS_COMPLETED
    END AS FC_SRVC_HRS_COMPLETED,
    S2.FC_SRVC_HRS_BUYOUT as FC_SRVC_HRS_BUYOUT,
    CASE
       WHEN S2.FC_SRVC_HRS_COMPLETED IS NULL
          THEN S2.FC_SRVC_HRS_DUE * S2.FC_SRVC_HRS_BUYOUT
          ELSE ((S2.FC_SRVC_HRS_DUE - S2.FC_SRVC_HRS_COMPLETED) * S2.FC_SRVC_HRS_BUYOUT)
    END as Balance_Due
FROM
    STUDENTS S, U_STUDENTSUSERFIELDS S2
WHERE
    S.DCID = S2.STUDENTSDCID AND
    s.enroll_status = 0 AND
    s.schoolid = ~(curschoolid) AND
    (((S2.FC_SRVC_HRS_DUE - S2.FC_SRVC_HRS_COMPLETED) * S2.FC_SRVC_HRS_BUYOUT) > 0 OR
    ((S2.FC_SRVC_HRS_DUE - S2.FC_SRVC_HRS_COMPLETED) * S2.FC_SRVC_HRS_BUYOUT) IS NULL) AND
    S2.FC_SRVC_HRS_DUE >.1
ORDER BY
    s.lastfirst

What I am really looking for are the totals of both of these. I want the SUM(tr.howmany) from the first table and the balance due of the second BUT I need the filters that are in there. This would be sorted by student. I hope I am making sense. Any assistance would be appreciated.

Body:
You can join together 2 separate SQL select statements:

Eg:
Select A.id, A.value, B.value
From   (select id, count(*) as value from TableA ...) AS A
join   (select id, sum(field) as value from TableB ...) AS B
on   A.id = B.id
order by A.id

As long as you have a common field to join on this would work.  In your case the student_number looks like a good candidate.  You will have to do the ordering outside of your subqueries.


来源: stackexchange

问:
Making an array out of doubles from a text file
I need to read a file of grades and input them into an array. I cant seem to figure it out though. Any suggestions. Thanks for your help :)
The grades.txt file looks like this:

```<code>90.0
71.5
87.9
95.0
98.1
</code>```

Code:

```<code>File file1 = new File("grades.txt");
Scanner gradesFile = new Scanner(file1);
String line = gradesFile.nextLine();

//create array
double[] array = new double[12];

//variable to increment
int u = 0;

//loop to put data into array
while(gradesFile.hasNextDouble())

    array[u] = gradesFile.nextDouble();
    u += 1;

gradesFile.close();
</code>```

答:
You can simply scan the double value in your file and store in the array as below

```<code>Scanner scan;
//Data file
File file = new File(grades.txt");
//Array to store the double read from file
double[] array = new double[10];
int i =0;

try {
    scan = new Scanner(file);

    //Scan while the file has next double value
    while(scan.hasNextDouble())
    {
        //Save the double value read from text file and store to array
        array[i] = scan.nextDouble();
        i++;
    }

}catch (FileNotFoundException e) {
    e.printStackTrace();
}
</code>```

To print what you have stored in your array

```<code>for(int y = 0; y < array.length;y++)
{
   System.out.println(array[y]);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to read a file of grades and input them into an array. I cant seem to figure it out though. Any suggestions. Thanks for your help :)
The grades.txt file looks like this:

90.0
71.5
87.9
95.0
98.1

Code:

File file1 = new File("grades.txt");
Scanner gradesFile = new Scanner(file1);
String line = gradesFile.nextLine();

//create array
double[] array = new double[12];

//variable to increment
int u = 0;

//loop to put data into array
while(gradesFile.hasNextDouble())

    array[u] = gradesFile.nextDouble();
    u += 1;

gradesFile.close();

Body:
You can simply scan the double value in your file and store in the array as below

Scanner scan;
//Data file
File file = new File(grades.txt");
//Array to store the double read from file
double[] array = new double[10];
int i =0;

try {
    scan = new Scanner(file);

    //Scan while the file has next double value
    while(scan.hasNextDouble())
    {
        //Save the double value read from text file and store to array
        array[i] = scan.nextDouble();
        i++;
    }

}catch (FileNotFoundException e) {
    e.printStackTrace();
}

To print what you have stored in your array

for(int y = 0; y < array.length;y++)
{
   System.out.println(array[y]);
}


问:
How to put a border-radius on a specific corner of a button
I have a modal that looks like this

As you can see, the modal has border-radius but the buttons at the footer dont. I want to put a border-radius at the bottom left of the purple button and a border-radius at the bottom right of the gray button. Ive tried border-bottom-left-radius and border-bottom-right-radius but it didnt work. Here`s my codes

Modal:

```<code><!--Notifier Modal-->
<div id="notifier-modal" class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
   <div class="modal-dialog modal-md" role="document">
       <div class="modal-content">
           <div class="modal-body">
               <div class="row">
                   <div class="col-md-12">
                       <div class="confirm-purchase-label">
                           Only {{size}} out of {{totalsize}} transactions have been loaded <br>
                           <h5>The complete list of transactions will be sent to your email after the process.</h5>
                       </div>
                   </div>
               </div>
           </div>

           <div class="modal-footer g-nopadding">
               <div class="col-md-6 g-nopadding">
                   <button type="button" class="btn btn-purple btn-block col-md-6" ng-click="proceedAction();">PROCEED</button>
               </div>
               <div class="col-md-6 g-nopadding">
                   <button type="button" class="btn btn-gray btn-block col-md-6" data-dismiss="modal">CANCEL</button>
               </div>
           </div>
       </div>
   </div>
</code>```

CSS:

```<code>#notifier-modal .btn,
{
    border: none!important;
    border-radius: 0px!important;
    font-family: 'AvenirMedium';
    height: 50px!important;
}

#notifier-modal .modal-md{
    width: 500px;
}

.modal-footer {
   padding: 15px;
   text-align: right;
   border-top: 1px solid #e5e5e5;
}

.modal-content{
   background:#f0f0f0;
   box-shadow:0px 0px 30px 0px rgba(101,101,101,0.50);
   border: none;
}

.btn-gray {
   color: #797979!important;
   background:#e0e0e0!important;
   font-size:14px!important;
   border: none!important;
}

.btn-purple {
   color: #f0f0f0!important;
   background-color: #9c82cd!important;
   font-size:14px!important;
   border: none!important;
}
</code>```

答:
```<code>.modal-footer{
   border-bottom-left-radius: 5px;
   border-bottom-right-radius: 5px;
   overflow: hidden;
}
</code>```

overflow: hidden solves it.

Body:
I have a modal that looks like this

As you can see, the modal has border-radius but the buttons at the footer dont. I want to put a border-radius at the bottom left of the purple button and a border-radius at the bottom right of the gray button. Ive tried border-bottom-left-radius and border-bottom-right-radius but it didnt work. Here`s my codes

Modal:

                           Only {{size}} out of {{totalsize}} transactions have been loaded

The complete list of transactions will be sent to your email after the process.

                   <button type="button" class="btn btn-purple btn-block col-md-6" ng-click="proceedAction();">PROCEED</button>

                   <button type="button" class="btn btn-gray btn-block col-md-6" data-dismiss="modal">CANCEL</button>

CSS:

#notifier-modal .btn,
{
    border: none!important;
    border-radius: 0px!important;
    font-family: 'AvenirMedium';
    height: 50px!important;
}

#notifier-modal .modal-md{
    width: 500px;
}

.modal-footer {
   padding: 15px;
   text-align: right;
   border-top: 1px solid #e5e5e5;
}

.modal-content{
   background:#f0f0f0;
   box-shadow:0px 0px 30px 0px rgba(101,101,101,0.50);
   border: none;
}

.btn-gray {
   color: #797979!important;
   background:#e0e0e0!important;
   font-size:14px!important;
   border: none!important;
}

.btn-purple {
   color: #f0f0f0!important;
   background-color: #9c82cd!important;
   font-size:14px!important;
   border: none!important;
}

Body:
.modal-footer{
   border-bottom-left-radius: 5px;
   border-bottom-right-radius: 5px;
   overflow: hidden;
}

overflow: hidden solves it.


问:
Setting the value of an unsigned char * in c++
I've got a function that takes an unsigned char * as a parameter, but the data I'm being sent is throwing a type mismatch error.

```<code>int main()
  {
  Queue * queue = newQueue ();
  addByteToQueue (queue, 1);
  addByteToQueue (queue, 2);
  addByteToQueue (queue, 3);
  return 0;
  }

void addByteToQueue (Queue * queue, unsigned char * byte)
  {
  // stuff
  }
</code>```

Visual studio is counting the 1/2/3 in the function calls as integers, which makes sense to me.  As a test, I also tried doing this:

```<code>unsigned char * a = 1;
</code>```

Similar error.  Now, I can't change the function prototype.  Assuming I'm being sent bad data in the call, how would one go about assigning the value of an unsigned char pointer?  Alternatively, is there some other crucial thing I'm missing that would make this work the way it is?

答:
There was a typo in the original version of the addByteToQueue prototype, which led to all the pointer confusion.  Here's the correct version, with a bit more of the code filled in:

```<code>class Queue
  {
  private:

    unsigned char queue[1024];
    int first = 0;
    int last = -1;

  public:

    void add (unsigned char b)
      {
      // adding to the queue
      }
  };

Queue * newQueue ();
void enqueue_byte (Queue * q, unsigned char b);

int main()
  {
  Queue * queue = newQueue ();
  addByteToQueue (queue, 1);
  addByteToQueue (queue, 2);
  addByteToQueue (queue, 3);
  return 0;
  }

Queue * newQueue ()
  {
  Queue * queue = new Queue ();
  return queue;
  }

// "unsigned char byte" instead of "unsigned char * byte"
void addByteToQueue (Queue * queue, unsigned char byte)
  {
  queue->add (byte);
  }
</code>```

I'm surprised it let me assign an integer to an unsigned char without some type of conversion, but it seems I'm learning a lot about C++ today.

Another solution would have been to keep the pointer param and modify the function call to be:

```<code>  unsigned char byte = 0;
  addByteToQueue (queue, &byte);
</code>```

In this case, however, this would have broken things for other people using the class.

Thanks to the people who commented and added answers.  This took a lot more reading and staring than I'd care to admit.

Body:
I've got a function that takes an unsigned char * as a parameter, but the data I'm being sent is throwing a type mismatch error.

int main()
  {
  Queue * queue = newQueue ();
  addByteToQueue (queue, 1);
  addByteToQueue (queue, 2);
  addByteToQueue (queue, 3);
  return 0;
  }

void addByteToQueue (Queue * queue, unsigned char * byte)
  {
  // stuff
  }

Visual studio is counting the 1/2/3 in the function calls as integers, which makes sense to me.  As a test, I also tried doing this:

unsigned char * a = 1;

Similar error.  Now, I can't change the function prototype.  Assuming I'm being sent bad data in the call, how would one go about assigning the value of an unsigned char pointer?  Alternatively, is there some other crucial thing I'm missing that would make this work the way it is?

Body:
There was a typo in the original version of the addByteToQueue prototype, which led to all the pointer confusion.  Here's the correct version, with a bit more of the code filled in:

class Queue
  {
  private:

    unsigned char queue[1024];
    int first = 0;
    int last = -1;

  public:

    void add (unsigned char b)
      {
      // adding to the queue
      }
  };

Queue * newQueue ();
void enqueue_byte (Queue * q, unsigned char b);

int main()
  {
  Queue * queue = newQueue ();
  addByteToQueue (queue, 1);
  addByteToQueue (queue, 2);
  addByteToQueue (queue, 3);
  return 0;
  }

Queue * newQueue ()
  {
  Queue * queue = new Queue ();
  return queue;
  }

// "unsigned char byte" instead of "unsigned char * byte"
void addByteToQueue (Queue * queue, unsigned char byte)
  {
  queue->add (byte);
  }

I'm surprised it let me assign an integer to an unsigned char without some type of conversion, but it seems I'm learning a lot about C++ today.

Another solution would have been to keep the pointer param and modify the function call to be:

  unsigned char byte = 0;
  addByteToQueue (queue, &byte);

In this case, however, this would have broken things for other people using the class.

Thanks to the people who commented and added answers.  This took a lot more reading and staring than I'd care to admit.


问:
Cannot convert type <class 'pyspark.mllib.regression.LabeledPoint'> into Vector while using StreamingLinearRegressionWithSGD
I am using SaprkStreaming to train a simple StreamingLinearRegressionWithSGD model with PySpark. Firstly, I was trying to simulate the random inputStream for model(fixed Vector w dots random Vector x, then plus random value obeying GuassianDistribution),code like below:

import sys
import socket
import time
import random
import numpy as np
from functools import reduce

def return_random_guass_seq(_type=list, len_term=10, mu=0, sigma=1, _scale=1):
    return _type([_scale*random.gauss(mu, sigma) for i in range(len_term)])

# set w vector
len_term = 100
w = return_random_guass_seq(_type=np.array, _scale=10, len_term=len_term)

socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_server.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
socket_server.bind((sys.argv[1], int(sys.argv[2])))
socket_server.listen(5)

while True:
    conn, (ip, port) = socket_server.accept()
    print(ip, port)
    while True:
        random_sleep_time = random.random()
        noisy = random.gauss(0, 1)*5
        x = return_random_guass_seq(_type=np.array, len_term=len_term)
        y = x.dot(w) + noisy
        time.sleep(random_sleep_time)
        s = str(y) + reduce(lambda i, j:str(i)+','+str(j), x, '')
        print(s)
        conn.send(bytes(s, 'utf-8'))
        conn.send(bytes('\n', 'utf-8'))
    socket_server.close()
```

<p>Then, I initialized StreamingLinearRegressionWithSGD model and tried to trainOn labeledStream,</p>

<pre class="lang-python prettyprint-override"><code>import sys
from pyspark.streaming import StreamingContext
from pyspark import SparkContext
from pyspark.mllib.linalg import Vectors
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.regression import StreamingLinearRegressionWithSGD
import numpy as np

#initialize sc,then initialize ssc
sc = SparkContext(appName="StreamingModel")
#just print ssc result and error
sc.setLogLevel("ERROR")

ssc = StreamingContext(sc, batchDuration=5)# 5 seconds window
stream = ssc.socketTextStream(sys.argv[1], int(sys.argv[2]))

#create model
len_term = 100
Model = StreamingLinearRegressionWithSGD(stepSize=0.1, numIterations=50)
Model.setInitialWeights(np.array([0.0, ]*len_term))

# create actions
labeledStream = stream.map(
    lambda x:tuple(x.split(','))
    ).map(
    lambda x:(float(x[0]), np.array([float(i) for i in x[1:]]) )
    ).map(
    lambda x:LabeledPoint(label=x[0], features=x[1])
    )

labeledStream.pprint()
Model.trainOn(labeledStream)
Model.predictOn(labeledStream).pprint()

# start sc_stream
ssc.start()
ssc.awaitTermination()
</code>```

And ran into the following error

TypeError: Cannot convert type <class 'pyspark.mllib.regression.LabeledPoint'> into Vector.

I can't figure out why this error happened. Was I misunderstanding something apperent or it was the result of negeligence?

Full trace:

Traceback (most recent call last):
  File "/home/zh/spark_hadoop/hadoop/tmp/nm-local-dir/usercache/zh/appcache/application_1512094491627_0072/container_1512094491627_0072_01_000003/pyspark.zip/pyspark/worker.py", line 177, in main
    process()
  File "/home/zh/spark_hadoop/hadoop/tmp/nm-local-dir/usercache/zh/appcache/application_1512094491627_0072/container_1512094491627_0072_01_000003/pyspark.zip/pyspark/worker.py", line 172, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "/home/zh/spark_hadoop/hadoop/tmp/nm-local-dir/usercache/zh/appcache/application_1512094491627_0072/container_1512094491627_0072_01_000003/pyspark.zip/pyspark/serializers.py", line 268, in dump_stream
    vs = list(itertools.islice(iterator, batch))
  File "/home/zh/spark_hadoop/spark/python/lib/pyspark.zip/pyspark/mllib/regression.py", line 746, in <lambda>
  File "/home/zh/spark_hadoop/hadoop/tmp/nm-local-dir/usercache/zh/appcache/application_1512094491627_0072/container_1512094491627_0072_01_000003/pyspark.zip/pyspark/mllib/regression.py", line 121, in predict
    x = _convert_to_vector(x)
  File "/home/zh/spark_hadoop/hadoop/tmp/nm-local-dir/usercache/zh/appcache/application_1512094491627_0072/container_1512094491627_0072_01_000003/pyspark.zip/pyspark/mllib/linalg/__init__.py", line 83, in _convert_to_vector
    raise TypeError("Cannot convert type %s into Vector" % type(l))
TypeError: Cannot convert type <class 'pyspark.mllib.regression.LabeledPoint'> into Vector

    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:193)
    at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:234)
    at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:152)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:63)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:63)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:108)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:335)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    ... 1 more
```

答:
StreamingLinearAlgorithm.predictOn requires DStream[Vector]. You have to map:

```<code>Model.predictOn(labeledStream.map(lambda x.features)).pprint()
</code>```

Body:
I am using SaprkStreaming to train a simple StreamingLinearRegressionWithSGD model with PySpark. Firstly, I was trying to simulate the random inputStream for model(fixed Vector w dots random Vector x, then plus random value obeying GuassianDistribution),code like below:

import sys
import socket
import time
import random
import numpy as np
from functools import reduce

def return_random_guass_seq(_type=list, len_term=10, mu=0, sigma=1, _scale=1):
    return _type([_scale*random.gauss(mu, sigma) for i in range(len_term)])

# set w vector
len_term = 100
w = return_random_guass_seq(_type=np.array, _scale=10, len_term=len_term)

socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_server.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
socket_server.bind((sys.argv[1], int(sys.argv[2])))
socket_server.listen(5)

while True:
    conn, (ip, port) = socket_server.accept()
    print(ip, port)
    while True:
        random_sleep_time = random.random()
        noisy = random.gauss(0, 1)*5
        x = return_random_guass_seq(_type=np.array, len_term=len_term)
        y = x.dot(w) + noisy
        time.sleep(random_sleep_time)
        s = str(y) + reduce(lambda i, j:str(i)+','+str(j), x, '')
        print(s)
        conn.send(bytes(s, 'utf-8'))
        conn.send(bytes('\n', 'utf-8'))
    socket_server.close()

Then, I initialized StreamingLinearRegressionWithSGD model and tried to trainOn labeledStream,

import sys
from pyspark.streaming import StreamingContext
from pyspark import SparkContext
from pyspark.mllib.linalg import Vectors
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.regression import StreamingLinearRegressionWithSGD
import numpy as np

#initialize sc,then initialize ssc
sc = SparkContext(appName="StreamingModel")
#just print ssc result and error
sc.setLogLevel("ERROR")

ssc = StreamingContext(sc, batchDuration=5)# 5 seconds window
stream = ssc.socketTextStream(sys.argv[1], int(sys.argv[2]))

#create model
len_term = 100
Model = StreamingLinearRegressionWithSGD(stepSize=0.1, numIterations=50)
Model.setInitialWeights(np.array([0.0, ]*len_term))

# create actions
labeledStream = stream.map(
    lambda x:tuple(x.split(','))
    ).map(
    lambda x:(float(x[0]), np.array([float(i) for i in x[1:]]) )
    ).map(
    lambda x:LabeledPoint(label=x[0], features=x[1])
    )

labeledStream.pprint()
Model.trainOn(labeledStream)
Model.predictOn(labeledStream).pprint()

# start sc_stream
ssc.start()
ssc.awaitTermination()

And ran into the following error

TypeError: Cannot convert type <class 'pyspark.mllib.regression.LabeledPoint'> into Vector.

I can't figure out why this error happened. Was I misunderstanding something apperent or it was the result of negeligence?

Full trace:

Traceback (most recent call last):
  File "/home/zh/spark_hadoop/hadoop/tmp/nm-local-dir/usercache/zh/appcache/application_1512094491627_0072/container_1512094491627_0072_01_000003/pyspark.zip/pyspark/worker.py", line 177, in main
    process()
  File "/home/zh/spark_hadoop/hadoop/tmp/nm-local-dir/usercache/zh/appcache/application_1512094491627_0072/container_1512094491627_0072_01_000003/pyspark.zip/pyspark/worker.py", line 172, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "/home/zh/spark_hadoop/hadoop/tmp/nm-local-dir/usercache/zh/appcache/application_1512094491627_0072/container_1512094491627_0072_01_000003/pyspark.zip/pyspark/serializers.py", line 268, in dump_stream
    vs = list(itertools.islice(iterator, batch))
  File "/home/zh/spark_hadoop/spark/python/lib/pyspark.zip/pyspark/mllib/regression.py", line 746, in <lambda>
  File "/home/zh/spark_hadoop/hadoop/tmp/nm-local-dir/usercache/zh/appcache/application_1512094491627_0072/container_1512094491627_0072_01_000003/pyspark.zip/pyspark/mllib/regression.py", line 121, in predict
    x = _convert_to_vector(x)
  File "/home/zh/spark_hadoop/hadoop/tmp/nm-local-dir/usercache/zh/appcache/application_1512094491627_0072/container_1512094491627_0072_01_000003/pyspark.zip/pyspark/mllib/linalg/__init__.py", line 83, in _convert_to_vector
    raise TypeError("Cannot convert type %s into Vector" % type(l))
TypeError: Cannot convert type <class 'pyspark.mllib.regression.LabeledPoint'> into Vector

    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:193)
    at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:234)
    at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:152)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:63)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:63)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:108)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:335)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    ... 1 more

Body:
StreamingLinearAlgorithm.predictOn requires DStream[Vector]. You have to map:

Model.predictOn(labeledStream.map(lambda x.features)).pprint()


问:
JS Google Maps API v3 Animate Marker Between Coordinates
I have a simple javascript maps application that I'm working on that requires me to animate the movement of multiple markers between different coords. Each marker is free to move on its own and all markers are stored in an array list. However, I have been having trouble getting them to smoothly transition locations.

I've done a ton of research and trial/error but no luck, anyone have any luck with this?

答:
An alternative is to use CSS transitions. The important bit is identifying the DIVs Google Maps is using for your marker (There are 2 one is transparent for touch events) The investigation has been done for you and you really only have to understand it once.

A complete example can be found here See how smoothly Hansel and Gretel move around the map! And the transition times coalesce if there is any delay.

All the code for my Brotkrumen Ultimate Web App can be found here you will be mostly interested in the HandleMap.js file but there is a aaa_readme.txt

Here is part of the code: -

```<code>function showJourney(){
    map.setZoom(map.getZoom());
    map.setOptions({gestureHandling: "none"});
    zoomOut.style.display = "none";
    zoomIn.style.display  = "none";

    hat.setPosition(
        new google.maps.LatLng(
                lastPos.coords.latitude,
                lastPos.coords.longitude));
    hat.setVisible(true);
    hat.setAnimation(bounce);

    HandG.setPosition(
        new google.maps.LatLng(
                firstPos.coords.latitude,
                firstPos.coords.longitude));
    HandG.setVisible(true);

    map.panTo(path[0]);
    google.maps.event.trigger(map, 'resize');

    if (document.querySelectorAll(MARKER_SELECTOR).length == 0){
        observer.observe(mapDiv, {
                        childList     : true,
                        subtree       : true ,
                        attributes    : true ,
                        characterData : false
                        })
    } else {
        setTimeout(plotTrip,0);
    }
}
function plotTrip(){
    nextFunc = plotStep;
    hat.setAnimation(bounce);
    HandG.setPosition(path[0]);
    dirPoly.setVisible(true);
    progressPath = [];
    progressPath.push(path[0]);
    dirPoly.setPath(path);
    stepPoly.setPath(progressPath);
    stepPoly.setVisible(true);
    currStep = 1;
    markerDivs = [];
    var markerImgs = document.querySelectorAll(MARKER_SELECTOR);
    for (var i=0; i<markerImgs.length; i++){
        console.log(markerImgs[i].src);
        markerDivs[i] = markerImgs[i].parentNode;
        markerDivs[i].style.transitionDuration = "0s";
        markerDivs[i].style.transitionProperty = "left, top";
        markerDivs[i].style.transitionTimingFunction = "linear";
    }

    setTimeout(plotStep,0);
    abort = false;
    btn.value = "Cancel";
    btn.disabled = false;
}
function plotStep(){
    if (abort) return;

    if (legs[currStep].didLoiter){
        countDown = legs[currStep].restTime;
        infoWindow.setContent(
            "<div id='waitDiv'><span>Waiting</span></div>");
        infoWindow.open(map,HandG);
        showInterval();
    } else {
        plotIt();
    }
}
function showInterval(){
    if (abort) return;

    infoWindow.setContent(
        "<div id='waitDiv'><span>Waiting "+deltaDate(countDown)+"</span></div>");
    countDown -= (ONE_SEC * multiSpeed);
    if (countDown < 1){
        infoWindow.close();
        plotIt();
    } else {
        setTimeout(showInterval, ONE_SEC);
    }
}
function plotIt(){
    if (abort) return;

    progressPath.push(path[currStep]);
    stepPoly.setPath(progressPath);
    map.panTo(path[currStep]);
    var transitionMS = legs[currStep].duration / multiSpeed;
    for (var i=0; i<markerDivs.length; i++){
        markerDivs[i].style.transitionDuration = transitionMS + "ms";
    }
    HandG.setPosition(path[currStep])

    if (++currStep >= path.length)
        nextFunc = cleanUp;

    plotTimer = setTimeout(nextFunc,transitionMS);
}
function cleanUp(){
    infoWindow.close();
    hat.setAnimation();
    btn.value = "Replay";
    btn.disabled = false;
    clearTimeout(plotTimer);
    for (var i=0; i<markerDivs.length; i++){
        markerDivs[i].style.transitionDuration = "0s";
    }
    HandG.setPosition(
        new google.maps.LatLng(
                lastPos.coords.latitude,
                lastPos.coords.longitude));
    HandG.setVisible(false);
    map.setOptions({gestureHandling: "cooperative"});
    zoomIn.style.display  = "";
    zoomOut.style.display = "";
    if (canTalk && !abort)
        speechSynthesis.speak(finish);
}
function waitForMarker(mutations, myInstance) {
    outer:
    for (var i=0; i<mutations.length; i++){
        if (mutations[i].type           == "attributes" &&
            mutations[i].target.tagName == "IMG"        &&
            mutations[i].target.src.toLowerCase().indexOf(MARKER_SRC) != -1){
            console.log("result")
            myInstance.disconnect();
            setTimeout(plotTrip,0)
            break outer;
        }
        if (mutations[i].type != "childList" ||
            mutations[i].addedNodes.length   == 0)
            continue;
        for (var j=0; j<mutations[i].addedNodes.length; j++) {
            var node = mutations[i].addedNodes[j];
            if (node.tagName == "DIV" && node.firstChild && node.firstChild.tagName == "IMG" &&
                node.firstChild.src.toLowerCase().indexOf(MARKER_SRC) != -1){
                console.log(node.firstChild.src);
                myInstance.disconnect();
                setTimeout(plotTrip,0)
                break outer;
            }
        }
    }
}
</code>```

Body:
An alternative is to use CSS transitions. The important bit is identifying the DIVs Google Maps is using for your marker (There are 2 one is transparent for touch events) The investigation has been done for you and you really only have to understand it once.

A complete example can be found here See how smoothly Hansel and Gretel move around the map! And the transition times coalesce if there is any delay.

All the code for my Brotkrumen Ultimate Web App can be found here you will be mostly interested in the HandleMap.js file but there is a aaa_readme.txt

Here is part of the code: -

function showJourney(){
    map.setZoom(map.getZoom());
    map.setOptions({gestureHandling: "none"});
    zoomOut.style.display = "none";
    zoomIn.style.display  = "none";

    hat.setPosition(
        new google.maps.LatLng(
                lastPos.coords.latitude,
                lastPos.coords.longitude));
    hat.setVisible(true);
    hat.setAnimation(bounce);

    HandG.setPosition(
        new google.maps.LatLng(
                firstPos.coords.latitude,
                firstPos.coords.longitude));
    HandG.setVisible(true);

    map.panTo(path[0]);
    google.maps.event.trigger(map, 'resize');

    if (document.querySelectorAll(MARKER_SELECTOR).length == 0){
        observer.observe(mapDiv, {
                        childList     : true,
                        subtree       : true ,
                        attributes    : true ,
                        characterData : false
                        })
    } else {
        setTimeout(plotTrip,0);
    }
}
function plotTrip(){
    nextFunc = plotStep;
    hat.setAnimation(bounce);
    HandG.setPosition(path[0]);
    dirPoly.setVisible(true);
    progressPath = [];
    progressPath.push(path[0]);
    dirPoly.setPath(path);
    stepPoly.setPath(progressPath);
    stepPoly.setVisible(true);
    currStep = 1;
    markerDivs = [];
    var markerImgs = document.querySelectorAll(MARKER_SELECTOR);
    for (var i=0; i<markerImgs.length; i++){
        console.log(markerImgs[i].src);
        markerDivs[i] = markerImgs[i].parentNode;
        markerDivs[i].style.transitionDuration = "0s";
        markerDivs[i].style.transitionProperty = "left, top";
        markerDivs[i].style.transitionTimingFunction = "linear";
    }

    setTimeout(plotStep,0);
    abort = false;
    btn.value = "Cancel";
    btn.disabled = false;
}
function plotStep(){
    if (abort) return;

    if (legs[currStep].didLoiter){
        countDown = legs[currStep].restTime;
        infoWindow.setContent(
            "<div id='waitDiv'><span>Waiting</span></div>");
        infoWindow.open(map,HandG);
        showInterval();
    } else {
        plotIt();
    }
}
function showInterval(){
    if (abort) return;

    infoWindow.setContent(
        "<div id='waitDiv'><span>Waiting "+deltaDate(countDown)+"</span></div>");
    countDown -= (ONE_SEC * multiSpeed);
    if (countDown < 1){
        infoWindow.close();
        plotIt();
    } else {
        setTimeout(showInterval, ONE_SEC);
    }
}
function plotIt(){
    if (abort) return;

    progressPath.push(path[currStep]);
    stepPoly.setPath(progressPath);
    map.panTo(path[currStep]);
    var transitionMS = legs[currStep].duration / multiSpeed;
    for (var i=0; i<markerDivs.length; i++){
        markerDivs[i].style.transitionDuration = transitionMS + "ms";
    }
    HandG.setPosition(path[currStep])

    if (++currStep >= path.length)
        nextFunc = cleanUp;

    plotTimer = setTimeout(nextFunc,transitionMS);
}
function cleanUp(){
    infoWindow.close();
    hat.setAnimation();
    btn.value = "Replay";
    btn.disabled = false;
    clearTimeout(plotTimer);
    for (var i=0; i<markerDivs.length; i++){
        markerDivs[i].style.transitionDuration = "0s";
    }
    HandG.setPosition(
        new google.maps.LatLng(
                lastPos.coords.latitude,
                lastPos.coords.longitude));
    HandG.setVisible(false);
    map.setOptions({gestureHandling: "cooperative"});
    zoomIn.style.display  = "";
    zoomOut.style.display = "";
    if (canTalk && !abort)
        speechSynthesis.speak(finish);
}
function waitForMarker(mutations, myInstance) {
    outer:
    for (var i=0; i<mutations.length; i++){
        if (mutations[i].type           == "attributes" &&
            mutations[i].target.tagName == "IMG"        &&
            mutations[i].target.src.toLowerCase().indexOf(MARKER_SRC) != -1){
            console.log("result")
            myInstance.disconnect();
            setTimeout(plotTrip,0)
            break outer;
        }
        if (mutations[i].type != "childList" ||
            mutations[i].addedNodes.length   == 0)
            continue;
        for (var j=0; j<mutations[i].addedNodes.length; j++) {
            var node = mutations[i].addedNodes[j];
            if (node.tagName == "DIV" && node.firstChild && node.firstChild.tagName == "IMG" &&
                node.firstChild.src.toLowerCase().indexOf(MARKER_SRC) != -1){
                console.log(node.firstChild.src);
                myInstance.disconnect();
                setTimeout(plotTrip,0)
                break outer;
            }
        }
    }
}

ContentLicense: CC BY-SA 4.0


问:
Spark standalone mode not distributing job to other worker node
I am running a spark job in standalone mode. I have configured my worker node to connect to master node. They are getting connected successfully, but when I am running the job on spark master the job is not getting distributed. I keep on getting the following message-

WARN TaskSchedulerImpl: Initial job has not accepted any resources;
  check your cluster UI to ensure that workers are registered and have
  sufficient resources

I have tried to run the job as local on the worker node and its running fine which means resources are available. Also the spark master-ui is showing that the worker has accepted the job.Password less ssh is enabled in both master and worker node to and fro.  I feel it might be some firewall issue or may be spark driver port is not opened. My worker node logs show-

16/03/21 10:05:40 INFO ExecutorRunner: Launch command:
  "/usr/lib/jvm/java-7-oracle/bin/java" "-cp"
  "/mnt/pd1/spark/spark-1.5.0-bin-hadoop2.6/sbin/../conf/:/mnt/pd1/spark/spark-1.5.0-bin-hadoop2.6/lib/spark-assembly-1.5.0-hadoop2.6.0.jar:/mnt/pd1/spark/spark-1.5.0-bin-hadoop2.6/lib/datanucleus-rdbms-3.2.9.jar:/mnt/pd1/spark/spark-1.5.0-bin-hadoop2.6/lib/datanucleus-api-jdo-3.2.6.jar:/mnt/pd1/spark/spark-1.5.0-bin-hadoop2.6/lib/datanucleus-core-3.2.10.jar"
  "-Xms8192M" "-Xmx8192M" "-Dspark.driver.port=51810"
  "-Dspark.cassandra.connection.port=9042" "-XX:MaxPermSize=256m"
  "org.apache.spark.executor.CoarseGrainedExecutorBackend"
  "--driver-url"
  "akka.tcp://sparkDriver@10.0.1.192:51810/user/CoarseGrainedScheduler"
  "--executor-id" "2" "--hostname" "10.0.1.194" "--cores" "4" "--app-id"
  "app-20160321100135-0001" "--worker-url"
  "akka.tcp://sparkWorker@10.0.1.194:39423/user/Worker"

Executor at worker nodes shows the following log in stderr-

16/03/21 10:13:52 INFO Slf4jLogger: Slf4jLogger started 16/03/21
  10:13:52 INFO Remoting: Starting remoting 16/03/21 10:13:52 INFO
  Remoting: Remoting started; listening on addresses
  :[akka.tcp://driverPropsFetcher@10.0.1.194:59715] 16/03/21 10:13:52
  INFO Utils: Successfully started service 'driverPropsFetcher' on port
  59715.

答:
Many people have the issue when setting up new clusters. If you can find spark slaves in the web UI but they are not accepting jobs, there is a high chance that the firewall is blocking the communication. Take a look at my other answer: Apache Spark on Mesos: Initial job has not accepted any resources:

While most of other answers focuses on resource allocation (cores, memory) on spark slaves, I would like to highlight that firewall could cause exactly the same issue, especially when you are running spark on cloud platforms.

If you can find spark slaves in the web UI, you have probably opened the standard ports 8080, 8081, 7077, 4040. Nonetheless, when you actually run a job, it uses SPARK_WORKER_PORT, spark.driver.port and spark.blockManager.port which by default are randomly assigned. If your firewall is blocking these ports, the master could not retrieve any job-specific response from slaves and return the error.

You can run a quick test by opening all the ports and see whether the slave accepts jobs.


问:
Send an email +attachment using dependency services DROID Xamarin forms
I came across this error when Trying to send an email with attachment. any help ? Thank you

****Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?****

this is my code :

```<code>[assembly: Dependency(typeof(sendEmail))]
namespace myapp.Droid
{
    public class sendEmail : IEmailTask
    {
        public sendEmail()
        {

        }

        public void SendEmail ()
        {
            var sqlliteFilname = "test.3gpp";
            string documentsPath = System.Environment.GetFolderPath(
            Environment.SpecialFolder.Personal);
            var stringPath = Path.Combine(documentsPath, sqlliteFilname);

            var path = Android.Net.Uri.FromFile(new
           Java.IO.File(stringPath));

            Intent emailIntent = new Intent(Intent.ActionSend);
            // set the type to 'email'
            emailIntent.SetData(Android.Net.Uri.Parse("mailto:"));

            String[] to = { "youremail@mail.com" };

            emailIntent.PutExtra(Intent.ExtraEmail, to);
            // the attachment
            emailIntent.PutExtra(Intent.ExtraStream, path);
            // the mail subject
            emailIntent.PutExtra(Intent.ExtraSubject, "Subject");

           Android.App.Application.Context.StartActivity(Intent.CreateChooser(emailIntent, "Send email..."));

        }
    }
}
</code>```

code on the page is :

```<code> void btnSendingHandle_Clicked(object sender, System.EventArgs e)
        {
            var getEmail = DependencyService.Get<IEmailTask>();

            getEmail.SendEmail();
        }
</code>```

答:
Like Nick had said

you could use Forms.Context to start activity.

Or

you could add emailIntent.SetFlags(ActivityFlags.NewTask); in your emailIntent.

In Android, every Activity should have its own task stack which you can use taskAffinity to define it, the package's name is the default value. But if you use Application.Context to start activity, there is not task stack for your activity, so it suggests you to use FLAG_ACTIVITY_NEW_TASK flag, this flag will create a task stack for you activity.

Body:
I came across this error when Trying to send an email with attachment. any help ? Thank you

****Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?****

this is my code :

[assembly: Dependency(typeof(sendEmail))]
namespace myapp.Droid
{
    public class sendEmail : IEmailTask
    {
        public sendEmail()
        {

        }

        public void SendEmail ()
        {
            var sqlliteFilname = "test.3gpp";
            string documentsPath = System.Environment.GetFolderPath(
            Environment.SpecialFolder.Personal);
            var stringPath = Path.Combine(documentsPath, sqlliteFilname);

            var path = Android.Net.Uri.FromFile(new
           Java.IO.File(stringPath));

            Intent emailIntent = new Intent(Intent.ActionSend);
            // set the type to 'email'
            emailIntent.SetData(Android.Net.Uri.Parse("mailto:"));

            String[] to = { "youremail@mail.com" };

            emailIntent.PutExtra(Intent.ExtraEmail, to);
            // the attachment
            emailIntent.PutExtra(Intent.ExtraStream, path);
            // the mail subject
            emailIntent.PutExtra(Intent.ExtraSubject, "Subject");

           Android.App.Application.Context.StartActivity(Intent.CreateChooser(emailIntent, "Send email..."));

        }
    }
}

code on the page is :

 void btnSendingHandle_Clicked(object sender, System.EventArgs e)
        {
            var getEmail = DependencyService.Get<IEmailTask>();

            getEmail.SendEmail();
        }


问:
"<Message: title>" needs to have a value for field "id" before this many-to-many relationship can be used.
I have a Message model, And in it I have create_user ForeignKey and receive_user ManyToManyField:

```<code>class Message(models.Model):
    """
    消息
    """
    message_num = models.CharField(default=getMessageNum, max_length=16, help_text="消息") # 注意：message_num 相同，说明是同一次发送

    title = models.CharField(max_length=64, help_text="消息名称")
    content = models.CharField(max_length=1024, help_text="消息内容")

    create_user = models.ForeignKey(User, related_name="created_messages",help_text="创建者")
    receive_user = models.ManyToManyField(User, related_name="received_messages", help_text="接受者")

    def __str__(self):
        return self.title
    def __unicode__(self):
        return self.title
</code>```

When I use the bellow to save a message, I except a exception:

```<code>try:
    receive_user = User.objects.get(id=user_id)
    message = Message.objects.create(
        title=title,
        content=content,
        create_user=create_user,
        receive_user=receive_user,
    )
    message.save()
except Exception as e:
    raise e
</code>```

I get the exception:

```<code>"<Message: title>" needs to have a value for field "id" before this many-to-many relationship can be used.
</code>```

How to resolve this issue? some friend can help me about this?

答:
Django documentation: https://docs.djangoproject.com/en/1.11/topics/db/examples/many_to_many/

Check code after

What follows are examples of operations that can be performed using
  the Python API facilities. Note that if you are using an intermediate
  model for a many-to-many relationship, some of the related manager’s
  methods are disabled, so some of these examples won’t work with such
  models.

My must save parent model first, and only after that you can add m2m values. Check below

```<code>    receive_user = User.objects.get(id=user_id)
    message = Message.objects.create(
        title=title,
        content=content,
        create_user=create_user,
        # receive_user=receive_user,
    )
    # message.save() - no needs in save() when you use create() method
    message.receive_user.add(receive_user)
</code>```

Body:
I have a Message model, And in it I have create_user ForeignKey and receive_user ManyToManyField:

class Message(models.Model):
    """
    消息
    """
    message_num = models.CharField(default=getMessageNum, max_length=16, help_text="消息") # 注意：message_num 相同，说明是同一次发送

    title = models.CharField(max_length=64, help_text="消息名称")
    content = models.CharField(max_length=1024, help_text="消息内容")

    create_user = models.ForeignKey(User, related_name="created_messages",help_text="创建者")
    receive_user = models.ManyToManyField(User, related_name="received_messages", help_text="接受者")

    def __str__(self):
        return self.title
    def __unicode__(self):
        return self.title

When I use the bellow to save a message, I except a exception:

try:
    receive_user = User.objects.get(id=user_id)
    message = Message.objects.create(
        title=title,
        content=content,
        create_user=create_user,
        receive_user=receive_user,
    )
    message.save()
except Exception as e:
    raise e

I get the exception:

"<Message: title>" needs to have a value for field "id" before this many-to-many relationship can be used.

How to resolve this issue? some friend can help me about this?

Body:
Django documentation: https://docs.djangoproject.com/en/1.11/topics/db/examples/many_to_many/

Check code after

What follows are examples of operations that can be performed using
  the Python API facilities. Note that if you are using an intermediate
  model for a many-to-many relationship, some of the related manager’s
  methods are disabled, so some of these examples won’t work with such
  models.

My must save parent model first, and only after that you can add m2m values. Check below

    receive_user = User.objects.get(id=user_id)
    message = Message.objects.create(
        title=title,
        content=content,
        create_user=create_user,
        # receive_user=receive_user,
    )
    # message.save() - no needs in save() when you use create() method
    message.receive_user.add(receive_user)


问:
Set loadURLTImeOutValue on WebView
I'm working with PhoneGap and Android and have my .html and js files on an external server.  When I use the following code, the app loads my external .html files and everything works fine:

```<code>this.setIntegerProperty("loadUrlTimeoutValue", 60000);
this.loadUrl("http://www.myserver.com");
</code>```

However, when work via a WebView I can't seem to set the loadURLTimeoutValue for a WebView:

```<code>private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

try {
     webView = (WebView) findViewById(R.id.webview);
     webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
     webView.loadUrl("http://www.myserver.com");
}
</code>```

This doesn't work. How can I set the timeout value on the WebView?

答:
```<code>WebView mWebView = findViewById(R.id.web_view);
mWebView.setWebViewClient(new WebViewClient() {
    private volatile boolean timeout;
    private volatile String timeoutOnPageStartedURL;
    private volatile String timeoutCurrentURL;

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);

        timeout = true;
        timeoutOnPageStartedURL = url;
        timeoutCurrentURL = view.getUrl();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (timeout) {
                    view.post(new Runnable() {
                        @Override
                        public void run() {
                            String currentURL = view.getUrl();
                            if ((timeoutOnPageStartedURL.hashCode() == currentURL.hashCode()) ||
                                (timeoutCurrentURL.hashCode() == currentURL.hashCode())) {
                                // do what you want with UI
                            }
                        }
                    });
                }
            }
        }).start();
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

        timeout = false;
    }
});
</code>```

Title: Set loadURLTImeOutValue on WebView

Body:
I'm working with PhoneGap and Android and have my .html and js files on an external server.  When I use the following code, the app loads my external .html files and everything works fine:

this.setIntegerProperty("loadUrlTimeoutValue", 60000);
this.loadUrl("http://www.myserver.com");

However, when work via a WebView I can't seem to set the loadURLTimeoutValue for a WebView:

private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

try {
     webView = (WebView) findViewById(R.id.webview);
     webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
     webView.loadUrl("http://www.myserver.com");
}

This doesn't work. How can I set the timeout value on the WebView?


问:
Best way to to create this field for my model
Hello everyone I just started with django and was wondering how to do the following behaivor in my models:

```<code>class Game(models.Model)
  characters_count = models.IntegerField(default=1) #basically i set to a choice of 1-3

class Match(models.Model)
 video=models.ForeignKey(Game)
 p1char1 = models.ForeignKey(Character)
 p2char1 = models.ForeignKey(Character)
 p1char2 = models.ForeignKey(Character)
 p2char2 = models.ForeignKey(Character)
 p1char3 = models.ForeignKey(Character)
 p2char3 = models.ForeignKey(Character)
</code>```

video contains the instance game which Match relies on.

I need to create a constraint that the Character selected is from the given game and that the number of characters each player selects is limited by game as well.

Should I perform this on the Save method? or can I set these constraints some other way so the forms will be generated by the models accordingly without doing it manually.

Will the limitation on the characters (by the game) can be done on the definition of the model?

答:
for your characters you should create a Many to Many relation with your character Model.

Then override Match save() method to constrain the number of characters selected.

Another way would be to put this constraint in the clean() method of a modelform based on match : so they have a list to choose from (use a checkbox list widget) and if they select too much character, the form will relaod with the error message you'll put in clean()

To limit the character depending on the game, you can add another M2M relation between Character and Game ('allowed_in_game') : in the admin, you'll be able to choose the characters from a game.

Then, in the Match Modelform, you'll have to modifiy the ModelchoiceField showing characters to filter them to show only the ones which are related to the current Game.

Here's how (just borrowed from here) :

```<code>class Matchform(forms.ModelForm):
    class Meta:
        model = Match

     def __init__(self, game, *args, **kwargs):
         super(Matchform, self).__init__(*args, **kwargs)
         self.fields['character'].queryset = Character.objects.filter(allowed_in_game__in = game)
</code>```

Then you can call your modified ModelForm like this :

```<code>Matchform(game)
Matchform(game,request.POST)
Matchform(game,instance=m)
</code>```

You can see that everytime the "game" parameter is added, it should be a Game object for this example to work.

Hope this helps....

ContentLicense: CC BY-SA 2.5

Body:
Hello everyone I just started with django and was wondering how to do the following behaivor in my models:

class Game(models.Model)
  characters_count = models.IntegerField(default=1) #basically i set to a choice of 1-3

class Match(models.Model)
 video=models.ForeignKey(Game)
 p1char1 = models.ForeignKey(Character)
 p2char1 = models.ForeignKey(Character)
 p1char2 = models.ForeignKey(Character)
 p2char2 = models.ForeignKey(Character)
 p1char3 = models.ForeignKey(Character)
 p2char3 = models.ForeignKey(Character)

video contains the instance game which Match relies on.

I need to create a constraint that the Character selected is from the given game and that the number of characters each player selects is limited by game as well.

Should I perform this on the Save method? or can I set these constraints some other way so the forms will be generated by the models accordingly without doing it manually.

Will the limitation on the characters (by the game) can be done on the definition of the model?

Body:
for your characters you should create a Many to Many relation with your character Model.

Then override Match save() method to constrain the number of characters selected.

Another way would be to put this constraint in the clean() method of a modelform based on match : so they have a list to choose from (use a checkbox list widget) and if they select too much character, the form will relaod with the error message you'll put in clean()

To limit the character depending on the game, you can add another M2M relation between Character and Game ('allowed_in_game') : in the admin, you'll be able to choose the characters from a game.

Then, in the Match Modelform, you'll have to modifiy the ModelchoiceField showing characters to filter them to show only the ones which are related to the current Game.

Here's how (just borrowed from here) :

class Matchform(forms.ModelForm):
    class Meta:
        model = Match

     def __init__(self, game, *args, **kwargs):
         super(Matchform, self).__init__(*args, **kwargs)
         self.fields['character'].queryset = Character.objects.filter(allowed_in_game__in = game)

Then you can call your modified ModelForm like this :

Matchform(game)
Matchform(game,request.POST)
Matchform(game,instance=m)

You can see that everytime the "game" parameter is added, it should be a Game object for this example to work.

Hope this helps....


问:
Javascript: Convert Array of Arrays Into Array of Objects
I am attempting to change an array of arrays containing two value arrays into an array of two objects.

I'm fairly new to JS and I'm not sure where my code is wrong. The array being logged to the console contains the same two objects.

let myArray = [
  [
    ['name', 'John'],
    ['job', 'Janitor']
  ],
  [
    ['name', 'Rob'],
    ['job', 'CEO']
  ]
];

function transformEmployeeData(array) {
  let arrayOfObjects = [];
  let newObj = {};
  // iterates through employees
  for (let i = 0; i < array.length; i++) {
    // resets obj to empty
    newObj = {};
    // iterates through employees properties
    for (let j = 0; j < array[i].length; j++) {
      newObj[array[j][j][0]] = array[j][j][1];
    }
    // pushes object into array
    arrayOfObjects.push(newObj);
  }
  return arrayOfObjects;
}

console.log(transformEmployeeData(myArray));```

答:
Your code is wrong here:

```<code>newObj[array[j][j][0]] = array[j][j][1];
</code>```

Should be:

```<code>newObj[array[i][j][0]] = array[i][j][1];
</code>```

Body:
Your code is wrong here:

newObj[array[j][j][0]] = array[j][j][1];

Should be:

newObj[array[i][j][0]] = array[i][j][1];


问:
iOS build failure in PhoneGap Build "error: Compiling IB documents for earlier than iOS 7 is no longer supported"
iOS build failure in PhoneGap Build
error: Compiling IB documents for earlier than iOS 7 is no longer supported.

Last successful build was on Dec 3. It fails since Dec 7.

Got to know that XCode 9 will not support storyboards that are built for iOS version less than 7.

I changed deployment-target to 7.0 and the build was successful.

<preference name="deployment-target" value="7.0"/>

Need to know if there was any Phonegap Build Xcode update happened recently?

答: iOS build issue is resolved and now I could create iOS builds successfully. No idea what happened yesterday with error though.</p>


问:
I cant pick up the carriage return in my program
These are the instructions for my program:

The first line on this file will hold a number indicating how many lines will follow. Every line after that will have a word and an integer on it. Fill up two arrays, one for the word and one for the integer. Once the arrays are filled, go to each element of the String array and print out that String the number of times the parallel number array says for it to print.

However, when I try to print out the answer, an error occurs, saying there's no line to pick up when reading from the file I'm supposed to.

```<code>    Scanner input = new Scanner(new File("parallel.txt"));
    int numLine = input.nextInt();

    int [] array = new int[numLine];
    String [] Stringarray = new String[numLine];

    for (int i = 0; i< numLine; i++)
        {
            Stringarray[i] = input.next();
            array[i] = input.nextInt();
            input.nextLine();
        }

    for (int i = 0; i<Stringarray.length; i++)
        {
            for (int a = 0; a<array[a]; a++)
                out.print(Stringarray[i] + " ");
            out.println();
        }

}
</code>```

}

答:
In the first part of your code, you read the first integer in the file, and but you fail to read the newline character. You then attempt to read the first token from the second line with Stringarray[i] = input.next() but your scanner is still waiting on the first line and there is no next. You can fix that like so:

```<code>int numLine = input.nextInt();
input.nextLine();
</code>```

I prefer to read an entire line at once, and then parse it separately, it's much cleaner. For example, and without any error checking:

```<code>String line = input.nextLine();
int number = Integer.parseInt(line); // parse the entire line as an integer

String line = input.nextLine();
String[] parts = line.split(" "); // split the line on spaces
String word = parts[0]; // treat the first part as a string
int number = Integer.parseInt(parts[1]); // parse the second part as an integer
</code>```

In the second part of your code, to print out the word X times you need to index the numbers array with the same index as the word array.

```<code>for (int i = 0; i < Stringarray.length; i++) // for each word in the Stringarray
{
    for (int a = 0; a < array[i]; a++) // index with i, not a
        System.out.print(Stringarray[i] + " "); // print the word
    System.out.println();
}
</code>```

Body:
These are the instructions for my program:

The first line on this file will hold a number indicating how many lines will follow. Every line after that will have a word and an integer on it. Fill up two arrays, one for the word and one for the integer. Once the arrays are filled, go to each element of the String array and print out that String the number of times the parallel number array says for it to print.

However, when I try to print out the answer, an error occurs, saying there's no line to pick up when reading from the file I'm supposed to.

    Scanner input = new Scanner(new File("parallel.txt"));
    int numLine = input.nextInt();

    int [] array = new int[numLine];
    String [] Stringarray = new String[numLine];

    for (int i = 0; i< numLine; i++)
        {
            Stringarray[i] = input.next();
            array[i] = input.nextInt();
            input.nextLine();
        }

    for (int i = 0; i<Stringarray.length; i++)
        {
            for (int a = 0; a<array[a]; a++)
                out.print(Stringarray[i] + " ");
            out.println();
        }

}

}

Body:
In the first part of your code, you read the first integer in the file, and but you fail to read the newline character. You then attempt to read the first token from the second line with Stringarray[i] = input.next() but your scanner is still waiting on the first line and there is no next. You can fix that like so:

int numLine = input.nextInt();
input.nextLine();

I prefer to read an entire line at once, and then parse it separately, it's much cleaner. For example, and without any error checking:

String line = input.nextLine();
int number = Integer.parseInt(line); // parse the entire line as an integer

String line = input.nextLine();
String[] parts = line.split(" "); // split the line on spaces
String word = parts[0]; // treat the first part as a string
int number = Integer.parseInt(parts[1]); // parse the second part as an integer

In the second part of your code, to print out the word X times you need to index the numbers array with the same index as the word array.

for (int i = 0; i < Stringarray.length; i++) // for each word in the Stringarray
{
    for (int a = 0; a < array[i]; a++) // index with i, not a
        System.out.print(Stringarray[i] + " "); // print the word
    System.out.println();
}


问:
Elixir: Run function after another function
I'm still quite new to Elixir and checking out some code in a repository and wondering if there is a way to cut down the following code snippet:

```<code>  def find(client) do
    Common.find(client, @resource)
    |> ResponseHandler.handle_response(@model_module)
  end

  def find(client, identifier) do
    Common.find(client, @resource, identifier)
    |> ResponseHandler.handle_response(@model_module)
  end

  def filter(client, filter) do
    Common.filter(client, @resource, filter)
    |> ResponseHandler.handle_response(@model_module)
  end

  def create(client, bank_transactions_map) do
    Common.create(client, @resource, bank_transactions_map)
    |> ResponseHandler.handle_response(@model_module)
  end

  def update(client, identifier, bank_transactions_map) do
    Common.update(client, @resource, identifier, bank_transactions_map)
    |> ResponseHandler.handle_response(@model_module)
  end
</code>```

All the functions here pipe into the same function and it seems a little repetitive. Is there a way to set up a function in the module to take in an argument and run the .handle_response line without setting it in each function here?

答:
You can define a new function which takes in the function name to call along with the arguments and that function will pipe into ResponseHandler.handle_response(@model_module) at the end. The following code is untested but should work:

```<code>def find(client) do
  go(:find, [client, @resource])
end

def find(client, identifier) do
  go(:find, [client, @resource, identifier])
end

...

def go(function, args) do
  apply(Common, function, args)
  |> ResponseHandler.handle_response(@model_module)
end
</code>```

You can also automatically inject @resource as the second argument if you want:

```<code>def find(client) do
  go(:find, [client])
end

def find(client, identifier) do
  go(:find, [client, identifier])
end

...

def go(function, [head | tail]) do
  apply(Common, function, [head, @resource | tail])
  |> ResponseHandler.handle_response(@model_module)
end
</code>```

You can reduce this even further using macros/metaprogramming but I wouldn't recommend it if you only have 5 cases as it complicates the code. I'd go with the first solution as it's the simplest one.

Body:
I'm still quite new to Elixir and checking out some code in a repository and wondering if there is a way to cut down the following code snippet:

  def find(client) do
    Common.find(client, @resource)
    |> ResponseHandler.handle_response(@model_module)
  end

  def find(client, identifier) do
    Common.find(client, @resource, identifier)
    |> ResponseHandler.handle_response(@model_module)
  end

  def filter(client, filter) do
    Common.filter(client, @resource, filter)
    |> ResponseHandler.handle_response(@model_module)
  end

  def create(client, bank_transactions_map) do
    Common.create(client, @resource, bank_transactions_map)
    |> ResponseHandler.handle_response(@model_module)
  end

  def update(client, identifier, bank_transactions_map) do
    Common.update(client, @resource, identifier, bank_transactions_map)
    |> ResponseHandler.handle_response(@model_module)
  end

All the functions here pipe into the same function and it seems a little repetitive. Is there a way to set up a function in the module to take in an argument and run the .handle_response line without setting it in each function here?

Body:
You can define a new function which takes in the function name to call along with the arguments and that function will pipe into ResponseHandler.handle_response(@model_module) at the end. The following code is untested but should work:

def find(client) do
  go(:find, [client, @resource])
end

def find(client, identifier) do
  go(:find, [client, @resource, identifier])
end

...

def go(function, args) do
  apply(Common, function, args)
  |> ResponseHandler.handle_response(@model_module)
end

You can also automatically inject @resource as the second argument if you want:

def find(client) do
  go(:find, [client])
end

def find(client, identifier) do
  go(:find, [client, identifier])
end

...

def go(function, [head | tail]) do
  apply(Common, function, [head, @resource | tail])
  |> ResponseHandler.handle_response(@model_module)
end

You can reduce this even further using macros/metaprogramming but I wouldn't recommend it if you only have 5 cases as it complicates the code. I'd go with the first solution as it's the simplest one.


问:
Custom read-host dialog for PowerShell 2 CTP3 ISE
Is it possible to hook a custom dialog into the new PowerShell ISE (Integrated Scripting Environment) that replaces the existing .NET WinForms dialog. I am talking about the dialog that the Read-Host cmdlet launches to request for user input.

答:
For example, see this URL:
http://www.microsoft.com/technet/scriptcenter/resources/pstips/feb08/pstip0208.mspx

Drop the full code into Notepad.

Add the first line:
function read-host {

Add the last line:
}

Copy all the contents from Notepad.

Paste it all into your PowerShell console.

Now, if you call read-host, you're going to see a new Windows Form.

Now, if I open other windows, it remains on top, but it seems it is not the top-most because I see it over everything else, but still need to click on it to make it active.

OwnerDisplayName: Klaus

LastEditorDisplayName: Rich B

OwnerDisplayName: Marco Shaw


问:
WebDav Problem svn: PROPFIND of '/dir/dir' 301 Moved Permanently
I get the following error when attempting to export my SVN repo files from my development server which is running SVN and WebDAV to my stage server which is running on a hostgator account.

Here is the full error:

```<code>svn: PROPFIND request failed on '/svn/egr/trunk'
svn: PROPFIND of '/svn/egr/trunk': 301 Moved Permanently (http://some.no-ip.info)
</code>```

Here is the SVN command I am using:

```<code>svn export http://some.no-ip.info/svn/egr/trunk . --force --username myusername
</code>```

My WebDAV virtual host configuration looks like this:

```<code><VirtualHost *:80>
        ServerName some.no-ip.info
        DocumentRoot /var/svn/

        <Directory /var/svn/>
                Options Indexes MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>

        Alias /svn "/var/svn/"
        <Location "/svn">
           DAV On
           DavDepthInfinity on
           SVNParentPath /var/svn/
           AuthType Basic
           AuthName "SVN Login"
           AuthUserFile /etc/apache2/dav_svn.passwd
           Require valid-user
       </Location>
</VirtualHost>
</code>```

Before you ask yes I plan on using this for multiple projects that already exist within /var/svn so this is why I have attempted configuring it with SVNParentPath.  A decent amount of stuff comes back in google regarding this error, but none of the solutions seem to work for me.

答:
Ok so I finally resolved the problem.  I moved all of the SVN/WebDAv configurations out of my virtual host config leaving it looking like this:

```<code><VirtualHost *:80>
        ServerName myhost.no-ip.info
        ServerAdmin webmaster@localhost
        ServerAlias egr.localhost
        DocumentRoot /var/svn/egr/trunk
        LogLevel warn
        CustomLog /var/log/apache2/access.log combined
        ErrorLog /var/log/apache2/error.log
        Options Indexes None
</VirtualHost>
</code>```

I then went into /etc/apache2/mods-available/dav_svn.conf and configured it like so:

```<code> <Location /svn>
     DAV svn
     SVNParentPath /var/svn/
     AuthType Basic
     AuthName "SVN Repo"
     AuthUserFile /etc/subversion/passwd
     <LimitExcept GET PROPFIND OPTIONS REPORT>
        Require valid-user
     </LimitExcept>
  </Location>
</code>```

I can no access my SVN repo with a remote (as well as local svn client) and also have apache render the files through HTTP.

Body:
I get the following error when attempting to export my SVN repo files from my development server which is running SVN and WebDAV to my stage server which is running on a hostgator account.

Here is the full error:

svn: PROPFIND request failed on '/svn/egr/trunk'
svn: PROPFIND of '/svn/egr/trunk': 301 Moved Permanently (http://some.no-ip.info)

Here is the SVN command I am using:

svn export http://some.no-ip.info/svn/egr/trunk . --force --username myusername

My WebDAV virtual host configuration looks like this:

<VirtualHost *:80>
        ServerName some.no-ip.info
        DocumentRoot /var/svn/

        <Directory /var/svn/>
                Options Indexes MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>

        Alias /svn "/var/svn/"
        <Location "/svn">
           DAV On
           DavDepthInfinity on
           SVNParentPath /var/svn/
           AuthType Basic
           AuthName "SVN Login"
           AuthUserFile /etc/apache2/dav_svn.passwd
           Require valid-user
       </Location>
</VirtualHost>

Before you ask yes I plan on using this for multiple projects that already exist within /var/svn so this is why I have attempted configuring it with SVNParentPath.  A decent amount of stuff comes back in google regarding this error, but none of the solutions seem to work for me.

Body:
Ok so I finally resolved the problem.  I moved all of the SVN/WebDAv configurations out of my virtual host config leaving it looking like this:

<VirtualHost *:80>
        ServerName myhost.no-ip.info
        ServerAdmin webmaster@localhost
        ServerAlias egr.localhost
        DocumentRoot /var/svn/egr/trunk
        LogLevel warn
        CustomLog /var/log/apache2/access.log combined
        ErrorLog /var/log/apache2/error.log
        Options Indexes None
</VirtualHost>

I then went into /etc/apache2/mods-available/dav_svn.conf and configured it like so:

 <Location /svn>
     DAV svn
     SVNParentPath /var/svn/
     AuthType Basic
     AuthName "SVN Repo"
     AuthUserFile /etc/subversion/passwd
     <LimitExcept GET PROPFIND OPTIONS REPORT>
        Require valid-user
     </LimitExcept>
  </Location>

I can no access my SVN repo with a remote (as well as local svn client) and also have apache render the files through HTTP.


问:
Change React State through Event Handlers
Here my question is:

How can I change the state of my default set object using multiple select ?

Here let's say, I have states checkDevice and checkCountry, so in the below fiddle I did set all values to false.

I want to set the values of only those properties to true which are selected in the multi select dropdown.

For example: In multi select, if I just select US and UK then in my state is there a way to get something like:

```<code>checkCountry:
     {
        'US': true,
        'UK': true,
        'JP': false
      }
</code>```

class Box extends React.Component {

  constructor() {
    super();
    this.state = {
      checkDevice: {
        'iPhone 4': false,
        'iPhone 5': false,
        'iPhone 6': false,
        'iPhone 7': false,
        'iPhone 8': false,
        'iPhone X': false,
      },
      checkCountry: {
        'US': false,
        'UK': false,
        'JP': false
      }
    }
  }

  componentDidMount() {
    $(document).ready(function() {
      $('#country').material_select();
    });
    $(document).ready(function() {
      $('#device').material_select();
    });
  }

  render() {
    return (

        <form className="row">

              <select value="" multiple id="country">
                <option value="" disabled selected>Choose your option</option>
                <option value="1">US</option>
                <option value="2">UK</option>
                <option value="3">JP</option>
              </select>
              Country

              <select value="" multiple id="device">
                <option value="" disabled selected>Choose your option</option>
                <option value="1">iPhone 4</option>
                <option value="2">iPhone 5</option>
                <option value="3">iPhone 6</option>
                <option value="4">iPhone 7</option>
                <option value="5">iPhone 8</option>
                <option value="6">iPhone X</option>
              </select>
              Devices

        </form>

          ```{JSON.stringify(this.state.checkCountry,null,2)}```

          ```{JSON.stringify(this.state.checkDevice,null,2)}```

    );
  };
}

ReactDOM.render( < Box / > , document.getElementById('root'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css" rel="stylesheet" />
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>
<div id='root'></div></code>```

CODEPEN, this will give you more freedom to play with.

UPDATE:

Here in the official documentation of React, we can see how to change the complete state, but is there a way to change just the property of the existing value

For Example::

```<code>handleChange(event){
    this.setState({checkCountry["event.target.value"] === true ? false: true});
}
</code>```

But I don't think, I can get in this way. But I'm trying something like this.

Ans to questions that might help:
Updating an object with setstate in react

答:
materializecss won't trigger react onChange, so you have to bind in componentDidMount

value of select is controlled by react (virtual dom remember?), so you have to assign current value to select

where I changed your code

class Box extends React.Component {
  componentDidMount() {

    //binding onchange
    $(this.countrySelect)
      .on("change", () => {
        let checkCountry = {
          US: false,
          UK: false,
          JP: false
        };
        let val = $(this.countrySelect).val();
        console.log(val);
        val.forEach(x => {
          checkCountry[x] = true;
        });
        this.setState({
          checkCountry
        });
      })
      .material_select();
  }

  render() {
    const { checkCountry } = this.state;
    const countryVal = Object.keys(checkCountry).filter(x => checkCountry[x]);
     //assigin value
    return (<select
      ref={countrySelect => (this.countrySelect = countrySelect)}
      value={countryVal}
    />)
  }
}```

see codepen https://codepen.io/postor/pen/wPLyNq?editors=1011 for result

after you know how to do it yourself. I suggest you refer this https://github.com/react-materialize/react-materialize, this might save you some time

Body:
Here my question is:

How can I change the state of my default set object using multiple select ?

Here let's say, I have states checkDevice and checkCountry, so in the below fiddle I did set all values to false.

I want to set the values of only those properties to true which are selected in the multi select dropdown.

For example: In multi select, if I just select US and UK then in my state is there a way to get something like:

checkCountry:
     {
        'US': true,
        'UK': true,
        'JP': false
      }

class Box extends React.Component {

  constructor() {
    super();
    this.state = {
      checkDevice: {
        'iPhone 4': false,
        'iPhone 5': false,
        'iPhone 6': false,
        'iPhone 7': false,
        'iPhone 8': false,
        'iPhone X': false,
      },
      checkCountry: {
        'US': false,
        'UK': false,
        'JP': false
      }
    }
  }

  componentDidMount() {
    $(document).ready(function() {
      $('#country').material_select();
    });
    $(document).ready(function() {
      $('#device').material_select();
    });
  }

  render() {
    return (

        <form className="row">

              <select value="" multiple id="country">
                <option value="" disabled selected>Choose your option</option>
                <option value="1">US</option>
                <option value="2">UK</option>
                <option value="3">JP</option>
              </select>
              Country

              <select value="" multiple id="device">
                <option value="" disabled selected>Choose your option</option>
                <option value="1">iPhone 4</option>
                <option value="2">iPhone 5</option>
                <option value="3">iPhone 6</option>
                <option value="4">iPhone 7</option>
                <option value="5">iPhone 8</option>
                <option value="6">iPhone X</option>
              </select>
              Devices

        </form>

{JSON.stringify(this.state.checkCountry,null,2)}

{JSON.stringify(this.state.checkDevice,null,2)}

    );
  };
}

ReactDOM.render( < Box / > , document.getElementById('root'));

<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css" rel="stylesheet" />

CODEPEN, this will give you more freedom to play with.

UPDATE:

Here in the official documentation of React, we can see how to change the complete state, but is there a way to change just the property of the existing value

For Example::

handleChange(event){
    this.setState({checkCountry["event.target.value"] === true ? false: true});
}

But I don't think, I can get in this way. But I'm trying something like this.

Ans to questions that might help:
Updating an object with setstate in react

Body:
materializecss won't trigger react onChange, so you have to bind in componentDidMount

value of select is controlled by react (virtual dom remember?), so you have to assign current value to select

where I changed your code

class Box extends React.Component {
  componentDidMount() {

    //binding onchange
    $(this.countrySelect)
      .on("change", () => {
        let checkCountry = {
          US: false,
          UK: false,
          JP: false
        };
        let val = $(this.countrySelect).val();
        console.log(val);
        val.forEach(x => {
          checkCountry[x] = true;
        });
        this.setState({
          checkCountry
        });
      })
      .material_select();
  }

  render() {
    const { checkCountry } = this.state;
    const countryVal = Object.keys(checkCountry).filter(x => checkCountry[x]);
     //assigin value
    return (<select
      ref={countrySelect => (this.countrySelect = countrySelect)}
      value={countryVal}
    />)
  }
}

see codepen https://codepen.io/postor/pen/wPLyNq?editors=1011 for result

after you know how to do it yourself. I suggest you refer this https://github.com/react-materialize/react-materialize, this might save you some time


问:
validate user input and loop until correct
I have looked on here for an idea in order to loop the user's invalid input and I haven't found one.

Ok, I know how to loop the first_number and second_number together but I am a bit confused on how to loop the separately if need be. So if the user inputs a bad second_number and loops that instead of the whole thing again.

I've attached the part I need help with (yes this is a school assignment):

```<code>def get_numbers():
first_number = 0.0
second_number = 0.0

while True:
    try:
        first_number = float(input("Please enter the first number: "))
        second_number = float(input("Please enter the second number: "))
    except ValueError:
        print("Not a valid input, please try again.")
        continue

    return first_number, second_number
</code>```

答:
First, you want to use two loops, one for each number, and break if the input is valid instead of continuing if it's invalid. Then you need to move the return statement to immediately following the second loop.

By the way, you can leave out the initial assignments to first_number and second_number (commented out below). Assigning them to float(input(...)) is enough.

```<code>def get_numbers():
    #first_number = 0.0
    #second_number = 0.0

    while True:
        try:
            first_number = float(input("Please enter the first number: "))
            break
        except ValueError:
            print("Not a valid input, please try again.")

    while True:
        try:
            second_number = float(input("Please enter the second number: "))
            break
        except ValueError:
            print("Not a valid input, please try again.")

    return first_number, second_number
</code>```

Body:
I have looked on here for an idea in order to loop the user's invalid input and I haven't found one.

Ok, I know how to loop the first_number and second_number together but I am a bit confused on how to loop the separately if need be. So if the user inputs a bad second_number and loops that instead of the whole thing again.

I've attached the part I need help with (yes this is a school assignment):

def get_numbers():
first_number = 0.0
second_number = 0.0

while True:
    try:
        first_number = float(input("Please enter the first number: "))
        second_number = float(input("Please enter the second number: "))
    except ValueError:
        print("Not a valid input, please try again.")
        continue

    return first_number, second_number

Body:
First, you want to use two loops, one for each number, and break if the input is valid instead of continuing if it's invalid. Then you need to move the return statement to immediately following the second loop.

By the way, you can leave out the initial assignments to first_number and second_number (commented out below). Assigning them to float(input(...)) is enough.

def get_numbers():
    #first_number = 0.0
    #second_number = 0.0

    while True:
        try:
            first_number = float(input("Please enter the first number: "))
            break
        except ValueError:
            print("Not a valid input, please try again.")

    while True:
        try:
            second_number = float(input("Please enter the second number: "))
            break
        except ValueError:
            print("Not a valid input, please try again.")

    return first_number, second_number


问:
Creating new objects for every NULL index of an object pointer array

I am trying to write a simple function that fills an array of object pointers by detecting NULL indexes and creating new objects.

```<code>Wire *wireArray[MAX_WIRES];//The array is of class "Wire" and returns a pointer to a wire object.

Wire *getWirePtrFromWireNum(int num); //the function gets the index to the array and returns a NULL if empty and the pointer if it is not NULL.
</code>```

In the following if-statement, I tried to pass the index to the function and create a new Wire object if the array at that number is NULL.

```<code>if (getWirePtrFromWireNum(wirenum) == NULL) {

                Wire newWire;
                wireArray[wirenum] = &newWire;

            }
</code>```

The function for the getWirePtrFromWireNum simply checks for the NULL index and returns the pointer if it is occupied.

```<code>Wire * Circuit::getWirePtrFromWireNum(int num)
{
    if (wireArray[num] == NULL) {

        return NULL;
    }

    else {

        return wireArray[num];

    }

}
</code>```

When I test it with a several inputs, it does not enter first if-statement at all. I did not feel the need to initialize the pointer array to NULL, but I feel like it should still be catching that the first indexes should be empty. The code does not return any errors, but the function does not seem to be doing what it should be. Where could my error be coming from?

EDIT:

```<code>for (int i = 0; i < MAX_WIRE; i++) {

    wireArray[i] == NULL;
}
</code>```

Fixed Function:

```<code>Wire * Circuit::getWirePtrFromWireNum(int num)
{
    if (wireArray[num] == NULL) {

        wireArray[num] = new Wire;
        return wireArray[num];

    }

    return wireArray[num];

}
</code>```

答:
```<code>if (wireArray[num] == NULL) {

    return NULL;
}

else {

    return wireArray[num];

}
</code>```

These statements don't do what you think that they do. You check wireArray == NULL, but it isn't set to NULL by default. In fact, the entire check is redundant because it can be simplified to return wireArray[num]. You need to initialize all of the elements in the array to NULL; their default values are whatever bits were left over from when the memory location was last used and are not defined.

```<code>if (getWirePtrFromWireNum(wirenum) == NULL) {

            Wire newWire;
            wireArray[wirenum] = &newWire;

}
</code>```

You have a dangling pointer here. newWire is destroyed after the if statement.

Body:
I am trying to write a simple function that fills an array of object pointers by detecting NULL indexes and creating new objects.

Wire *wireArray[MAX_WIRES];//The array is of class "Wire" and returns a pointer to a wire object.

Wire *getWirePtrFromWireNum(int num); //the function gets the index to the array and returns a NULL if empty and the pointer if it is not NULL.

In the following if-statement, I tried to pass the index to the function and create a new Wire object if the array at that number is NULL.

if (getWirePtrFromWireNum(wirenum) == NULL) {

                Wire newWire;
                wireArray[wirenum] = &newWire;

            }

The function for the getWirePtrFromWireNum simply checks for the NULL index and returns the pointer if it is occupied.

Wire * Circuit::getWirePtrFromWireNum(int num)
{
    if (wireArray[num] == NULL) {

        return NULL;
    }

    else {

        return wireArray[num];

    }

}

When I test it with a several inputs, it does not enter first if-statement at all. I did not feel the need to initialize the pointer array to NULL, but I feel like it should still be catching that the first indexes should be empty. The code does not return any errors, but the function does not seem to be doing what it should be. Where could my error be coming from?

EDIT:

for (int i = 0; i < MAX_WIRE; i++) {

    wireArray[i] == NULL;
}

Fixed Function:

Wire * Circuit::getWirePtrFromWireNum(int num)
{
    if (wireArray[num] == NULL) {

        wireArray[num] = new Wire;
        return wireArray[num];

    }

    return wireArray[num];

}

Body:
if (wireArray[num] == NULL) {

    return NULL;
}

else {

    return wireArray[num];

}

These statements don't do what you think that they do. You check wireArray == NULL, but it isn't set to NULL by default. In fact, the entire check is redundant because it can be simplified to return wireArray[num]. You need to initialize all of the elements in the array to NULL; their default values are whatever bits were left over from when the memory location was last used and are not defined.

if (getWirePtrFromWireNum(wirenum) == NULL) {

            Wire newWire;
            wireArray[wirenum] = &newWire;

}

You have a dangling pointer here. newWire is destroyed after the if statement.


问:
Couldn't retrieve data from my database
I have a problem in my system. Last time i checked, my system was working fine but now i get this error and it seems like my system cannot retrieve data from my database. I am getting a Token mismatch exception even though i have csrf token in all of my forms. Somebody Help.</p>

答:
1- You might missed the crsf token in your form please check it if missed
add this to your form <input type="hidden" name="_token" value="{{ csrf_token() }}">
2- If you have it already you should clear your laravel cache and view cache.
 - php artisan clear:cache
 - php artisan view:clear
3- One more think please screenshot your error too it is easy to look at.

Title: Couldn't retrieve data from my database


问:
Getting Trying to get property of non-object error

Trying to display values from database for a specific id using json and php

When I do var dump all correct values are displayed

```<code>function getItemByID($id) {

    //Connect to database and server
    include ("connect.php") ;

    if (!$connect) {
    die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "SELECT * FROM items WHERE id ='".$id."'";
    $res1 = mysqli_query($connect, $sql);

    $rows = mysqli_fetch_assoc($res1);

    $itemtxt = '[{"id" : '.$rows['id'].',' ;
    $itemtxt = $itemtxt.'"item" : '.$rows['item'].',' ;
    $itemtxt = $itemtxt.'"image" : '.$rows['image'].',' ;
    $itemtxt = $itemtxt.'"descr" : '.$rows['descr'].'}] ,' ;

    $itemtxt = substr($itemtxt, 0, -2) ;

    var_dump($itemtxt);

    return $itemtxt;

}
</code>```

This is where the error gets displayed from on line 10,11,12,13

```<code><?php
    $id = $_GET['id'];

    include("library.php");

    $itemtxt = getItemByID($id);
    $itemjson = json_decode($itemtxt);

    echo $itemjson -> id;
    echo $itemjson -> item;
    echo $itemjson -> image;
    echo $itemjson -> descr;

?>
</code>```

Trying to get this data to display on this page but getting "Trying to get property of non object" error.

答:
The string you are creating is a JSON array. For which your json_decode is returning an array. Remove the [ from the begining and end of you string generation and it should work. So change the below :

```<code>$itemtxt = '[{"id" : '.$rows['id'].',' ;
$itemtxt = $itemtxt.'"item" : '.$rows['item'].',' ;
$itemtxt = $itemtxt.'"image" : '.$rows['image'].',' ;
$itemtxt = $itemtxt.'"descr" : '.$rows['descr'].'}] ,' ;
</code>```

to

```<code>$itemtxt = '{"id" : '.$rows['id'].',' ;
$itemtxt = $itemtxt.'"item" : '.$rows['item'].',' ;
$itemtxt = $itemtxt.'"image" : '.$rows['image'].',' ;
$itemtxt = $itemtxt.'"descr" : '.$rows['descr'].'} ,' ;
</code>```

Body:
Trying to display values from database for a specific id using json and php

When I do var dump all correct values are displayed

function getItemByID($id) {

    //Connect to database and server
    include ("connect.php") ;

    if (!$connect) {
    die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "SELECT * FROM items WHERE id ='".$id."'";
    $res1 = mysqli_query($connect, $sql);

    $rows = mysqli_fetch_assoc($res1);

    $itemtxt = '[{"id" : '.$rows['id'].',' ;
    $itemtxt = $itemtxt.'"item" : '.$rows['item'].',' ;
    $itemtxt = $itemtxt.'"image" : '.$rows['image'].',' ;
    $itemtxt = $itemtxt.'"descr" : '.$rows['descr'].'}] ,' ;

    $itemtxt = substr($itemtxt, 0, -2) ;

    var_dump($itemtxt);

    return $itemtxt;

}

This is where the error gets displayed from on line 10,11,12,13

<?php
    $id = $_GET['id'];

    include("library.php");

    $itemtxt = getItemByID($id);
    $itemjson = json_decode($itemtxt);

    echo $itemjson -> id;
    echo $itemjson -> item;
    echo $itemjson -> image;
    echo $itemjson -> descr;

?>

Trying to get this data to display on this page but getting "Trying to get property of non object" error.

Body:
The string you are creating is a JSON array. For which your json_decode is returning an array. Remove the [ from the begining and end of you string generation and it should work. So change the below :

$itemtxt = '[{"id" : '.$rows['id'].',' ;
$itemtxt = $itemtxt.'"item" : '.$rows['item'].',' ;
$itemtxt = $itemtxt.'"image" : '.$rows['image'].',' ;
$itemtxt = $itemtxt.'"descr" : '.$rows['descr'].'}] ,' ;

to

$itemtxt = '{"id" : '.$rows['id'].',' ;
$itemtxt = $itemtxt.'"item" : '.$rows['item'].',' ;
$itemtxt = $itemtxt.'"image" : '.$rows['image'].',' ;
$itemtxt = $itemtxt.'"descr" : '.$rows['descr'].'} ,' ;


问:
Access to the docker app from a virtual machine
I have a dockerized app (hosted by Apache) on my local machine. I would like to test the app on IE11 and Edge. So I installed a virtual box to run the app on IE and Edge on the virtual box Window10.

However, it looks like I cannot access to the app's on the browser. Anybody who know how to do it?

Thanks!

答:
Two main things to check.

Make sure that your container exports a port to its host (eg docker run -p 80:8080 ...). This assumes that your app is listening to port 8080. Change it as needed.

Add a network interface to your Virtual Box. If you're on a home wifi network for instance, just add a Network Interface for that network. That will allow your Virtual Box VM to be accessible from your wifi network.

Beside that, you'll really need to put more information like the command line instructions you use to start your app (or docker-compose file), the result of ifconfig from inside your host, etc.


问:
MSMQ - Send copies of messages received
Is there any way to configure an MSMQ queue to send copies of all messages it receives to another MSMQ queue? I have a memory leak on a production application that services a queue.  I have a test version (that hopefully fixes the memory leak) on a test server, that services a test queue.  I want to deluge the test version with the production stream of messages, to ensure that the memory leak has been fixed.  After I am done testing, I would like to shut off this "message forwarding"</p>

答: No. MSMQ is a protocol for delivering messages. You would need an application to read the delivered messages and send new copies to a different queue. </p>

Title: MSMQ - Send copies of messages received


问:
Share variables between different jupyter notebooks
I have two different Jupyter notebooks, running on the same server. What I would like to do is to access some (only a few of them) of the variables of one notebook through the other notebook (I have to compare if the two different versions of the algorithm give the same results, basically). Is there a way to do this?

Thanks

答:
Between 2 jupyter notebook, you can use the %store command.

In the first jupyter notebook:

```<code>data = 'string or data-table to pass'
%store data
del data # This will DELETE the data from the memory of the first notebook
</code>```

In the second jupyter notebook:

```<code>%store -r data
data
</code>```

You can find more information at here.

Body:
Between 2 jupyter notebook, you can use the %store command.

In the first jupyter notebook:

data = 'string or data-table to pass'
%store data
del data # This will DELETE the data from the memory of the first notebook

In the second jupyter notebook:

%store -r data
data

You can find more information at here.


问:
How to apply exponential moving average decay for variables in pytorch?
I am reading following paper. And it uses EMA decay for variables.

Bidirectional Attention Flow for Machine Comprehension

During training, the moving averages of all weights of the model are
  maintained with the exponential decay rate of 0.999.

They use TensorFlow and I found the related code of EMA.

https://github.com/allenai/bi-att-flow/blob/master/basic/model.py#L229

In PyTorch, how do I apply EMA to Variables?

答:
Moving average is the key concept of momentum in gradient descent.

In PyTorch document you can find:

optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)

Change the parameter momentum to the value you want.