问:
How to select
 inside

Assume I have html structure as

```<code>ul
  li //this one
    ul
      li
      li
      li
  li //this one
</code>```

I don't want to get all li's.
As I commented I just want to get first segment li's. How can I select them?

```<code>document.querySelectorAll("ul > li");
</code>```

returns all li's.

edit: actually this is just a snippet of the tree.

I can't modify the structure as adding class or id. I'm looking for an answer to get the list of first layer lis

答:
You need to select all the li items where the grandparent is not another list item.

```<code>:not(li) > * > li {}
</code>```

This will only work if you don't have extra elements in the markup.

For example it would fail with:

```<code><ul>
  <li>
    <div>
      <ul>
        <li>
</code>```

A slower, but more reliable, approach would be to get all the list items and then filter out ones which had list item ancestors.

var lis = document.getElementsByTagName('li');
var lis_without_li_ancestors = [];
for (var i = 0; i < lis.length; i++) {
  var element = lis[i];
  if (!has_li_ancestor(element)) {
    lis_without_li_ancestors.push(element);
  }
}

console.log(lis_without_li_ancestors);

function has_li_ancestor(element) {
  var parent = element.parentNode;
  if (parent.tagName.toLowerCase() === "body") {
    return false;
  } else if (parent.tagName.toLowerCase() === "li") {
    return true;
  } else {
    return has_li_ancestor(parent);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>
    <ul>
      <li>...
    </ul>
</ul></code>```

Title: How to select <li> inside <ul>

Body:
Assume I have html structure as

ul
  li //this one
    ul
      li
      li
      li
  li //this one

I don't want to get all li's.
As I commented I just want to get first segment li's. How can I select them?

document.querySelectorAll("ul > li");

returns all li's.

edit: actually this is just a snippet of the tree.

I can't modify the structure as adding class or id. I'm looking for an answer to get the list of first layer lis

Body:
You need to select all the li items where the grandparent is not another list item.

:not(li) > * > li {}

This will only work if you don't have extra elements in the markup.

For example it would fail with:

<ul>
  <li>
    <div>
      <ul>
        <li>

A slower, but more reliable, approach would be to get all the list items and then filter out ones which had list item ancestors.

var lis = document.getElementsByTagName('li');
var lis_without_li_ancestors = [];
for (var i = 0; i < lis.length; i++) {
  var element = lis[i];
  if (!has_li_ancestor(element)) {
    lis_without_li_ancestors.push(element);
  }
}

console.log(lis_without_li_ancestors);

function has_li_ancestor(element) {
  var parent = element.parentNode;
  if (parent.tagName.toLowerCase() === "body") {
    return false;
  } else if (parent.tagName.toLowerCase() === "li") {
    return true;
  } else {
    return has_li_ancestor(parent);
  }
}

<ul>
  <li>
    <ul>
      <li>...
    </ul>
</ul>


来源: stackexchange

问:
Looking for an Object Oriented JMeter example
I'm looking to abstract the sequence of REST calls for complicated behaviors in my company's app into a series of classes that are instantiated as needed and the methods would effectively create the sequence of HTTP request calls.  It's my hope that doing this would make the tests more compact and readable (as well as providing more reusable code).  I would need to utilize the StandardJmeterEngine and export the test to JMX format after the HashTree test plan is created.

To cut on development time, I'm hoping to find a nice example of this; I'm sure someone's done it, but I've yet to stumble onto it.

答:
If you are looking into the way of programmatic creation JMeter test take a look into the following sources:

JMeter API

How to Write a plugin for JMeter

Five Ways To Launch a JMeter Test without Using the JMeter GUI

If you are looking for an example project you can check out jmeter-from-code solution which demonstrates creating a JMeter Test Plan programmatically, storing it into a .jmx script file, running it and getting the .jtl results file.

ContentLicense: CC BY-SA 3.0


问:
Convert Alamofire request to synchronous?
How can I convert my current Alamofire request into a synchronous request? Will this stop all other execution until the request completes?

MY current function is as follows:

```<code>func updateLabels() {
    Alamofire.request(apiUrl).responseJSON { response in
        if let data = response.result.value {
            var rawJson = JSON(data)
            var json = rawJson[0]

            var totalViews = json["totalViews"].stringValue
            var uniqueUsers = json["uniqueUsers"].stringValue

            print(totalViews)
            print(uniqueUsers)

            self.totalViews.setText(totalViews)
            self.uniqueUsers.setText(uniqueUsers)
        }
    }
}
</code>```

I'm using Alamofire_Synchronous. I'm not super familiar with Alamofire so any help would be awesome, thanks!

答:
You can use this extension and call sync request to Alamofire lib.

```<code>extension Alamofire.Manager {

    func syncRequest(URLRequest: URLRequestConvertible) -> Response<AnyObject, NSError> {

        var outResponse: Response<AnyObject, NSError>!
        let semaphore: dispatch_semaphore_t! = dispatch_semaphore_create(0)

        self.request(URLRequest).responseJSON { (response: Response<AnyObject, NSError>) -> Void in

            outResponse = response
            dispatch_semaphore_signal(semaphore)
        }
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

        return outResponse
    }
}
</code>```

Body:
How can I convert my current Alamofire request into a synchronous request? Will this stop all other execution until the request completes?

MY current function is as follows:

func updateLabels() {
    Alamofire.request(apiUrl).responseJSON { response in
        if let data = response.result.value {
            var rawJson = JSON(data)
            var json = rawJson[0]

            var totalViews = json["totalViews"].stringValue
            var uniqueUsers = json["uniqueUsers"].stringValue

            print(totalViews)
            print(uniqueUsers)

            self.totalViews.setText(totalViews)
            self.uniqueUsers.setText(uniqueUsers)
        }
    }
}

I'm using Alamofire_Synchronous. I'm not super familiar with Alamofire so any help would be awesome, thanks!

Body:
You can use this extension and call sync request to Alamofire lib.

extension Alamofire.Manager {

    func syncRequest(URLRequest: URLRequestConvertible) -> Response<AnyObject, NSError> {

        var outResponse: Response<AnyObject, NSError>!
        let semaphore: dispatch_semaphore_t! = dispatch_semaphore_create(0)

        self.request(URLRequest).responseJSON { (response: Response<AnyObject, NSError>) -> Void in

            outResponse = response
            dispatch_semaphore_signal(semaphore)
        }
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

        return outResponse
    }
}


问:
Curl POST command to pass json data to spring-boot app not working
Have looked at other related posts but nothing seemed to work.

Basically I'm trying to figure out how to pass data to my restful spring-boot app.

Here is the curl command I'm using:

```<code>$ curl -iX POST -H 'Content-Type: application/json' -d @args.json http://localhost:8080/myapp/dummyApi
</code>```

With args.json contains:

file: args.json:

```<code>{
  "arg1": "hello",
  "arg2": 10,
  "arg3": {
    "a": "1",
    "b": "2"
  }
}
</code>```

The api is defined in MyController.java as such:

file: MyController.java

```<code>@RestController
@RequestMapping("/myapp")
public class MyController {

//...

static class DummyRet {
    private String foo;
    public DummyRet(String f) {
        foo = f;
    }
    public String getFoo() {
        return foo;
    }
    public void setFoo(String foo) {
        this.foo = foo;
    }
}

@RequestMapping(value="/dummyApi", method=RequestMethod.POST)
public DummyRet dummyApi(@RequestParam(value = "arg1", required = false, defaultValue = "") String arg1,
                               @RequestParam(value = "arg2", required = false, defaultValue = "") Long arg2,
                               @RequestParam(value = "arg3", required = false) Map<String, String> arg3) {
    LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    LOGGER.info("Arguments received:");
    LOGGER.info("arg1: " + arg1);
    LOGGER.info("arg2: " + arg2);
    LOGGER.info("arg3: " + arg3);
    LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    return new DummyRet("foo");
}

//...
}
</code>```

The return of the curl command is 200 success (since non of the arguments is required) but the values of args are not reaching over to dummyApi method

```<code>$ curl -iX POST -H 'Content-Type: application/json' -d @args.json http://localhost:8080/myapp/dummyApi
HTTP/1.1 200
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sun, 04 Jun 2017 15:37:42 GMT

{"foo":"foo"}
</code>```

The server console looks like this:

```<code>2017-06-04 18:17:56.818 DEBUG 32258 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing POST request for [/myapp/dummyApi]
2017-06-04 18:17:56.818 DEBUG 32258 --- [nio-8080-exec-7] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /myapp/dummyApi
2017-06-04 18:17:56.818 DEBUG 32258 --- [nio-8080-exec-7] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public com.xx.controllers.MyController$DummyRet com.xx.controllers.MyController.dummyApi(java.lang.String,java.lang.Long,java.util.Map<java.lang.String, java.lang.String>)]
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : Arguments received:
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : arg1:
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : arg2: null
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : arg3: null
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
2017-06-04 18:17:56.819 DEBUG 32258 --- [nio-8080-exec-7] m.m.a.RequestResponseBodyMethodProcessor : Written [com.xx.controllers.MyController$DummyRet@c35d46f] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@301ec38b]
2017-06-04 18:17:56.819 DEBUG 32258 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-06-04 18:17:56.819 DEBUG 32258 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : Successfully completed request
</code>```

I hope I haven't left out any of the important details, but please let me know if anything is missing.

答:
Refer below sample,</p>

```<code>curl -H "Content-Type: application/json" --data @body.json
http://localhost:8080/ui/webapp/conf
</code>```

Body:
Have looked at other related posts but nothing seemed to work.

Basically I'm trying to figure out how to pass data to my restful spring-boot app.

Here is the curl command I'm using:

$ curl -iX POST -H 'Content-Type: application/json' -d @args.json http://localhost:8080/myapp/dummyApi

With args.json contains:

file: args.json:

{
  "arg1": "hello",
  "arg2": 10,
  "arg3": {
    "a": "1",
    "b": "2"
  }
}

The api is defined in MyController.java as such:

file: MyController.java

@RestController
@RequestMapping("/myapp")
public class MyController {

//...

static class DummyRet {
    private String foo;
    public DummyRet(String f) {
        foo = f;
    }
    public String getFoo() {
        return foo;
    }
    public void setFoo(String foo) {
        this.foo = foo;
    }
}

@RequestMapping(value="/dummyApi", method=RequestMethod.POST)
public DummyRet dummyApi(@RequestParam(value = "arg1", required = false, defaultValue = "") String arg1,
                               @RequestParam(value = "arg2", required = false, defaultValue = "") Long arg2,
                               @RequestParam(value = "arg3", required = false) Map<String, String> arg3) {
    LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    LOGGER.info("Arguments received:");
    LOGGER.info("arg1: " + arg1);
    LOGGER.info("arg2: " + arg2);
    LOGGER.info("arg3: " + arg3);
    LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    return new DummyRet("foo");
}

//...
}

The return of the curl command is 200 success (since non of the arguments is required) but the values of args are not reaching over to dummyApi method

$ curl -iX POST -H 'Content-Type: application/json' -d @args.json http://localhost:8080/myapp/dummyApi
HTTP/1.1 200
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sun, 04 Jun 2017 15:37:42 GMT

{"foo":"foo"}

The server console looks like this:

2017-06-04 18:17:56.818 DEBUG 32258 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing POST request for [/myapp/dummyApi]
2017-06-04 18:17:56.818 DEBUG 32258 --- [nio-8080-exec-7] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /myapp/dummyApi
2017-06-04 18:17:56.818 DEBUG 32258 --- [nio-8080-exec-7] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public com.xx.controllers.MyController$DummyRet com.xx.controllers.MyController.dummyApi(java.lang.String,java.lang.Long,java.util.Map<java.lang.String, java.lang.String>)]
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : Arguments received:
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : arg1:
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : arg2: null
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : arg3: null
2017-06-04 18:17:56.819  INFO 32258 --- [nio-8080-exec-7] c.p.controllers.MyController       : >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
2017-06-04 18:17:56.819 DEBUG 32258 --- [nio-8080-exec-7] m.m.a.RequestResponseBodyMethodProcessor : Written [com.xx.controllers.MyController$DummyRet@c35d46f] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@301ec38b]
2017-06-04 18:17:56.819 DEBUG 32258 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-06-04 18:17:56.819 DEBUG 32258 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : Successfully completed request

I hope I haven't left out any of the important details, but please let me know if anything is missing.

Body:
Refer below sample,

curl -H "Content-Type: application/json" --data @body.json
http://localhost:8080/ui/webapp/conf


问:
Multi-threaded Queue in Linux C
I'm writing a simple program that reads urls from a text file, and checks the validity of them using multi threaded programming. I used mutexes and condition variables to synchronize my threads but my app still crashes and after some debugging sessions I decided to get some help :)

The input of the file is a text file containing urls like:
http://www.youtube.com/
http://www.facebook.com/

And the output should be the aggregated result of the curl request on each url (whether it returns OK, UNKOWN or ERROR)

This is my code:

```<code>/*
 * ex3.c
 */

#define _GNU_SOURCE

#include <curl/curl.h>
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#define REQUEST_TIMEOUT_SECONDS 2L

#define URL_OK 0
#define URL_ERROR 1
#define URL_UNKNOWN 2

#define QUEUE_SIZE 32

#define handle_error_en(en, msg) \
        do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)

typedef struct {
    int ok, error, unknown;
} UrlStatus;

typedef struct {
    void **array;
    int size;
    int capacity;
    int head;
    int tail;
    pthread_mutex_t mutex;
    pthread_cond_t cv_empty; /* get notified when the queue is not full */
    pthread_cond_t cv_full; /* get notified when the queue is not empty */
} Queue;

void queue_init(Queue *queue, int capacity) {
    /*
     * Initializes the queue with the specified capacity.
     * This function should allocate the internal array, initialize its properties
     * and also initialize its mutex and condition variables.
     */
    queue->array = (void**)malloc(sizeof(void*) * capacity);
    if (queue->array == NULL) {
        perror("unable to allocate memory");
        exit(EXIT_FAILURE);
    }
    queue->capacity = capacity;
    queue->size = 0;
    queue->head = 0;
    queue->tail = 0;
    pthread_mutex_init(&(queue->mutex), NULL);
    pthread_cond_init(&(queue->cv_empty), NULL);
    pthread_cond_init(&(queue->cv_full), NULL);
}

void enqueue(Queue *queue, void *data) {
    /*
     * Enqueue an object to the queue.
     *
     * TODO:
     * 1. This function should be synchronized on the queue's mutex
     * 2. If the queue is full, it should wait until it is not full
     *      (i.e. cv_empty)
     * 3. Add an element to the tail of the queue, and update the tail & size
     *      parameters
     * 4. Signal that the queue is not empty (i.e. cv_full)
     */

    pthread_mutex_lock(&(queue->mutex));
    while (queue->size >= QUEUE_SIZE) {
        pthread_cond_wait(&(queue->cv_empty), &(queue->mutex));
    }

    if(queue->size == 0) {
        queue->head = 0;
    }

    queue->array[queue->tail] = data;
    queue->size++;

    queue->tail++;
    pthread_cond_signal(&(queue->cv_full));
    pthread_mutex_unlock(&(queue->mutex));

}

void *dequeue(Queue *queue) {
    /*
     * Dequeue an object from the queue.
     *
     * TODO:
     * 1. This function should be synchronized on the queue's mutex
     * 2. If the queue is empty, it should wait until it is not empty (i.e. cv_full)
     * 3. Read the head element, and update the head & size parameters
     * 4. Signal that the queue is not full (i.e. cv_empty)
     * 5. Return the dequeued item
     */
    void *data;

    pthread_mutex_lock(&(queue->mutex));
    while (queue->size <= 0) {
        pthread_cond_wait(&(queue->cv_full), &(queue->mutex));
    }

    queue->head++;
    data = queue->array[queue->head];
    queue->size--;

    pthread_cond_signal(&(queue->cv_empty));
    pthread_mutex_unlock(&(queue->mutex));

    return data;
}

void queue_destroy(Queue *queue) {
    /*
     * Free the queue memory and destroy the mutex and the condition variables.
     */
    int ret;

    free(queue->array);

    ret = pthread_mutex_destroy(&(queue->mutex));
    if (ret != 0) {
        handle_error_en(ret, "unable to destroy mutex");
    }
    ret = pthread_cond_destroy(&(queue->cv_empty));
    if (ret != 0) {
        handle_error_en(ret, "unable to destroy cv_empty condition variable");
    }
    ret = pthread_cond_destroy(&(queue->cv_full));
    if (ret != 0) {
        handle_error_en(ret, "unable to destroy cv_full condition variable");
    }
}

void usage() {
    fprintf(stderr, "usage:\n\t./ex3 FILENAME NUMBER_OF_THREADS\n");
    exit(EXIT_FAILURE);
}

int count = 0;
int check_url(const char *url) {
    CURL *curl;
    CURLcode res;
    long response_code = 0L;
    int http_status = URL_UNKNOWN;

    curl = curl_easy_init();

    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, REQUEST_TIMEOUT_SECONDS);
        curl_easy_setopt(curl, CURLOPT_NOBODY, 1L); /* do a HEAD request */

        res = curl_easy_perform(curl);
        if(res == CURLE_OK) {
            res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);

            if (res == CURLE_OK &&
                    response_code >= 200 &&
                    response_code < 400) {
                http_status = URL_OK;
            } else {
                http_status = URL_ERROR;
            }
        }
        curl_easy_cleanup(curl);
    }

    return http_status;
}

typedef struct {
    Queue *url_queue;
    Queue *result_queue;
} WorkerArguments;

void *worker(void *args) {
    /*
     * TODO:
     * 1. Initialize a UrlStatus (allocate memory using malloc, and zero it
     *      using memset)
     * 2. Dequeue URL from url_queue, run check_url on it, and update results
     *    (don't forget to free() the url)
     * 3. After dequeuing a NULL value:
     *      Enqueue results to result_queue and return
     */

    WorkerArguments *worker_args = (WorkerArguments *)args;
    UrlStatus *results = NULL;
    char *url;

    results = malloc(sizeof(UrlStatus));
    if(results == NULL) {
        perror("Could not allocate memory");
        exit(-1);
    }

    memset(results, 0, sizeof(UrlStatus));

    while((url = (char *)dequeue(worker_args->url_queue)) != NULL) {
        switch(check_url(url)) {
            case URL_OK:
                results->ok++;
            break;
            case URL_UNKNOWN:
                results->unknown++;
            break;
            case URL_ERROR:
                results->error++;
            break;
        }
        /*free(url);*/
    }
    enqueue(worker_args->result_queue, results);
    return NULL;
}

typedef struct {
    const char *filename;
    Queue *url_queue;
} FileReaderArguments;

void *file_reader(void *args) {
    /*
     * TODO:
     * 1. Open filename (use fopen, check for errors)
     * 2. Use getline() to read lines (i.e. URLs) from the file (use errno to check for errors)
     * 3. Copy each url to the heap (use malloc and strncpy)
     * 4. Enqueue the URL to url_queue
     * 5. Don't forget to free the line variable, and close the file (and check for errors!)
     */

    FileReaderArguments *file_reader_args = (FileReaderArguments *)args;
    FILE *toplist_file;
    char *line = NULL;
    char *url = NULL;
    size_t len = 0;
    ssize_t read = 0;

    toplist_file = fopen(file_reader_args->filename, "r");

        if (toplist_file == NULL) {
            exit(EXIT_FAILURE);
        }

    while ((read = getline(&line, &len, toplist_file)) != -1) {
        if (read == -1) {
            perror("error reading file");
        }
        if(read == 1) continue; /*empty line*/
        url = malloc(read);
        if(url == NULL) {
            perror("Could not allocate memory");
        }
        line[read-1] = '\0'; /* null-terminate the URL */
        strncpy(url, line, read);
        enqueue(file_reader_args->url_queue, url);
    }
    fclose(toplist_file);
    return NULL;
}

typedef struct {
    int number_of_threads;
    Queue *url_queue;
    Queue *result_queue;
} CollectorArguments;

void *collector(void *args) {
    /*
     * TODO:
     * 1. Enqueue number_of_threads NULLs to the url_queue
     * 2. Dequeue and aggregate number_of_threads thread_results
     *      from result_queue into results (don't forget to free() thread_results)
     * 3. Print aggregated results to the screen
     */

    CollectorArguments *collector_args = (CollectorArguments *)args;
    UrlStatus results = {0};
    UrlStatus *thread_results;
    int i;

    for(i= 0; i < collector_args->number_of_threads; i++) {
    }

    for(i= 0; i < collector_args->number_of_threads; i++) {
        thread_results = dequeue(collector_args->result_queue);
        results.ok += thread_results->ok;
        results.error += thread_results->error;
        results.unknown += thread_results->unknown;
        /* free(thread_results);*/
    }

    printf("%d OK, %d Error, %d Unknown\n",
            results.ok,
            results.error,
            results.unknown);
    return NULL;
}

void parallel_checker(const char *filename, int number_of_threads) {
    /*
     * TODO:
     * 1. Initialize a Queue for URLs, a Queue for results (use QUEUE_SIZE)
     * 2. Start number_of_threads threads running worker()
     * 3. Start a thread running file_reader(), and join it
     * 4. Start a thread running collector(), and join it
     * 5. Join all worker threads
     * 6. Destroy both queues
     */
    Queue url_queue, result_queue;
    WorkerArguments worker_arguments = {0};
    FileReaderArguments file_reader_arguments = {0};
    CollectorArguments collector_arguments = {0};
    pthread_t *worker_threads;
    pthread_t file_reader_thread, collector_thread;
    int i;
    int err;

    queue_init(&url_queue, QUEUE_SIZE);
    queue_init(&result_queue, QUEUE_SIZE);

    worker_arguments.url_queue = &url_queue;
    worker_arguments.result_queue = &result_queue;

    file_reader_arguments.filename = filename;
    file_reader_arguments.url_queue = &url_queue;

    collector_arguments.url_queue = &url_queue;
    collector_arguments.result_queue = &result_queue;
    collector_arguments.number_of_threads = number_of_threads;

    worker_threads = (pthread_t *) malloc(sizeof(pthread_t) * number_of_threads);
    if (worker_threads == NULL) {
        perror("unable to allocate memory");
        return;
    }
    curl_global_init(CURL_GLOBAL_ALL); /* init libcurl before starting threads */

    for(i=0; i<number_of_threads; i++) {
        err = pthread_create(&(worker_threads[i]), NULL, &worker, &worker_arguments);
        if (err != 0) {
            fprintf(stderr, "can't create thread :[%s]\n", strerror(err));
        }
    }

    err = pthread_create(&file_reader_thread, NULL, &file_reader, &file_reader_arguments);
    if (err != 0) {
        fprintf(stderr, "can't create thread :[%s]\n", strerror(err));
    }

    err = pthread_join(file_reader_thread, NULL);
    if (err != 0) {
        fprintf(stderr, "can't join thread :[%s]\n", strerror(err));
    }

    err = pthread_create(&collector_thread, NULL, &collector, &collector_arguments);
    if (err != 0) {
        fprintf(stderr, "can't create thread :[%s]\n", strerror(err));
    }

    err = pthread_join(collector_thread, NULL);
    if (err != 0) {
        fprintf(stderr, "can't join thread :[%s]\n", strerror(err));
    }

    for(i=0; i<number_of_threads; i++) {
        err = pthread_join(worker_threads[i], NULL);

        if (err != 0) {
            fprintf(stderr, "can't join thread :[%s]\n", strerror(err));
        }
    }

    queue_destroy(&url_queue);
    queue_destroy(&result_queue);
    free(worker_threads);
}

int main(int argc, char **argv) {
    if (argc != 3) {
        usage();
    } else {
        parallel_checker(argv[1], atoi(argv[2]));
    }

    return EXIT_SUCCESS;
}
</code>```

I think that I'm missing something with the synchronization mechanisms, can anyone spot where I was wrong?

Thanks a lot!!!

答:
One multi-threading logic flaw is definitely:

There is no distinction between "worker input queue temporarily empty" and "file reader thread finished" - Your workers simply exit when there is nothing to read (even temporarily) on their input queue. So, if the file_reader thread produces queue entries slower than the workers consume them for any reason, the consumers will starve and die, leaving the producer with no consumer and, finally, a hang.

Title: Multi-threaded Queue in Linux C

Body:
I'm writing a simple program that reads urls from a text file, and checks the validity of them using multi threaded programming. I used mutexes and condition variables to synchronize my threads but my app still crashes and after some debugging sessions I decided to get some help :)

The input of the file is a text file containing urls like:
http://www.youtube.com/
http://www.facebook.com/

And the output should be the aggregated result of the curl request on each url (whether it returns OK, UNKOWN or ERROR)

This is my code:

/*
 * ex3.c
 */

#define _GNU_SOURCE

#include <curl/curl.h>
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#define REQUEST_TIMEOUT_SECONDS 2L

#define URL_OK 0
#define URL_ERROR 1
#define URL_UNKNOWN 2

#define QUEUE_SIZE 32

#define handle_error_en(en, msg) \
        do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)

typedef struct {
    int ok, error, unknown;
} UrlStatus;

typedef struct {
    void **array;
    int size;
    int capacity;
    int head;
    int tail;
    pthread_mutex_t mutex;
    pthread_cond_t cv_empty; /* get notified when the queue is not full */
    pthread_cond_t cv_full; /* get notified when the queue is not empty */
} Queue;

void queue_init(Queue *queue, int capacity) {
    /*
     * Initializes the queue with the specified capacity.
     * This function should allocate the internal array, initialize its properties
     * and also initialize its mutex and condition variables.
     */
    queue->array = (void**)malloc(sizeof(void*) * capacity);
    if (queue->array == NULL) {
        perror("unable to allocate memory");
        exit(EXIT_FAILURE);
    }
    queue->capacity = capacity;
    queue->size = 0;
    queue->head = 0;
    queue->tail = 0;
    pthread_mutex_init(&(queue->mutex), NULL);
    pthread_cond_init(&(queue->cv_empty), NULL);
    pthread_cond_init(&(queue->cv_full), NULL);
}

void enqueue(Queue *queue, void *data) {
    /*
     * Enqueue an object to the queue.
     *
     * TODO:
     * 1. This function should be synchronized on the queue's mutex
     * 2. If the queue is full, it should wait until it is not full
     *      (i.e. cv_empty)
     * 3. Add an element to the tail of the queue, and update the tail & size
     *      parameters
     * 4. Signal that the queue is not empty (i.e. cv_full)
     */

    pthread_mutex_lock(&(queue->mutex));
    while (queue->size >= QUEUE_SIZE) {
        pthread_cond_wait(&(queue->cv_empty), &(queue->mutex));
    }

    if(queue->size == 0) {
        queue->head = 0;
    }

    queue->array[queue->tail] = data;
    queue->size++;

    queue->tail++;
    pthread_cond_signal(&(queue->cv_full));
    pthread_mutex_unlock(&(queue->mutex));

}

void *dequeue(Queue *queue) {
    /*
     * Dequeue an object from the queue.
     *
     * TODO:
     * 1. This function should be synchronized on the queue's mutex
     * 2. If the queue is empty, it should wait until it is not empty (i.e. cv_full)
     * 3. Read the head element, and update the head & size parameters
     * 4. Signal that the queue is not full (i.e. cv_empty)
     * 5. Return the dequeued item
     */
    void *data;

    pthread_mutex_lock(&(queue->mutex));
    while (queue->size <= 0) {
        pthread_cond_wait(&(queue->cv_full), &(queue->mutex));
    }

    queue->head++;
    data = queue->array[queue->head];
    queue->size--;

    pthread_cond_signal(&(queue->cv_empty));
    pthread_mutex_unlock(&(queue->mutex));

    return data;
}

void queue_destroy(Queue *queue) {
    /*
     * Free the queue memory and destroy the mutex and the condition variables.
     */
    int ret;

    free(queue->array);

    ret = pthread_mutex_destroy(&(queue->mutex));
    if (ret != 0) {
        handle_error_en(ret, "unable to destroy mutex");
    }
    ret = pthread_cond_destroy(&(queue->cv_empty));
    if (ret != 0) {
        handle_error_en(ret, "unable to destroy cv_empty condition variable");
    }
    ret = pthread_cond_destroy(&(queue->cv_full));
    if (ret != 0) {
        handle_error_en(ret, "unable to destroy cv_full condition variable");
    }
}

void usage() {
    fprintf(stderr, "usage:\n\t./ex3 FILENAME NUMBER_OF_THREADS\n");
    exit(EXIT_FAILURE);
}

int count = 0;
int check_url(const char *url) {
    CURL *curl;
    CURLcode res;
    long response_code = 0L;
    int http_status = URL_UNKNOWN;

    curl = curl_easy_init();

    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, REQUEST_TIMEOUT_SECONDS);
        curl_easy_setopt(curl, CURLOPT_NOBODY, 1L); /* do a HEAD request */

        res = curl_easy_perform(curl);
        if(res == CURLE_OK) {
            res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);

            if (res == CURLE_OK &&
                    response_code >= 200 &&
                    response_code < 400) {
                http_status = URL_OK;
            } else {
                http_status = URL_ERROR;
            }
        }
        curl_easy_cleanup(curl);
    }

    return http_status;
}

typedef struct {
    Queue *url_queue;
    Queue *result_queue;
} WorkerArguments;

void *worker(void *args) {
    /*
     * TODO:
     * 1. Initialize a UrlStatus (allocate memory using malloc, and zero it
     *      using memset)
     * 2. Dequeue URL from url_queue, run check_url on it, and update results
     *    (don't forget to free() the url)
     * 3. After dequeuing a NULL value:
     *      Enqueue results to result_queue and return
     */

    WorkerArguments *worker_args = (WorkerArguments *)args;
    UrlStatus *results = NULL;
    char *url;

    results = malloc(sizeof(UrlStatus));
    if(results == NULL) {
        perror("Could not allocate memory");
        exit(-1);
    }

    memset(results, 0, sizeof(UrlStatus));

    while((url = (char *)dequeue(worker_args->url_queue)) != NULL) {
        switch(check_url(url)) {
            case URL_OK:
                results->ok++;
            break;
            case URL_UNKNOWN:
                results->unknown++;
            break;
            case URL_ERROR:
                results->error++;
            break;
        }
        /*free(url);*/
    }
    enqueue(worker_args->result_queue, results);
    return NULL;
}

typedef struct {
    const char *filename;
    Queue *url_queue;
} FileReaderArguments;

void *file_reader(void *args) {
    /*
     * TODO:
     * 1. Open filename (use fopen, check for errors)
     * 2. Use getline() to read lines (i.e. URLs) from the file (use errno to check for errors)
     * 3. Copy each url to the heap (use malloc and strncpy)
     * 4. Enqueue the URL to url_queue
     * 5. Don't forget to free the line variable, and close the file (and check for errors!)
     */

    FileReaderArguments *file_reader_args = (FileReaderArguments *)args;
    FILE *toplist_file;
    char *line = NULL;
    char *url = NULL;
    size_t len = 0;
    ssize_t read = 0;

    toplist_file = fopen(file_reader_args->filename, "r");

        if (toplist_file == NULL) {
            exit(EXIT_FAILURE);
        }

    while ((read = getline(&line, &len, toplist_file)) != -1) {
        if (read == -1) {
            perror("error reading file");
        }
        if(read == 1) continue; /*empty line*/
        url = malloc(read);
        if(url == NULL) {
            perror("Could not allocate memory");
        }
        line[read-1] = '\0'; /* null-terminate the URL */
        strncpy(url, line, read);
        enqueue(file_reader_args->url_queue, url);
    }
    fclose(toplist_file);
    return NULL;
}

typedef struct {
    int number_of_threads;
    Queue *url_queue;
    Queue *result_queue;
} CollectorArguments;

void *collector(void *args) {
    /*
     * TODO:
     * 1. Enqueue number_of_threads NULLs to the url_queue
     * 2. Dequeue and aggregate number_of_threads thread_results
     *      from result_queue into results (don't forget to free() thread_results)
     * 3. Print aggregated results to the screen
     */

    CollectorArguments *collector_args = (CollectorArguments *)args;
    UrlStatus results = {0};
    UrlStatus *thread_results;
    int i;

    for(i= 0; i < collector_args->number_of_threads; i++) {
    }

    for(i= 0; i < collector_args->number_of_threads; i++) {
        thread_results = dequeue(collector_args->result_queue);
        results.ok += thread_results->ok;
        results.error += thread_results->error;
        results.unknown += thread_results->unknown;
        /* free(thread_results);*/
    }

    printf("%d OK, %d Error, %d Unknown\n",
            results.ok,
            results.error,
            results.unknown);
    return NULL;
}

void parallel_checker(const char *filename, int number_of_threads) {
    /*
     * TODO:
     * 1. Initialize a Queue for URLs, a Queue for results (use QUEUE_SIZE)
     * 2. Start number_of_threads threads running worker()
     * 3. Start a thread running file_reader(), and join it
     * 4. Start a thread running collector(), and join it
     * 5. Join all worker threads
     * 6. Destroy both queues
     */
    Queue url_queue, result_queue;
    WorkerArguments worker_arguments = {0};
    FileReaderArguments file_reader_arguments = {0};
    CollectorArguments collector_arguments = {0};
    pthread_t *worker_threads;
    pthread_t file_reader_thread, collector_thread;
    int i;
    int err;

    queue_init(&url_queue, QUEUE_SIZE);
    queue_init(&result_queue, QUEUE_SIZE);

    worker_arguments.url_queue = &url_queue;
    worker_arguments.result_queue = &result_queue;

    file_reader_arguments.filename = filename;
    file_reader_arguments.url_queue = &url_queue;

    collector_arguments.url_queue = &url_queue;
    collector_arguments.result_queue = &result_queue;
    collector_arguments.number_of_threads = number_of_threads;

    worker_threads = (pthread_t *) malloc(sizeof(pthread_t) * number_of_threads);
    if (worker_threads == NULL) {
        perror("unable to allocate memory");
        return;
    }
    curl_global_init(CURL_GLOBAL_ALL); /* init libcurl before starting threads */

    for(i=0; i<number_of_threads; i++) {
        err = pthread_create(&(worker_threads[i]), NULL, &worker, &worker_arguments);
        if (err != 0) {
            fprintf(stderr, "can't create thread :[%s]\n", strerror(err));
        }
    }

    err = pthread_create(&file_reader_thread, NULL, &file_reader, &file_reader_arguments);
    if (err != 0) {
        fprintf(stderr, "can't create thread :[%s]\n", strerror(err));
    }

    err = pthread_join(file_reader_thread, NULL);
    if (err != 0) {
        fprintf(stderr, "can't join thread :[%s]\n", strerror(err));
    }

    err = pthread_create(&collector_thread, NULL, &collector, &collector_arguments);
    if (err != 0) {
        fprintf(stderr, "can't create thread :[%s]\n", strerror(err));
    }

    err = pthread_join(collector_thread, NULL);
    if (err != 0) {
        fprintf(stderr, "can't join thread :[%s]\n", strerror(err));
    }

    for(i=0; i<number_of_threads; i++) {
        err = pthread_join(worker_threads[i], NULL);

        if (err != 0) {
            fprintf(stderr, "can't join thread :[%s]\n", strerror(err));
        }
    }

    queue_destroy(&url_queue);
    queue_destroy(&result_queue);
    free(worker_threads);
}

int main(int argc, char **argv) {
    if (argc != 3) {
        usage();
    } else {
        parallel_checker(argv[1], atoi(argv[2]));
    }

    return EXIT_SUCCESS;
}

I think that I'm missing something with the synchronization mechanisms, can anyone spot where I was wrong?

Thanks a lot!!!


问:
How to write a simple generic Core Data function for all Entities
EDIT: Specifically using Swift Generics

I want a countAll() function for all of my entities and I'm hoping to achieve this by writing one generic function.

The following handles an entity called 'Event', but I want to handle an entity named 'T'.

I'm not sure how to write a generic function like this. Could someone help please?

```<code>func countAll() -> Int {
    let request: NSFetchRequest<Event> = Event.fetchRequest()
    do {
      return try persistentContainer.viewContext.count(for: request)
    } catch {
      XCTAssert(false, "Core Data failed to fetch with error: " + error.localizedDescription)
      return 0
    }
}
</code>```

This is the closest I can get before I hit an error:

```<code>func count<T: NSFetchRequestResult>(entityName: String) -> Int {
    let request = NSFetchRequest<T>(entityName: entityName)
    do {
      return try persistentContainer.viewContext.count(for: request)
    } catch {
      XCTAssert(false, "Core Data failed to fetch with error: " + error.localizedDescription)
      return 0
    }
}
</code>```

答:
A suitable alternative to a generic function is a protocol extension and class methods

```<code>protocol Fetchable
{
    associatedtype FetchableType: NSManagedObject = Self

    static var entityName : String { get }
    static func countAll(in persistentContainer: NSPersistentContainer) throws -> Int

}

extension Fetchable where Self : NSManagedObject, FetchableType == Self
{
    static var entityName : String {
        return NSStringFromClass(self).components(separatedBy: ".").last!
    }

    static func countAll(in persistentContainer: NSPersistentContainer) throws -> Int
    {
        let request = NSFetchRequest<FetchableType>(entityName: entityName)
        return try persistentContainer.viewContext.count(for: request)
    }
}
</code>```

The benefit is you can call the method on the class, just make your NSManagedObject subclasses adopt the protocol.

```<code>do {
    try Event.countAll(in: persistentContainer)
} catch { print(error) }
</code>```

Body:
EDIT: Specifically using Swift Generics

I want a countAll() function for all of my entities and I'm hoping to achieve this by writing one generic function.

The following handles an entity called 'Event', but I want to handle an entity named 'T'.

I'm not sure how to write a generic function like this. Could someone help please?

func countAll() -> Int {
    let request: NSFetchRequest<Event> = Event.fetchRequest()
    do {
      return try persistentContainer.viewContext.count(for: request)
    } catch {
      XCTAssert(false, "Core Data failed to fetch with error: " + error.localizedDescription)
      return 0
    }
}

This is the closest I can get before I hit an error:

func count<T: NSFetchRequestResult>(entityName: String) -> Int {
    let request = NSFetchRequest<T>(entityName: entityName)
    do {
      return try persistentContainer.viewContext.count(for: request)
    } catch {
      XCTAssert(false, "Core Data failed to fetch with error: " + error.localizedDescription)
      return 0
    }
}

Body:
A suitable alternative to a generic function is a protocol extension and class methods

protocol Fetchable
{
    associatedtype FetchableType: NSManagedObject = Self

    static var entityName : String { get }
    static func countAll(in persistentContainer: NSPersistentContainer) throws -> Int

}

extension Fetchable where Self : NSManagedObject, FetchableType == Self
{
    static var entityName : String {
        return NSStringFromClass(self).components(separatedBy: ".").last!
    }

    static func countAll(in persistentContainer: NSPersistentContainer) throws -> Int
    {
        let request = NSFetchRequest<FetchableType>(entityName: entityName)
        return try persistentContainer.viewContext.count(for: request)
    }
}

The benefit is you can call the method on the class, just make your NSManagedObject subclasses adopt the protocol.

do {
    try Event.countAll(in: persistentContainer)
} catch { print(error) }


问:
Trying to organize data into df form
I receive a big json among 2 dates that returns the inventory of some chemical elements stored in a lab.

ElementData is the json 1 recieve, with the followinf structure:

```<code>ElementData= [{'_id': '', 'date': '2017-06-01T00:00:00.000Z', 'values': {'Boron':
{'amount': 58.67,'time': '15:40:02'}, 'Cobalt':
{'amount': '108.25', 'time': '11:35:39'}, 'Fluorine':
{'amount': '13.25','time': '09:38:48'},
'silver': {'amount': '200.89', 'time':
'13:28:14'}, 'chronium': {'amount': '10.22',
'time': '14:00:30'}...
    }
  }
]
</code>```

In order to obtain the dates from the json I use item['date'] in the following code,  I recieve:

```<code>dates=[]
for item in ElementData:
    dates.append((item['date'])[0:10])
print(dates)
</code>```

Returning for my particular json:

```<code>['2017-06-01', '2017-06-02']
</code>```

On the other hand, I have a list of elements from which I would like to find the chemical amounts stored those dates.

```<code>list=['Potasium','Sodium']
</code>```

To get the stored amounts of the listed elements  for the given dates, the code I use is:

```<code>for elements in list:
    for item in ElementData:
        print (elements + ' amount for date ' +item['date'][0:10]+ ' was:' + str(item['values'][elements]['amount']))
</code>```

returning the following :

```<code>potassium amount for date 2017-06-01 was:12.19
potassium amount for date 2017-06-02 was:10.07
sodium amount for date 2017-06-01 was:7.22
sodium amount for date 2017-06-02  was:30.07
</code>```

The problem I am facing is that I would like with the given data to obtain a dataframe like this:

```<code>               Potasium    Sodium
2017-06-02       10.07      30.07
2017-06-01       12.19       7.22
</code>```

The main issue I am facing is to insert the values in the dataframe, it is the first time I am dealing with this problem and not sure the steps to follow.

答:
The data you have appears to contain 3 important features, the chemical name, the date of a measurement and the measurement itself.

A dataframe can be constructed from smaller objects called Series. A series has a name, a set of values, and an index used to identify each value - so it's not a bad fit.

What's additionally helpful, is that you can combine a bunch of Series together into a dataframe, and pandas will take care of what happens when the indices don't align.

So, one way to construct a series, is to combine a pair of lists, one containing the set of values you construct from your data, and the other to contain the index records.

```<code>import pandas as pd

sodium = [ 7.22, 30.07 ]
sodium_index = [ '2017-06-01', '2017-06-02' ]
potassium = [12.19, 10.07]
potassium_index = [ '2017-06-01', '2017-06-02' ]

sodium_series = pd.Series(sodium, index=sodium_index)
potassium_series = pd.Series(potassium, index=potassium_index)
</code>```

Which gives you a pair of series objects, that can be combined to form a dataframe:

```<code>chemical_df = pd.concat([sodium_series, potassium_series],axis=1).rename(columns={0:'Sodium',1:'Potassium'})
</code>```

There's a lot going on in that final line - but essentially, it's a combination of the two series, specifying that the series represent columns (axis=0 would try to combine them end-to-end as a list of 4 records) and setting the column names from their default 0,1,2,... values to the appropriate English-names.

In the example above, the index (date) of the measurements is aligned across the two different sets of measurements, but if there were some misalignment, say you had a different number of readings, or different dates for the readings, pandas will still create the dataframe, but will fill in the missing values (by default) with NaN.

ContentLicense: CC BY-SA 4.0

Title: Trying to organize data into df form

Body:
I receive a big json among 2 dates that returns the inventory of some chemical elements stored in a lab.

ElementData is the json 1 recieve, with the followinf structure:

ElementData= [{'_id': '', 'date': '2017-06-01T00:00:00.000Z', 'values': {'Boron':
{'amount': 58.67,'time': '15:40:02'}, 'Cobalt':
{'amount': '108.25', 'time': '11:35:39'}, 'Fluorine':
{'amount': '13.25','time': '09:38:48'},
'silver': {'amount': '200.89', 'time':
'13:28:14'}, 'chronium': {'amount': '10.22',
'time': '14:00:30'}...
    }
  }
]

In order to obtain the dates from the json I use item['date'] in the following code,  I recieve:

dates=[]
for item in ElementData:
    dates.append((item['date'])[0:10])
print(dates)

Returning for my particular json:

['2017-06-01', '2017-06-02']

On the other hand, I have a list of elements from which I would like to find the chemical amounts stored those dates.

list=['Potasium','Sodium']

To get the stored amounts of the listed elements  for the given dates, the code I use is:

for elements in list:
    for item in ElementData:
        print (elements + ' amount for date ' +item['date'][0:10]+ ' was:' + str(item['values'][elements]['amount']))

returning the following :

potassium amount for date 2017-06-01 was:12.19
potassium amount for date 2017-06-02 was:10.07
sodium amount for date 2017-06-01 was:7.22
sodium amount for date 2017-06-02  was:30.07

The problem I am facing is that I would like with the given data to obtain a dataframe like this:

               Potasium    Sodium
2017-06-02       10.07      30.07
2017-06-01       12.19       7.22

The main issue I am facing is to insert the values in the dataframe, it is the first time I am dealing with this problem and not sure the steps to follow.

Body:
The data you have appears to contain 3 important features, the chemical name, the date of a measurement and the measurement itself.

A dataframe can be constructed from smaller objects called Series. A series has a name, a set of values, and an index used to identify each value - so it's not a bad fit.

What's additionally helpful, is that you can combine a bunch of Series together into a dataframe, and pandas will take care of what happens when the indices don't align.

So, one way to construct a series, is to combine a pair of lists, one containing the set of values you construct from your data, and the other to contain the index records.

import pandas as pd

sodium = [ 7.22, 30.07 ]
sodium_index = [ '2017-06-01', '2017-06-02' ]
potassium = [12.19, 10.07]
potassium_index = [ '2017-06-01', '2017-06-02' ]

sodium_series = pd.Series(sodium, index=sodium_index)
potassium_series = pd.Series(potassium, index=potassium_index)

Which gives you a pair of series objects, that can be combined to form a dataframe:

chemical_df = pd.concat([sodium_series, potassium_series],axis=1).rename(columns={0:'Sodium',1:'Potassium'})

There's a lot going on in that final line - but essentially, it's a combination of the two series, specifying that the series represent columns (axis=0 would try to combine them end-to-end as a list of 4 records) and setting the column names from their default 0,1,2,... values to the appropriate English-names.

In the example above, the index (date) of the measurements is aligned across the two different sets of measurements, but if there were some misalignment, say you had a different number of readings, or different dates for the readings, pandas will still create the dataframe, but will fill in the missing values (by default) with NaN.


问:
i have error while create CRM app
```<code>[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MyPage : ContentPage
{
    AuthenticationResult authResult;
    private OrganizationDataWebServiceProxy proxy;
    public MyPage()
    {
        InitializeComponent();
        myButton.Clicked += MyButton_Clicked;

        proxy = new OrganizationDataWebServiceProxy();
    }
    async void MyButton_Clicked(object sender, EventArgs args)
    {
        try
        {
            var auth = DependencyService.Get<IAuthenticator>();
           authResult = await auth.Authenticate(Constants.Authority,

            Constants.ServiceURL,

            Constants.ClientId,

            Constants.RedirectURL,

            Constants.Username,

            Constants.Password);
        }
        catch(Exception ex)
        {

            await DisplayAlert("Error", "This: " + ex, "got it");
        }

        proxy.ServiceUrl = Constants.ServiceURL;

        proxy.AccessToken = authResult.AccessToken;

        await GetLoggedInUserName();

    }
    public async Task GetLoggedInUserName()
    {
        try
        {
            WhoAmIResponse result = (WhoAmIResponse)await proxy.Execute(new WhoAmIRequest());

            await DisplayAlert("Result \n", "User Id : " + result.UserId.ToString() + "\n OrganizationId: " + result.OrganizationId.ToString() + "\n BusinessUnitId: " + result.BusinessUnitId.ToString(), "Ok", "Cancel");

        }
        catch (Exception ex)
        {

            await DisplayAlert("Error", "This: " + ex, "got it");
        }
    }

}
</code>```

}

And i get this error message

1.The name lt doesnt exist in the current text

2.The name amp doesnt exist in the current text

3.The name gt doesnt exist in the current text

4.IAuthenticator is a type which isnt valid in the given context

 somebody please help me, i was about to make crm app with xamarin.forms from this tutorial http://scaleablesolutions.com/connecting-xamarin-form-application-with-dynamics-crm/

答:
Author of that tutorial has some errors in code due to HTML encoding, and you copied that error.

Change line

```<code>var auth = DependencyService.Get&lt;IAuthenticator&gt;();
</code>```

Into

```<code>var auth = DependencyService.Get<IAuthenticator>();
</code>```

Title: i have error while create CRM app

Body:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MyPage : ContentPage
{
    AuthenticationResult authResult;
    private OrganizationDataWebServiceProxy proxy;
    public MyPage()
    {
        InitializeComponent();
        myButton.Clicked += MyButton_Clicked;

        proxy = new OrganizationDataWebServiceProxy();
    }
    async void MyButton_Clicked(object sender, EventArgs args)
    {
        try
        {
            var auth = DependencyService.Get&lt;IAuthenticator&gt;();
           authResult = await auth.Authenticate(Constants.Authority,

            Constants.ServiceURL,

            Constants.ClientId,

            Constants.RedirectURL,

            Constants.Username,

            Constants.Password);
        }
        catch(Exception ex)
        {

            await DisplayAlert("Error", "This: " + ex, "got it");
        }

        proxy.ServiceUrl = Constants.ServiceURL;

        proxy.AccessToken = authResult.AccessToken;

        await GetLoggedInUserName();

    }
    public async Task GetLoggedInUserName()
    {
        try
        {
            WhoAmIResponse result = (WhoAmIResponse)await proxy.Execute(new WhoAmIRequest());

            await DisplayAlert("Result \n", "User Id : " + result.UserId.ToString() + "\n OrganizationId: " + result.OrganizationId.ToString() + "\n BusinessUnitId: " + result.BusinessUnitId.ToString(), "Ok", "Cancel");

        }
        catch (Exception ex)
        {

            await DisplayAlert("Error", "This: " + ex, "got it");
        }
    }

}

}

And i get this error message

1.The name lt doesnt exist in the current text

2.The name amp doesnt exist in the current text

3.The name gt doesnt exist in the current text

4.IAuthenticator is a type which isnt valid in the given context

 somebody please help me, i was about to make crm app with xamarin.forms from this tutorial http://scaleablesolutions.com/connecting-xamarin-form-application-with-dynamics-crm/

Body:
Author of that tutorial has some errors in code due to HTML encoding, and you copied that error.

Change line

var auth = DependencyService.Get&amp;lt;IAuthenticator&amp;gt;();

Into

var auth = DependencyService.Get<IAuthenticator>();


问:
Update association with doctrine and symfony 2.7
I want to know if it exists a better way to update association in doctrine from the inversed side entity, in this case it's a many to many type, but it may be another one.
This is the method I used :

```<code>$entity = $em->getRepository('MyBundle:MyEntity')->find($id);

foreach ($entity->getAssociation() as $value) {
    $entity->removeAssociation($value);
}
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
        foreach ($entity->getAssociation() as $value) {
            $entity->addAssociation($value);
        }
        $em->flush();
}
</code>```

I think that it's not a good approach, beacause I want to update (so remove and add) only the association that i select or unselect in my form, not every element of the array. So I made a service with an update function :

```<code>    public function updateCollection(&$newEntity, $newCollection, $oldCollection, $contains, $add, $remove) {

    foreach ($oldCollection as $value) {
        $item = call_user_func(array($newCollection, $contains), $value);
        if(!$item){
            call_user_func( array($newEntity, $remove), $value );
        }
    }

    foreach ($newCollection as $value) {
        $item = call_user_func(array($oldCollection, $contains), $value );
        if(!$item){
            call_user_func( array($newEntity, $add), $value );
        }
    }

}
</code>```

And I call this method with this :

```<code>    $oldAssociation = clone $entity->getAssociation();

    $editForm = $this->createEditForm($entity);
    $editForm->handleRequest($request);

    if ($editForm->isValid()) {

      $this->get('service_update')->updateCollection(
        $entity,
        $entity->getAssociation(),
        $oldAssociation,
        'contains',
        'addAssociation',
        'removeAssociation'
  );

  $em->flush();

}
</code>```

But I think that this method is more time expensive than the first one, but it only remove and add elements from the array for wich the association has been changed. I don't know what is the best way to do this, maybe none of the two. Can you bring me on the right way please?
Thank you and sorry for my bad english

答:
I was doing it in the wrong way.
I found the best solution ever to update the inversed side of a relation in this post:
https://knpuniversity.com/screencast/collections/saving-inverse-side-collection

I don't know why but I didn't found that before, I advise people to use that solution for a multiple choices of entity type elements.

Body:
I want to know if it exists a better way to update association in doctrine from the inversed side entity, in this case it's a many to many type, but it may be another one.
This is the method I used :

$entity = $em->getRepository('MyBundle:MyEntity')->find($id);

foreach ($entity->getAssociation() as $value) {
    $entity->removeAssociation($value);
}
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
        foreach ($entity->getAssociation() as $value) {
            $entity->addAssociation($value);
        }
        $em->flush();
}

I think that it's not a good approach, beacause I want to update (so remove and add) only the association that i select or unselect in my form, not every element of the array. So I made a service with an update function :

    public function updateCollection(&$newEntity, $newCollection, $oldCollection, $contains, $add, $remove) {

    foreach ($oldCollection as $value) {
        $item = call_user_func(array($newCollection, $contains), $value);
        if(!$item){
            call_user_func( array($newEntity, $remove), $value );
        }
    }

    foreach ($newCollection as $value) {
        $item = call_user_func(array($oldCollection, $contains), $value );
        if(!$item){
            call_user_func( array($newEntity, $add), $value );
        }
    }

}

And I call this method with this :

    $oldAssociation = clone $entity->getAssociation();

    $editForm = $this->createEditForm($entity);
    $editForm->handleRequest($request);

    if ($editForm->isValid()) {

      $this->get('service_update')->updateCollection(
        $entity,
        $entity->getAssociation(),
        $oldAssociation,
        'contains',
        'addAssociation',
        'removeAssociation'
  );

  $em->flush();

}

But I think that this method is more time expensive than the first one, but it only remove and add elements from the array for wich the association has been changed. I don't know what is the best way to do this, maybe none of the two. Can you bring me on the right way please?
Thank you and sorry for my bad english


问:
Calling python file from java throws error
I am trying to call python file from java. but it throws following error.

```<code>java.io.IOException: Cannot run program "python": CreateProcess error=2, The system cannot find the file specified
</code>```

The code that I have tried is :

```<code>    Process p = Runtime.getRuntime().exec("python C:\\Project\\Script\\Test.py");
    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    System.out.println(in.readLine());
</code>```

what could be the problem?

答:
Runtime.exec expects a file with no path information to be in the user dir and not in the directory you specify to use as working directory.
Try using this code once.</p>

```<code>Runtime rt = Runtime.getRuntime();
Process prs;
File Dir_temp = new File("C:\\Project\\Script\\");
prs = rt.exec(new File(Dir_temp, "Test.py").getAbsolutePath(), null, Dir_temp);
prs.waitFor();
prs.destroy();
</code>```

Body:
I am trying to call python file from java. but it throws following error.

java.io.IOException: Cannot run program "python": CreateProcess error=2, The system cannot find the file specified

The code that I have tried is :

    Process p = Runtime.getRuntime().exec("python C:\\Project\\Script\\Test.py");
    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    System.out.println(in.readLine());

what could be the problem?

Body:
Runtime.exec expects a file with no path information to be in the user dir and not in the directory you specify to use as working directory.
Try using this code once.

Runtime rt = Runtime.getRuntime();
Process prs;
File Dir_temp = new File("C:\\Project\\Script\\");
prs = rt.exec(new File(Dir_temp, "Test.py").getAbsolutePath(), null, Dir_temp);
prs.waitFor();
prs.destroy();


问:
I was trying to convert images to a video using jcodec
I was trying to convert a set of images into video using Jcodec, Saw a video on youtube that was running correctly. I did everything they showed. But the code didn't work. plz, help. I'm posting the link to the video, my code, and the errors.

video link: https://www.youtube.com/watch?v=NYhnqE3E4CI

java code:

```<code>package imagetovideoencoder;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.jcodec.api.awt.AWTSequenceEncoder;
import org.jcodec.api.SequenceEncoder;
import org.jcodec.common.io.NIOUtils;
import org.jcodec.common.io.SeekableByteChannel;
import org.jcodec.scale.AWTUtil;
import org.jcodec.common.*;

/**
 *
 * @author dell
 */
public class ImagetoVideoEncoder {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {

        AWTSequenceEncoder enc = AWTSequenceEncoder.createSequenceEncoder(new File("C:\\Users\\dell\\Desktop\\Downloads from seenium\\test.mp4"));
        enc.getEncoder().setKeyInterval(25);
        int framestoEncode = 100;

        for(int i=1;i<=framestoEncode/2;++i)
        {
            BufferedImage image = ImageIO.read(new File("C:/Users/dell/Desktop/Downloads from seenium/0f1f4905877e9a5e92b069c966059cce.jpg"));
            enc.encodeImage(image);
        }

        for(int i=1;i<=framestoEncode/2;++i)
        {
            BufferedImage image = ImageIO.read(new File("C:/Users/dell/Desktop/Downloads from seenium/54cae4238a5cf_-_american-muscle-facts-05-0312-xln.jpg"));
            enc.encodeImage(image);
        }

        enc.finish();
    }

}
</code>```

error:
    run:

Exception in thread "main" java.lang.NoSuchMethodError: org.jcodec.api.SequenceEncoder.(Lorg/jcodec/common/io/SeekableByteChannel;)V
          at org.jcodec.api.awt.AWTSequenceEncoder.(AWTSequenceEncoder.java:27)
          at org.jcodec.api.awt.AWTSequenceEncoder.createSequenceEncoder(AWTSequenceEncoder.java:23)
          at imagetovideoencoder.ImagetoVideoEncoder.main(ImagetoVideoEncoder.java:30)
      C:\Users\dell\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
      BUILD FAILED (total time: 9 seconds)

答: The above code worked. A proper method to encode images into video. It was the problem of incompatible JAR files as suggested by Jens in one of the answers. So I deleted the added JAR files and repeated the steps shown in the video. It worked. Only thing I noticed was that the images needed to be of the same size. So I just ran a small function to resize the images to same size. It works fine.  </p>

Body:
I was trying to convert a set of images into video using Jcodec, Saw a video on youtube that was running correctly. I did everything they showed. But the code didn't work. plz, help. I'm posting the link to the video, my code, and the errors.

video link: https://www.youtube.com/watch?v=NYhnqE3E4CI

java code:

package imagetovideoencoder;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.jcodec.api.awt.AWTSequenceEncoder;
import org.jcodec.api.SequenceEncoder;
import org.jcodec.common.io.NIOUtils;
import org.jcodec.common.io.SeekableByteChannel;
import org.jcodec.scale.AWTUtil;
import org.jcodec.common.*;

/**
 *
 * @author dell
 */
public class ImagetoVideoEncoder {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {

        AWTSequenceEncoder enc = AWTSequenceEncoder.createSequenceEncoder(new File("C:\\Users\\dell\\Desktop\\Downloads from seenium\\test.mp4"));
        enc.getEncoder().setKeyInterval(25);
        int framestoEncode = 100;

        for(int i=1;i<=framestoEncode/2;++i)
        {
            BufferedImage image = ImageIO.read(new File("C:/Users/dell/Desktop/Downloads from seenium/0f1f4905877e9a5e92b069c966059cce.jpg"));
            enc.encodeImage(image);
        }

        for(int i=1;i<=framestoEncode/2;++i)
        {
            BufferedImage image = ImageIO.read(new File("C:/Users/dell/Desktop/Downloads from seenium/54cae4238a5cf_-_american-muscle-facts-05-0312-xln.jpg"));
            enc.encodeImage(image);
        }

        enc.finish();
    }

}

error:
    run:

Exception in thread "main" java.lang.NoSuchMethodError: org.jcodec.api.SequenceEncoder.(Lorg/jcodec/common/io/SeekableByteChannel;)V
          at org.jcodec.api.awt.AWTSequenceEncoder.(AWTSequenceEncoder.java:27)
          at org.jcodec.api.awt.AWTSequenceEncoder.createSequenceEncoder(AWTSequenceEncoder.java:23)
          at imagetovideoencoder.ImagetoVideoEncoder.main(ImagetoVideoEncoder.java:30)
      C:\Users\dell\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
      BUILD FAILED (total time: 9 seconds)


问:
What language apart from JavaScript can you execute in a browser
Are there other languages apart from javascript that browsers can interpret and execute. I'm happy for browser specific ones as well.

Any answers welcomed

答:
Every language for which an interpreter written in JavaScript exists: Brainfuck, Ruby (more precisely: YARV bytecode), Scheme, Clamato, many others.

Every language for which a compiler exists that compiles the language to JavaScript: C, Java, JVML bytecode, CIL bytecode, Ruby, Clojure, Scala, Objective-J, Haxe, Ur, Links, Flapjax, Caja, many others.

Every language for which a compiler exists that compiles the language to one of the languages listed above, since you can then either interpret the output of the compiler in JavaScript, or compile it again to JavaScript. (E.g. you can compile JVML bytecode to JavaScript and you can compile Ruby to JVML bytecode, ergo you can compile Ruby to JavaScript.)

Every language for which an interpreter exists as a browser plugin: JVML bytecode (Java Applets), CIL bytecode (Silverlight), ActionScript bytecode (Flash), C, many others.

Every language which can be executed by the browser directly: VBScript (in Internet Explorer), XSLT (several browsers), x86/AMD64 machine code (Chrome Native Client), many others.

See also:

What language types are allowed in the HTML script tag?

Are there other languages than Objective-J that get “compiled” to JavaScript in the browser?

ContentLicense: CC BY-SA 2.5


问:
Dynamicaly pick the change from drool file at runtime | without maven
I am very very new to Drool, please forgive me if I have made any foolish mistake below. I am currently working on an application which is Ant based (migrating to maven is a high risk). I am trying to upgrade the drool version from 4.0.7 to 6.5.0. I want to dynamically get the updated version of the .drl file at runtime of java code so that I don't need to build the java files every time. Here is my below code.

DroolsPoc.java

```<code>package com.test;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import org.kie.api.KieServices;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;

public class DroolsPoc {

    private static AtomicBoolean isRulesChangeScanerStarted = new AtomicBoolean(
            false);

    public static void main(String[] args) throws InterruptedException {

        Map<String, Object> input = new HashMap<String, Object>();

        input.put("input", new Dto());

        KieServices ks = KieServices.Factory.get();

        KieFileSystem kfs = ks.newKieFileSystem();
        kfs.write(ResourceFactory.newFileResource(new File("C:/Users/workspace1/Drools_POC/src/poc.drl")));
        ks.newKieBuilder(kfs).buildAll();

        KieContainer kieContainer = ks.newKieContainer(ks.getRepository().getDefaultReleaseId());

        KieSession kieSession = kieContainer.newKieSession();
        kieSession.insert(input);
        System.out.println("Fired all rules 1");
        kieSession.fireAllRules();

        System.out.println(((Dto) input.get("input")).getName());

        Thread.currentThread().sleep(20000);

        /*The updated rule should get printed by below code*/
        KieSession kieSession1 = kieContainer.newKieSession();
        kieSession1.insert(input);
        System.out.println("Fired all rules 2");
        kieSession1.fireAllRules();

        System.out.println(((Dto) input.get("input")).getName());

    }

}
</code>```

Dto.java

```<code>package com.test;

public class Dto {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}
</code>```

poc.drl

```<code>import java.util.Map;
import java.util.HashMap;
import com.test.Dto;

function Boolean checkIfNull(Map input){

  Dto dto = (Dto)input.get("input");

  if (null == dto.getName()){
      return true;
  }

      return false;

}

function void setName(Map input){

  Dto dto = (Dto)input.get("input");

  dto.setName("The moon is out");

}

rule "PopulateNameInDto"
dialect "mvel"
when
    map : HashMap() eval
    (
    checkIfNull(map)
    )
then
    setName(map);
end
</code>```

The code is running fine, the only problem is, when the thread sleeps for 20 seconds, in DroolsPoc.java file at line Thread.currentThread().sleep(20000);, then I am updating the poc.drl file from "The moon is out" to "The sun is out". So I am expecting this change to reflect when the program again runs after sleep.

Any help would be appreciated, Many Thanks in advance.

答:
It seems I had to recreate the service object and again import the file.
worked but this way is not optimal.</p>

```<code>Thread.currentThread().sleep(20000);
Map<String, Object> input1 = new HashMap<String, Object>();
input1.put("input", new Dto());
KieServices ks1 = KieServices.Factory.get();
KieFileSystem kfs1 = ks1.newKieFileSystem();

kfs1.write(ResourceFactory.newFileResource(new File(
        "C:/Users/workspace1/Drools_POC/src/poc.drl")));
ks1.newKieBuilder(kfs1).buildAll();
KieContainer kieContainer1 = ks.newKieContainer(ks.getRepository()
        .getDefaultReleaseId());

KieSession kieSession1 = kieContainer1.newKieSession();
kieSession1.insert(input1);
System.out.println("Fired all rules 1");

kieSession1.fireAllRules();
System.out.println(((Dto) input1.get("input")).getName());
</code>```

Body:
I am very very new to Drool, please forgive me if I have made any foolish mistake below. I am currently working on an application which is Ant based (migrating to maven is a high risk). I am trying to upgrade the drool version from 4.0.7 to 6.5.0. I want to dynamically get the updated version of the .drl file at runtime of java code so that I don't need to build the java files every time. Here is my below code.

DroolsPoc.java

package com.test;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import org.kie.api.KieServices;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;

public class DroolsPoc {

    private static AtomicBoolean isRulesChangeScanerStarted = new AtomicBoolean(
            false);

    public static void main(String[] args) throws InterruptedException {

        Map<String, Object> input = new HashMap<String, Object>();

        input.put("input", new Dto());

        KieServices ks = KieServices.Factory.get();

        KieFileSystem kfs = ks.newKieFileSystem();
        kfs.write(ResourceFactory.newFileResource(new File("C:/Users/workspace1/Drools_POC/src/poc.drl")));
        ks.newKieBuilder(kfs).buildAll();

        KieContainer kieContainer = ks.newKieContainer(ks.getRepository().getDefaultReleaseId());

        KieSession kieSession = kieContainer.newKieSession();
        kieSession.insert(input);
        System.out.println("Fired all rules 1");
        kieSession.fireAllRules();

        System.out.println(((Dto) input.get("input")).getName());

        Thread.currentThread().sleep(20000);

        /*The updated rule should get printed by below code*/
        KieSession kieSession1 = kieContainer.newKieSession();
        kieSession1.insert(input);
        System.out.println("Fired all rules 2");
        kieSession1.fireAllRules();

        System.out.println(((Dto) input.get("input")).getName());

    }

}

Dto.java

package com.test;

public class Dto {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

poc.drl

import java.util.Map;
import java.util.HashMap;
import com.test.Dto;

function Boolean checkIfNull(Map input){

  Dto dto = (Dto)input.get("input");

  if (null == dto.getName()){
      return true;
  }

      return false;

}

function void setName(Map input){

  Dto dto = (Dto)input.get("input");

  dto.setName("The moon is out");

}

rule "PopulateNameInDto"
dialect "mvel"
when
    map : HashMap() eval
    (
    checkIfNull(map)
    )
then
    setName(map);
end

The code is running fine, the only problem is, when the thread sleeps for 20 seconds, in DroolsPoc.java file at line Thread.currentThread().sleep(20000);, then I am updating the poc.drl file from "The moon is out" to "The sun is out". So I am expecting this change to reflect when the program again runs after sleep.

Any help would be appreciated, Many Thanks in advance.

Body:
It seems I had to recreate the service object and again import the file.
worked but this way is not optimal.

Thread.currentThread().sleep(20000);
Map<String, Object> input1 = new HashMap<String, Object>();
input1.put("input", new Dto());
KieServices ks1 = KieServices.Factory.get();
KieFileSystem kfs1 = ks1.newKieFileSystem();

kfs1.write(ResourceFactory.newFileResource(new File(
        "C:/Users/workspace1/Drools_POC/src/poc.drl")));
ks1.newKieBuilder(kfs1).buildAll();
KieContainer kieContainer1 = ks.newKieContainer(ks.getRepository()
        .getDefaultReleaseId());

KieSession kieSession1 = kieContainer1.newKieSession();
kieSession1.insert(input1);
System.out.println("Fired all rules 1");

kieSession1.fireAllRules();
System.out.println(((Dto) input1.get("input")).getName());


问:
Generate a pandas dataframe from ordereddict?
I am trying to create a pandas dataframe from an ordereddict to preserve the order of the values. But for some reason after creating the dataframe the fields are messed up again.

Here's the list of ordereddicts:

```<code>[OrderedDict([
  ('key_a',
  'value_a'),
  ('key_b',
  'value_b'),
]),
OrderedDict([
  ('key_a',
  'value_c'),
  ('key_b',
  'value_d'),
])
]
</code>```

Now how should I create a pandas DataFrame from these? What I am looking for is something like that (the important thing is the key_a and key_b etc column name order):

```<code>  key_a    key_b
0 value_a  value_b
1 value_c  value_d
</code>```

I have tried:

```<code>pd.DataFrame.from_records(orderedDictList)
pd.DataFrame.from_dict(orderedDictList)
</code>```

Feel free to ask any additional questions.

答:
Following this answer, you need to explicitly specify your column order:

```<code>df = pd.DataFrame(orderedDictList, columns=orderedDictList.keys())
</code>```

Of course, first you need to ensure that you have an ordered dictionary.

Body:
I am trying to create a pandas dataframe from an ordereddict to preserve the order of the values. But for some reason after creating the dataframe the fields are messed up again.

Here's the list of ordereddicts:

[OrderedDict([
  ('key_a',
  'value_a'),
  ('key_b',
  'value_b'),
]),
OrderedDict([
  ('key_a',
  'value_c'),
  ('key_b',
  'value_d'),
])
]

Now how should I create a pandas DataFrame from these? What I am looking for is something like that (the important thing is the key_a and key_b etc column name order):

  key_a    key_b
0 value_a  value_b
1 value_c  value_d

I have tried:

pd.DataFrame.from_records(orderedDictList)
pd.DataFrame.from_dict(orderedDictList)

Feel free to ask any additional questions.

Body:
Following this answer, you need to explicitly specify your column order:

df = pd.DataFrame(orderedDictList, columns=orderedDictList.keys())

Of course, first you need to ensure that you have an ordered dictionary.


问:
I am looking at way to create an accessibility label for a simple text box in Xamarin.Form using Visual Studio on MAC
I have tried using instructions from various forums but can't get it working. Any suggestions would be appreciated. Here is the sample code I am working on:                   " </p>

答:
Accessibility label will be available from the box in future XF release.
currently you can add this feature only by manual for your app:

see link - https://developer.xamarin.com/guides/xamarin-forms/advanced/accessibility/


问:
How can i display my results for my multiple choice quiz?
I'm making a multiple choice quiz and was wondering How I would be
able to display the answers. At the moment I've got it outputting how
many answers the user got correct (1,2,3 etc). I would like it to output the 3 choices under the question headings and color the correct one in bold. Here is the code I've done so far.

function check() {
  var question1 = document.quiz.question1.value;
  var question2 = document.quiz.question2.value;
  var question3 = document.quiz.question3.value;
  var correct = 0;

  if (question1 == "it") {
    correct++;
  }

  if (question2 == "stuff1") {
    correct++;
  }

  if (question3 == "stuff3") {
    correct++;
  }

  var messages = ["MLG!", "Okay...", "Git Gud"];
  var pictures = ["img/win.gif", "img/meh.gif", "img/lose.gif"];

  var range;

  if (correct < 1) {
    range = 2;
  }

  if (correct > 0 && correct < 3) {
    range = 1;
  }

  if (correct > 2) {
    range = 0;
  }

  document.getElementById("after_submit").style.visibility = "visible";
  document.getElementById("message").innerHTML = messages[range];
  document.getElementById("number_correct").innerHTML = "You got " +
    correct + " correct.";
  document.getElementById("picture").src = pictures[range];
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1> Random Quiz ! </h1>
<form id="quiz" name="quiz">
  <h2> How do you spell it? </h2>
  <input id="textbox" type="text" name="question1">
  <br>
  <h3> What is the colour of the sky? </h3>
  <input type="radio" id="MCQ" name="question2" value="stuff1"> Lime Green
  <br>
  <input type="radio" id="MCQ" name="question2" value="stuff2"> Neon Purple
  <br>
  <h4> Does looking at pictures of sun hurt your eyes? </h4>
  <input type="radio" id="MCQ" name="question3" value="stuff3"> Yes
  <br>
  <input type="radio" id="MCQ" name="question3" value="stuff4"> Maybe...
  <br>
  <input id="BTN" type="button" value="Next" onclick="check();">
</form>

<div id="after_submit">

  <p id="message"></p>
  <p id="number_correct"></p>
  <img id="picture">
</div></code>```

答:
To make your code easier, you could store the questions in an array:</p>

```<code>function check(){
var answers=[1,2,3].map(id=> document.quiz["question"+id]);
var solutions=["it","stuff2", "stuff3"];
var correct=0;
for(var i=0;i<solutions.length && i<answers.length;i++){
  if(answers[i].value===solutions[i]){
     correct++;
  }else{
   alert(" No! Question "+(i+1)+" was "+solutions[i]);
  }
}
//calc range + show emoji
}
</code>```

Body:
I'm making a multiple choice quiz and was wondering How I would be
able to display the answers. At the moment I've got it outputting how
many answers the user got correct (1,2,3 etc). I would like it to output the 3 choices under the question headings and color the correct one in bold. Here is the code I've done so far.

function check() {
  var question1 = document.quiz.question1.value;
  var question2 = document.quiz.question2.value;
  var question3 = document.quiz.question3.value;
  var correct = 0;

  if (question1 == "it") {
    correct++;
  }

  if (question2 == "stuff1") {
    correct++;
  }

  if (question3 == "stuff3") {
    correct++;
  }

  var messages = ["MLG!", "Okay...", "Git Gud"];
  var pictures = ["img/win.gif", "img/meh.gif", "img/lose.gif"];

  var range;

  if (correct < 1) {
    range = 2;
  }

  if (correct > 0 && correct < 3) {
    range = 1;
  }

  if (correct > 2) {
    range = 0;
  }

  document.getElementById("after_submit").style.visibility = "visible";
  document.getElementById("message").innerHTML = messages[range];
  document.getElementById("number_correct").innerHTML = "You got " +
    correct + " correct.";
  document.getElementById("picture").src = pictures[range];
}

 Random Quiz !

<form id="quiz" name="quiz">

 How do you spell it?

  <input id="textbox" type="text" name="question1">

 What is the colour of the sky?

  <input type="radio" id="MCQ" name="question2" value="stuff1"> Lime Green

  <input type="radio" id="MCQ" name="question2" value="stuff2"> Neon Purple

 Does looking at pictures of sun hurt your eyes?

  <input type="radio" id="MCQ" name="question3" value="stuff3"> Yes

  <input type="radio" id="MCQ" name="question3" value="stuff4"> Maybe...

  <input id="BTN" type="button" value="Next" onclick="check();">
</form>

Body:
To make your code easier, you could store the questions in an array:

function check(){
var answers=[1,2,3].map(id=> document.quiz["question"+id]);
var solutions=["it","stuff2", "stuff3"];
var correct=0;
for(var i=0;i<solutions.length && i<answers.length;i++){
  if(answers[i].value===solutions[i]){
     correct++;
  }else{
   alert(" No! Question "+(i+1)+" was "+solutions[i]);
  }
}
//calc range + show emoji
}


问:
Are there any compatibility issues in browsers when using identical CSS class identifiers for different elements?
I'm wondering if it is okay to use identical class names for parts in different "parent" (regarding CSS class) elements.

For example:

.section, .panel {
  background: black;
  padding: 8px;
  margin: 8px;
}

/* First .head */
.section .head{
  background: yellow;
}

/* Second .head */
.panel .head{
  background: lime;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="section">
  <div class="head">
    Section Head
  </div>
</div>

<div class="panel">
  <div class="head">
    Panel Head
  </div>
</div></code>```

Both, section and panel, have a header which has different styling but the same identifier ".head". I only define rules for ".head" when it is inside of the element ".section" or ".panel", but never for a plain ".head". So, now I'm wondering if this can cause any compatibility issues or is this perfectly acceptable across most browsers? (including IE8+)

答:
As long as you keep track of the classes, it should be ok. Its more readability than compatibility, so be carefull and dont overuse it.

Futhermore, when you are adding more styles also be carefull if styling one new feature, affects past ones due to repeated classes.

Body:
I'm wondering if it is okay to use identical class names for parts in different "parent" (regarding CSS class) elements.

For example:

.section, .panel {
  background: black;
  padding: 8px;
  margin: 8px;
}

/* First .head */
.section .head{
  background: yellow;
}

/* Second .head */
.panel .head{
  background: lime;
}

    Section Head

    Panel Head

Both, section and panel, have a header which has different styling but the same identifier ".head". I only define rules for ".head" when it is inside of the element ".section" or ".panel", but never for a plain ".head". So, now I'm wondering if this can cause any compatibility issues or is this perfectly acceptable across most browsers? (including IE8+)


问:
C# TrimEnd trimming too many chars
I'm seeing odd results when using string.TrimEnd() method

```<code>var s = "FDLBicester.freshviprint01";
var x = s.TrimEnd("freshviprint01".ToCharArray());
Console.WriteLine(x);
</code>```

Produces

FDLBicester.

However, slightly changing the TrimEnd to include the . as well:

```<code>var s = "FDLBicester.freshviprint01";
var x = s.TrimEnd(".freshviprint01".ToCharArray());
Console.WriteLine(x);
</code>```

Produces

FDLBic

????

Why am I losing ester by also trimming the .?

答:
when you put

```<code>  var x = s.TrimEnd(".freshviprint01".ToCharArray());
</code>```

you actually want to remove all the trailing characters from {'.', '0', '1', 'e', 'f', 'h', 'i', 'i', 'n', 'p', 'r', 'r', 's', 't', 'v'} set (c i s the first character that's not in the set):

```<code>  "FDLBicester.freshviprint01" -> "FDLBic"
</code>```

please, notice that all the characters in the icester are presented in the set and that's why are trimmed out. You, probably, want to cut off some suffix, like this:

```<code>  var s = "FDLBicester.freshviprint01";
  var suffix = ".freshviprint01";

  var x = s.EndsWith(suffix)
    ? s.Substring(0, s.Length - suffix.Length)
    : s;
</code>```

Title: C# TrimEnd trimming too many chars

Body:
I'm seeing odd results when using string.TrimEnd() method

var s = "FDLBicester.freshviprint01";
var x = s.TrimEnd("freshviprint01".ToCharArray());
Console.WriteLine(x);

Produces

FDLBicester.

However, slightly changing the TrimEnd to include the . as well:

var s = "FDLBicester.freshviprint01";
var x = s.TrimEnd(".freshviprint01".ToCharArray());
Console.WriteLine(x);

Produces

FDLBic

????

Why am I losing ester by also trimming the .?

Body:
when you put

  var x = s.TrimEnd(".freshviprint01".ToCharArray());

you actually want to remove all the trailing characters from {'.', '0', '1', 'e', 'f', 'h', 'i', 'i', 'n', 'p', 'r', 'r', 's', 't', 'v'} set (c i s the first character that's not in the set):

  "FDLBicester.freshviprint01" -> "FDLBic"

please, notice that all the characters in the icester are presented in the set and that's why are trimmed out. You, probably, want to cut off some suffix, like this:

  var s = "FDLBicester.freshviprint01";
  var suffix = ".freshviprint01";

  var x = s.EndsWith(suffix)
    ? s.Substring(0, s.Length - suffix.Length)
    : s;


问:
Espressif Wifi not connecting or showing AP
First of all, I won't go into details, cause there are a lot of them, and I dont want to write (a too long) essay. There is TL;DR section at the end, because I have a specific question, but maybe some additional info can help.

I have a device that is made of a GRU (glass room unit) and espressif (esp8266).

GRU and esp8266 communicate via serial, with GRU as master. GRU is programmed with an internal tool, and I can monitor everything on it, including the info it gets from esp8266.
There is a test/development device, that has espressif on top of the GRU, so I can easily take it off, reprogram/reconfigure it, and put it on.

Espressif is inside of a GRU, and downloading stuff to flash is a real pain. There is whole process including a OS switch (from Win7 to Linux and back). Console output on espressif cannot be done, or at least not in the time frame I have.

For esp8266 I use non-os SDK V2.0.0_16_08_10.

Espressif can be configured with downloading a configuration to flash, or via UDP (over a network if connected, over its AP if its not connected).

Algorithm for Wifi:

```<code> 1. Try to connect to a network from configuration
 2. If it succeeds, raise a flag for that
 3. If it fails, enter dual (STATION+AP) mode and raise a flag for that
</code>```

The reason espressif is not always in dual mode is that it affects multi-cast operations.

Configuration over network is done by a Java aplication I wrote.

Scenario 1

I've configured a wifi router, configured all (x19) of the devices (espressif in devices that is) to connect to its network. When I turned them on, they would connect one by one. The ones that didn't entered dual mode and could be configured via the app.

All well.

Scenario 2
I've wanted to test the system in real world, so I reconfigured them to connect to the our firms network. Additionally when I was already going thru the whole process I've downloaded latest firmare to flash.

I expected that they would connect or enter dual mode and create their own APs. But they did not.

I tested then the code and configuration on espressif whose console output I could monitor, and everything worked.

I tested then the code and configuration on the test device, and it worked again.

I've then redownloaded the code and configuration to one device, and it didn't work.

TL;DR
I have two devices, espressif on a GRU and espressif inside of a GRU. Both connected to one network. Esp on a GRU work for another, Esp inside of a GRU doesn't work for that other network.
They have identical code and configuration, so it shouldn't be a software issue.

Does having espressif inside of a device jams its signal enough that it can't go trough? Device is not big (5x5x2cm).

UPDATE 1:
While I was writing, the espressif inside of a GRU managed to connect to network. I then restarted it so I can check that it can do it again, and it can't connect again.
It took me about 10 minutes to write the whole question.

答:
There are two things that seem to have caused the problem.

When I removed gpio_init(), network stuff became faster, much much faster. Everything on it, connecting to AP, creating AP etc...

I've changed my config and wifi code, so that it now stores the ap and station config to flash via API.

I only check if its internal config is the same as mine from flash. If it isn't, it saves it. Now, I only control the current opmode.

Body:
First of all, I won't go into details, cause there are a lot of them, and I dont want to write (a too long) essay. There is TL;DR section at the end, because I have a specific question, but maybe some additional info can help.

I have a device that is made of a GRU (glass room unit) and espressif (esp8266).

GRU and esp8266 communicate via serial, with GRU as master. GRU is programmed with an internal tool, and I can monitor everything on it, including the info it gets from esp8266.
There is a test/development device, that has espressif on top of the GRU, so I can easily take it off, reprogram/reconfigure it, and put it on.

Espressif is inside of a GRU, and downloading stuff to flash is a real pain. There is whole process including a OS switch (from Win7 to Linux and back). Console output on espressif cannot be done, or at least not in the time frame I have.

For esp8266 I use non-os SDK V2.0.0_16_08_10.

Espressif can be configured with downloading a configuration to flash, or via UDP (over a network if connected, over its AP if its not connected).

Algorithm for Wifi:

 1. Try to connect to a network from configuration
 2. If it succeeds, raise a flag for that
 3. If it fails, enter dual (STATION+AP) mode and raise a flag for that

The reason espressif is not always in dual mode is that it affects multi-cast operations.

Configuration over network is done by a Java aplication I wrote.

Scenario 1

I've configured a wifi router, configured all (x19) of the devices (espressif in devices that is) to connect to its network. When I turned them on, they would connect one by one. The ones that didn't entered dual mode and could be configured via the app.

All well.

Scenario 2
I've wanted to test the system in real world, so I reconfigured them to connect to the our firms network. Additionally when I was already going thru the whole process I've downloaded latest firmare to flash.

I expected that they would connect or enter dual mode and create their own APs. But they did not.

I tested then the code and configuration on espressif whose console output I could monitor, and everything worked.

I tested then the code and configuration on the test device, and it worked again.

I've then redownloaded the code and configuration to one device, and it didn't work.

TL;DR
I have two devices, espressif on a GRU and espressif inside of a GRU. Both connected to one network. Esp on a GRU work for another, Esp inside of a GRU doesn't work for that other network.
They have identical code and configuration, so it shouldn't be a software issue.

Does having espressif inside of a device jams its signal enough that it can't go trough? Device is not big (5x5x2cm).

UPDATE 1:
While I was writing, the espressif inside of a GRU managed to connect to network. I then restarted it so I can check that it can do it again, and it can't connect again.
It took me about 10 minutes to write the whole question.