问:
How do I send a variable name and its value to the server and receive back a calculated response
I am new to wordpress and plugins but have a reasonable grip on php, javascript and html. I have created a plugin for wordpress which generates a page (form) which gathers information regarding a product specification. [It is actually a number of sequential forms, but for simplicity lets say it is one.  I do not want to "submit" the form as there are many fields on each form and I do not want to "submit" until it is completed and they are ready to move to the next form].

I would like to be able to (re)calculate the product price when the user changes a parameter. To do this I would like to be able to pass the name of the changed parameter and its value back to the server (where all of the dependant data for the calculation is stored), and do the calculation and return the new price. At present I have a javascript function which is called with the pertinent data on an "onChange" and then modifies the div which represents the total price. this works if I compute the value locally, but now I am looking to complete the function by sending data to the server and receiving the calculated response e.g. :

```<code>function total_price(arg,value) {

   ***** send arg and value to server *****

   ***** receive total_price back from server *****

    var total_div = document.getElementById("total_price");
    total_div.innerHTML = "£"+total_price;
}
</code>```

What code should I be putting in here and what should I have on the server in order to receive the data, do the calculation and send back the result?

答:
I mostly have jQuery loaded in the front-end, so I'll post an answer using the jQuery framework. You'll most probably find a good vanilla snippet elsewhere if you're not looking to load a javascript library.

Front End

```<code>var html_price = 1; // Whatever you need here

// You'll notice that the ajaxurl variable below, is sent to the front-end in the second code snippet of this answer
$.post( ajaxurl, {
    action: "get_total_price", // action is a special parameter Wordpress is listening for
    price: html_price
}).done( function( price ) {
    // Price back from the server you can use in the DOM
    // You should probably send this using JSON, this example only uses a string
    console.log( price );
});
</code>```

Back End

```<code>// Here is where Wordpress is waiting for that special action parameter
// https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

add_action( 'wp_ajax_get_total_price', 'get_total_price' );
add_action( 'wp_ajax_nopriv_get_total_price', 'get_total_price' );

function get_total_price() {
    $price = $_POST[ 'price' ];

    if( $price ) {

        // do with the price what you want
        echo $price; // Echo instead of return
        exit; // Remember to close up the server response here

    } else {

        echo '0'; // Unrealistic, but guarantees a response
        exit;

    }
}

// Send the AJAX URL to the front end. There are more elegant ways to do this, but for the purpose of this answer, this should work.
add_action( 'wp_head', 'add_ajaxurl_to_head' );
function add_ajaxurl_to_head() { ?>
    <script>
        ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
    </script>
<?php }
</code>```

Body:
I am new to wordpress and plugins but have a reasonable grip on php, javascript and html. I have created a plugin for wordpress which generates a page (form) which gathers information regarding a product specification. [It is actually a number of sequential forms, but for simplicity lets say it is one.  I do not want to "submit" the form as there are many fields on each form and I do not want to "submit" until it is completed and they are ready to move to the next form].

I would like to be able to (re)calculate the product price when the user changes a parameter. To do this I would like to be able to pass the name of the changed parameter and its value back to the server (where all of the dependant data for the calculation is stored), and do the calculation and return the new price. At present I have a javascript function which is called with the pertinent data on an "onChange" and then modifies the div which represents the total price. this works if I compute the value locally, but now I am looking to complete the function by sending data to the server and receiving the calculated response e.g. :

function total_price(arg,value) {

   ***** send arg and value to server *****

   ***** receive total_price back from server *****

    var total_div = document.getElementById("total_price");
    total_div.innerHTML = "£"+total_price;
}

What code should I be putting in here and what should I have on the server in order to receive the data, do the calculation and send back the result?

Body:
I mostly have jQuery loaded in the front-end, so I'll post an answer using the jQuery framework. You'll most probably find a good vanilla snippet elsewhere if you're not looking to load a javascript library.

Front End

var html_price = 1; // Whatever you need here

// You'll notice that the ajaxurl variable below, is sent to the front-end in the second code snippet of this answer
$.post( ajaxurl, {
    action: "get_total_price", // action is a special parameter Wordpress is listening for
    price: html_price
}).done( function( price ) {
    // Price back from the server you can use in the DOM
    // You should probably send this using JSON, this example only uses a string
    console.log( price );
});

Back End

// Here is where Wordpress is waiting for that special action parameter
// https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

add_action( 'wp_ajax_get_total_price', 'get_total_price' );
add_action( 'wp_ajax_nopriv_get_total_price', 'get_total_price' );

function get_total_price() {
    $price = $_POST[ 'price' ];

    if( $price ) {

        // do with the price what you want
        echo $price; // Echo instead of return
        exit; // Remember to close up the server response here

    } else {

        echo '0'; // Unrealistic, but guarantees a response
        exit;

    }
}

// Send the AJAX URL to the front end. There are more elegant ways to do this, but for the purpose of this answer, this should work.
add_action( 'wp_head', 'add_ajaxurl_to_head' );
function add_ajaxurl_to_head() { ?>
    <script>
        ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
    </script>
<?php }


来源: stackexchange

问:
Change webpage content?
Sorry if this is a noob question, but I am new in the world of python, so I'm sorry.
I have a camera controlled by a python code.I want to count every person who pass the camera and show the number on a web page.
The object recognition algorithm and motion detection is working ok, but now I want to make a live preview on a webpage.
So in the while(true) from the python I want to call a function that changes the number of people that passed the camera on the web page without refreshing the webpage.
If anyone can give me a suggestion or a tutorial I will be grateful forever!

答: Save the number of passed people into a file accessible in webserver. You can retrieve this file by ajax embedded into your webpage. </p>

ContentLicense: CC BY-SA 3.0

Title: Change webpage content?


问:
Contact form works, sends email, information is missing
I created this contact form from below. Everything works great up to the point where I am trying to add another section to the “body” in the email form. The first message works that appends to the body, but I cannot get say another section in the HTML form to work.

What is wrong with this form? Thank you for your help.

```<code><form method="post" action="emailform.php">
    <fieldset>
        <ul>
        <li>
        <label for="name">Your Name:</label>
        <input type="text" name="name" id="name"class="large" required="required" placeholder="Enter your name"/></li><!--Basically gave a name here-->

        <li>
        <label for="idlabel">Your Email:</label>
        <input type="email" name="email"  placeholder="Enter your email"/></li><!--Basically gave a name here-->

         <label for="message2"> <textarea name="message2" maxlength="800" rows="6"
        cols="23"></textarea></li></ul>

        <li><label for="message">Enter Your Message Below</label>
            <textarea name="message" maxlength="800" rows="6"
        cols="23"></textarea></li></ul><!--Basically gave a name here and removed label as name-->

        <input type="submit" value="Submit"/>
    </fieldset>
</form>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Emailing Form Data</title>
    <style type="text/css">

    body {
        font-size: 100%;
        font-family: Arial, sans-serif;
    }
    </style>
</head>
<body>

<?php

if (empty($_POST)) {
    print "<p>No data was submitted.</p>";
    print "</body></html>";
    exit();
}

/* Creates function that removes magic escaping, if it's been applied, from values and then removes extra newlines and returns to foil spammers. Thanks Larry Ullman! */
function clear_user_input($value) {
    if (get_magic_quotes_gpc()) $value=stripslashes($value);
    $value= str_replace( "\n", '', trim($value));
    $value= str_replace( "\r", '', $value);
    return $value;
}

/* Create body of email message by cleaning each field and then appending each name and value to it. */

$body ="Here is the data that was submitted:\n";
//Fetching the form fields here
$email = $_REQUEST['email'];
$name = $_REQUEST['name'];
$message2 = $_REQUEST['message2'];
$message = $_REQUEST['message'];

/* Removes newlines and returns from $email and $name so they can't smuggle extra email addresses for spammers */
$email   = clear_user_input($email);
$name    = clear_user_input($name);

$body   .= clear_user_input($message); + clear_user_input($message2); //Appending the message to the body of the email

/* Create header that puts email in From box along with name in parentheses and sends Bcc to alternate address. Change yourmail@yourdomain.com to the Bcc email address you want to include. */
$from='From: '. $email . "(" . $name . ")" . "\r\n" . 'Bcc: yourmail@yourdomain.com' . "\r\n";

// Creates intelligible subject line that also shows me where it came from
$subject = 'New User Sign Up!';

/* Sends mail to the address below with the form data submitted above. Replace yourmail@yourdomain.com with the email address to which you want the data sent. */
mail ('yourmail@yourdomain.com', $subject, $body, $from);
?>

<p>Thank you.</p>

</body>
</html>
</code>```

答:
Change

$body .= clear_user_input($message); + clear_user_input($message2);

to

$body .= clear_user_input($message).clear_user_input($message2);

Also you might want to add lots of checks on validity of all passed values (valid emails, empty values ect..), as it is you will get lots of empty or spammy messages.

Body:
I created this contact form from below. Everything works great up to the point where I am trying to add another section to the “body” in the email form. The first message works that appends to the body, but I cannot get say another section in the HTML form to work.

What is wrong with this form? Thank you for your help.

<form method="post" action="emailform.php">
    <fieldset>

        Your Name:
        <input type="text" name="name" id="name"class="large" required="required" placeholder="Enter your name"/>

        Your Email:
        <input type="email" name="email"  placeholder="Enter your email"/>

          <textarea name="message2" maxlength="800" rows="6"
        cols="23"></textarea>

Enter Your Message Below
            <textarea name="message" maxlength="800" rows="6"
        cols="23"></textarea>

        <input type="submit" value="Submit"/>
    </fieldset>
</form>

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Emailing Form Data</title>

<?php

if (empty($_POST)) {
    print "
No data was submitted.
";
    print "";
    exit();
}

/* Creates function that removes magic escaping, if it's been applied, from values and then removes extra newlines and returns to foil spammers. Thanks Larry Ullman! */
function clear_user_input($value) {
    if (get_magic_quotes_gpc()) $value=stripslashes($value);
    $value= str_replace( "\n", '', trim($value));
    $value= str_replace( "\r", '', $value);
    return $value;
}

/* Create body of email message by cleaning each field and then appending each name and value to it. */

$body ="Here is the data that was submitted:\n";
//Fetching the form fields here
$email = $_REQUEST['email'];
$name = $_REQUEST['name'];
$message2 = $_REQUEST['message2'];
$message = $_REQUEST['message'];

/* Removes newlines and returns from $email and $name so they can't smuggle extra email addresses for spammers */
$email   = clear_user_input($email);
$name    = clear_user_input($name);

$body   .= clear_user_input($message); + clear_user_input($message2); //Appending the message to the body of the email

/* Create header that puts email in From box along with name in parentheses and sends Bcc to alternate address. Change yourmail@yourdomain.com to the Bcc email address you want to include. */
$from='From: '. $email . "(" . $name . ")" . "\r\n" . 'Bcc: yourmail@yourdomain.com' . "\r\n";

// Creates intelligible subject line that also shows me where it came from
$subject = 'New User Sign Up!';

/* Sends mail to the address below with the form data submitted above. Replace yourmail@yourdomain.com with the email address to which you want the data sent. */
mail ('yourmail@yourdomain.com', $subject, $body, $from);
?>

Thank you.


问:
How to I catch and handle a fatal error when Py_initialize fails?
I am embedding python in a C++ dll (so ultimately I can put it in an xll). When the setup is wrong Py_Initialize is documented as terminally failing - see http://docs.python.org/c-api/init.html, "...it is a fatal error if the initialization fails.".

Is it possible to catch this error and how?

Thinking maybe a global windows hook?

答:
At the moment, Jason's solution seems to be the only way, but this doesn't cover cases where Python fails due to a fatal error somewhere later after Py_Initialize(), so there's no way for the embedding application to handle it in a more graceful manner (show GUI message and only then abort).

I've created a patch and issue in the Python bug tracker, cross-referencing this question: http://bugs.python.org/issue30560


问:
I can't resize numpy.ndarrays
I know that several questions have been asked about numpy.resize(array, new_size), but it's not doing anything for me. Right now, I have x_array.shape == (1456, 26) and x_array.shape == (1456, 1). I need a way to make their shapes equal. I have tried np.resize(x_array, y_array.shape) but it's not doing anything (no errors, no change). Is it even possible to change the shape like that? Both are numpy.ndarray types. Thank you.</p>

答:
While it's technically possible to resize a numpy array with numpy.resize (see this answer, for example), it's usually much more convenient to use powerful numpy array indexing to achieve the same goal of transforming an ndarray's shape.

So, if your problem is

I need a way to make their shapes equal,

there are two possible solutions:

You want to extend y_array. To do that just create a new array y_ext, and copy elements from y_array into it:

```<code>y_ext = numpy.zeros((1456,26))   # y_ext.shape == (1456,26)
y_ext[:,0] = y_array[:,0]
</code>```

You want to trim x_array. It's even simpler:

```<code>x_trimmed = x_array[:,0]     # x_trimmed.shape == (1456,)
y_trimmed = y_array[:,0]     # y_trimmed.shape == (1456,)
</code>```

Note that in the latter case x_trimmed shape is (1456,), not (1456,1). That's why y_array is "trimmed" too (it becomes 1-dim array), so x_trimmed and y_trimmed shapes become truly equal.

Title: I can't resize numpy.ndarrays

Body:
While it's technically possible to resize a numpy array with numpy.resize (see this answer, for example), it's usually much more convenient to use powerful numpy array indexing to achieve the same goal of transforming an ndarray's shape.

So, if your problem is

I need a way to make their shapes equal,

there are two possible solutions:

You want to extend y_array. To do that just create a new array y_ext, and copy elements from y_array into it:

y_ext = numpy.zeros((1456,26))   # y_ext.shape == (1456,26)
y_ext[:,0] = y_array[:,0]

You want to trim x_array. It's even simpler:

x_trimmed = x_array[:,0]     # x_trimmed.shape == (1456,)
y_trimmed = y_array[:,0]     # y_trimmed.shape == (1456,)

Note that in the latter case x_trimmed shape is (1456,), not (1456,1). That's why y_array is "trimmed" too (it becomes 1-dim array), so x_trimmed and y_trimmed shapes become truly equal.


问:
cocos2d vector with CallFunc callbacks. Losing memory
I got vector at mainScene:

```<code>std::vector<CallFunc*> callbacksToSchedule;
</code>```

At init() method:

```<code>auto updateCallBack = CallFunc::create([](){log("hello");});
updateCallBack->setTag(100);
callbacksToSchedule.push_back(updateCallBack);
Director::getInstance()->getScheduler()->schedule([this](float dt) {
                                                      for(auto callFunc: callbacksToSchedule){
                                                          log(std::to_string(callFunc->getTag()).c_str());
                                                          callFunc->execute();
                                                      }
                                                  }, this,
                   RESOURCES_UPDATE_TIME, true, "schedulerKey");
</code>```

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

And output:

1952803683

But should be:

100

答:
updateCallBack released when the init() ends.  purged from memory because retainCount is zero. When you need them in an instance variable you've to retain them.

```<code>auto updateCallBack = CallFunc::create([](){log("hello");});
updateCallBack->setTag(100);
updateCallBack->retain();                      // retain updateCallBack
callbacksToSchedule.push_back(updateCallBack);
Director::getInstance()->getScheduler()->schedule([this](float dt) {

        for(auto callFunc: callbacksToSchedule){
            CCLOG("%d TAG VALUE",callFunc->getTag());
            callFunc->execute();
        }
    }, this,RESOURCES_UPDATE_TIME, true, "schedulerKey");
</code>```

Body:
I got vector at mainScene:

std::vector<CallFunc*> callbacksToSchedule;

At init() method:

auto updateCallBack = CallFunc::create([](){log("hello");});
updateCallBack->setTag(100);
callbacksToSchedule.push_back(updateCallBack);
Director::getInstance()->getScheduler()->schedule([this](float dt) {
                                                      for(auto callFunc: callbacksToSchedule){
                                                          log(std::to_string(callFunc->getTag()).c_str());
                                                          callFunc->execute();
                                                      }
                                                  }, this,
                   RESOURCES_UPDATE_TIME, true, "schedulerKey");

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

And output:

1952803683

But should be:

100

Body:
updateCallBack released when the init() ends.  purged from memory because retainCount is zero. When you need them in an instance variable you've to retain them.

auto updateCallBack = CallFunc::create([](){log("hello");});
updateCallBack->setTag(100);
updateCallBack->retain();                      // retain updateCallBack
callbacksToSchedule.push_back(updateCallBack);
Director::getInstance()->getScheduler()->schedule([this](float dt) {

        for(auto callFunc: callbacksToSchedule){
            CCLOG("%d TAG VALUE",callFunc->getTag());
            callFunc->execute();
        }
    }, this,RESOURCES_UPDATE_TIME, true, "schedulerKey");


问:
Send JSON from javascript to REST and add the content to database
I am currently parsing a csv file to JSON format with help of PapaParser in javascript. I want to send this parsed JSON data using AJAX to a RESTful service which in turn will have to send the data to MySQL database.

I am not able to send the data to the RESTful service.

My javascript code is:`

$('#submit').click(function()
{
  $("input[type=file]").parse({
    config:
    {
      delimiter:",",
      header: true,
      dynamicTyping: true,
      skipEmptyLines: false,
      complete: function(result, file)
      {
        console.log("This file done:", file);
        var emp=(JSON.stringify(result.data, null, 4));

        $.ajax( {
         url: 'http://localhost:8100/department/v1',
         data: result.data,
         datatype : "application/json",
         type: 'POST',
         dataType: 'JSON',
         success: function( returnObj ) {
          //FunctionDefinitionHere
          console.log(result.data);
         }
       });
   }
 }
});

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
 <title>Add Employee | Allowance Processing System</title>
 <script type="text/javascript" src="PapaParse/jquery-3.2.1.js"></script>
<script type="text/javascript" src="PapaParse/jquery-3.2.1.min.js"></script>

</head>
<body>
 <p>Select an Excel Sheet with Employee Details</p>
 <br/>
 <form action="#" method="POST">
  <input type="file" name="file" id="file" accept=".csv" />
  <input type="submit" id="submit">
 </form>
 <script type="text/javascript" src="parse.js"></script>
<script type="text/javascript" src="PapaParse/papaparse.js"></script>
<script type="text/javascript" src="PapaParse/papaparse.min.js"></script>
</body>
</html></code>```

`

答:
You have 2 dataType properties. I suspect you want contentType to be json which also requires you to send stringified data

Try

```<code>$.ajax({
  url: 'http://localhost:8100/department/v1',
  data: emp, // stringified json
  contentType: "application/json",
  type: 'POST',
  dataType: 'JSON',
  success: function(returnObj) {
    //FunctionDefinitionHere
    console.log(returnObj);
  }
});
</code>```

Also add an error handler to help debug

Body:
I am currently parsing a csv file to JSON format with help of PapaParser in javascript. I want to send this parsed JSON data using AJAX to a RESTful service which in turn will have to send the data to MySQL database.

I am not able to send the data to the RESTful service.

My javascript code is:`

$('#submit').click(function()
{
  $("input[type=file]").parse({
    config:
    {
      delimiter:",",
      header: true,
      dynamicTyping: true,
      skipEmptyLines: false,
      complete: function(result, file)
      {
        console.log("This file done:", file);
        var emp=(JSON.stringify(result.data, null, 4));

        $.ajax( {
         url: 'http://localhost:8100/department/v1',
         data: result.data,
         datatype : "application/json",
         type: 'POST',
         dataType: 'JSON',
         success: function( returnObj ) {
          //FunctionDefinitionHere
          console.log(result.data);
         }
       });
   }
 }
});

});

<!DOCTYPE html>

 <title>Add Employee | Allowance Processing System</title>

Select an Excel Sheet with Employee Details

 <form action="#" method="POST">
  <input type="file" name="file" id="file" accept=".csv" />
  <input type="submit" id="submit">
 </form>

`

Body:
You have 2 dataType properties. I suspect you want contentType to be json which also requires you to send stringified data

Try

$.ajax({
  url: 'http://localhost:8100/department/v1',
  data: emp, // stringified json
  contentType: "application/json",
  type: 'POST',
  dataType: 'JSON',
  success: function(returnObj) {
    //FunctionDefinitionHere
    console.log(returnObj);
  }
});

Also add an error handler to help debug


问:
Case object extending class with constructor in Scala
I am a beginner in Scala and was playing around to learn more about Abstract data types. I defined the following definition to replicate Option type:

```<code>sealed abstract class Maybe[+A](x:A)
case object Nothing extends Maybe[Nothing](Nothing)
case class Just[A](x:A) extends Maybe[A](x)
</code>```

But I encountered the following error.

```<code>found   : Nothing.type
required: Nothing
    case object Nothing extends Maybe[Nothing](Nothing)
</code>```

How do I pass Nothing instead of Nothing.type?

I referred to the following question for hints:
How to extend an object in Scala with an abstract class with constructor?, but it was not helpful.

答:
This is a bit of clarification for Assaf Mendelson's answer, but it's too big for a comment.

```<code>case object Nothing extends Maybe[Nothing](Nothing)
</code>```

Scala has separate namespaces for types and values. Nothing in case object Nothing is a value. Nothing in Maybe[Nothing] is a type. Since you didn't define a type called Nothing, it refers to the automatically imported scala.Nothing and you must pass a value of this type as an argument. By definition it has no values but e.g. case object Nothing extends Maybe[Nothing](throw new Exception) would compile, as the type of throw expressions is Nothing. Instead you pass the value Nothing, i.e. the same case object you are defining; its type is written as Nothing.type.

Body:
I am a beginner in Scala and was playing around to learn more about Abstract data types. I defined the following definition to replicate Option type:

sealed abstract class Maybe[+A](x:A)
case object Nothing extends Maybe[Nothing](Nothing)
case class Just[A](x:A) extends Maybe[A](x)

But I encountered the following error.

found   : Nothing.type
required: Nothing
    case object Nothing extends Maybe[Nothing](Nothing)

How do I pass Nothing instead of Nothing.type?

I referred to the following question for hints:
How to extend an object in Scala with an abstract class with constructor?, but it was not helpful.

Body:
This is a bit of clarification for Assaf Mendelson's answer, but it's too big for a comment.

case object Nothing extends Maybe[Nothing](Nothing)

Scala has separate namespaces for types and values. Nothing in case object Nothing is a value. Nothing in Maybe[Nothing] is a type. Since you didn't define a type called Nothing, it refers to the automatically imported scala.Nothing and you must pass a value of this type as an argument. By definition it has no values but e.g. case object Nothing extends Maybe[Nothing](throw new Exception) would compile, as the type of throw expressions is Nothing. Instead you pass the value Nothing, i.e. the same case object you are defining; its type is written as Nothing.type.


问:
SQL Query to check if student1 has a course with student 2
I have one table and I need to check if two users, for whom I have the IDs (e.g. 20 and 21) share the same course, just true or false.

```
Table: jos_gj_users
Columns: id_user, id_group

Data Example: (20; 4)
              (20; 5)
              (20; 6)
              (21; 6)
              (21; 7)
```

The data above shows that user 20 and user 21 share the course 6 but how do I get this with SQL just by entering the IDs and without looping through the results with PHP?

答:
Give this a try - it accepts the input parameters in the first bolded area, and returns a value of TRUE or FALSE via a CASE statement based on the values in the second bolded areas.

SELECT DISTINCT CASE WHEN

  (SELECT DISTINCT COUNT(id_group) FROM jos_gj_users WHERE id_user IN (20, 21)
 GROUP BY id_group

  HAVING COUNT(DISTINCT id_user) = 2) IS NOT NULL THEN 'TRUE'

  ELSE 'FALSE'

  END

  FROM jos_gj_users

ContentLicense: CC BY-SA 2.5

Body:
I have one table and I need to check if two users, for whom I have the IDs (e.g. 20 and 21) share the same course, just true or false.

Table: jos_gj_users
Columns: id_user, id_group

Data Example: (20; 4)
              (20; 5)
              (20; 6)
              (21; 6)
              (21; 7)

The data above shows that user 20 and user 21 share the course 6 but how do I get this with SQL just by entering the IDs and without looping through the results with PHP?


答:
You can use $reduce to collect all the devices inside all rooms across all floors in a single document in 3.4 version.

The below query has two parts inner reduce and outer reduce.

The inner reduce will collect all the devices, $reducing one room at a time and concatenating with the previous room's devices arrays in a single floor element.

The output from the inner reduce is piped to the outer $reduce to concat devices across all floors.

Something like

```<code>db.collection.aggregate(
    [{
        "$project": {
            "_id": 0,
            "devices": {
                "$reduce": {
                    "input": "$floors",
                    "initialValue": [],
                    "in": {
                        "$concatArrays": [
                            "$$value",
                            {
                                "$reduce": {
                                    "input": "$$this.rooms",
                                    "initialValue": [],
                                    "in": {
                                        "$concatArrays": [
                                            "$$value",
                                            "$$this.devices"
                                        ]
                                    }
                                }
                            }
                        ]
                    }
                }
            }
        }
    }]
)
</code>```

For MongoDB Version < 3.4

You can use the below pipeline. Use preserveNullAndEmptyArrays option on $unwind to prevent pipeline from dropping documents when any of the below arrays is missing, null or empty.

```<code>db.collection.aggregate(
    [
      { "$unwind": "$floors" },
      { "$unwind": "$floors.rooms" },
      { "$unwind": "$floors.rooms.devices" },
      { "$group":{ "_id":"$_id", "devices":{ "$push":"$floors.rooms.devices"} } }
    ]
)
</code>```

Title: MongoDB query embedded document array

Body:
I have the following document:

{
    "_id" : ObjectId("59299670266cc82a042f3817"),
    "_userId" : ObjectId("590a08dba07c1a1bee87b310"),
    "name" : "My home",
    "floors" : [
        {
            "_id" : ObjectId("59299670266cc82a042f4541"),
            "name" : "Floor 1",
            "rooms" : [
                {
                    "_id" : ObjectId("59299670266cc82a042f4551"),
                    "name" : "Room 1",
                    "devices" : [
                        {
                            "_id" : ObjectId("59299670266cc82a042f4561"),
                            "name" : "Device 1"
                        },
                        {
                            "_id" : ObjectId("59299670266cc82a042f4562"),
                            "name" : "Device 2"
                        }
                    ]
                },
                {
                    "_id" : ObjectId("59299670266cc82a042f4552"),
                    "name" : "Room 2",
                    "devices" : [
                        {
                            "_id" : ObjectId("59299670266cc82a042f4563"),
                            "name" : "Device 3"
                        },
                        {
                            "_id" : ObjectId("59299670266cc82a042f4564"),
                            "name" : "Device 4"
                        }
                    ]
                }
            ]
        },
        {
            "_id" : ObjectId("59299670266cc82a042f4542"),
            "name" : "Floor 2",
            "rooms" : [
                {
                    "_id" : ObjectId("59299670266cc82a042f4553"),
                    "name" : "Room 1",
                    "devices" : [
                        {
                            "_id" : ObjectId("59299670266cc82a042f4565"),
                            "name" : "Device 5"
                        },
                        {
                            "_id" : ObjectId("59299670266cc82a042f4566"),
                            "name" : "Device 6"
                        }
                    ]
                },
                {
                    "_id" : ObjectId("59299670266cc82a042f4554"),
                    "name" : "Room 2",
                    "devices" : [
                        {
                            "_id" : ObjectId("59299670266cc82a042f4567"),
                            "name" : "Device 7"
                        },
                        {
                            "_id" : ObjectId("59299670266cc82a042f4568"),
                            "name" : "Device 8"
                        }
                    ]
                }
            ]
        }
    ]
}

And I would like to get a list of all devices:

[
    {
        "_id" : ObjectId("59299670266cc82a042f4561"),
        "name" : "Device 1"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4562"),
        "name" : "Device 2"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4563"),
        "name" : "Device 3"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4564"),
        "name" : "Device 4"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4565"),
        "name" : "Device 5"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4566"),
        "name" : "Device 6"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4567"),
        "name" : "Device 7"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4568"),
        "name" : "Device 8"
    }
]

Is that possible with MongoDB?

I've tried it with aggregate and { $unwind: $floors.rooms.devices } or

{ $unwind: $floors }
{ $unwind: $floors.rooms }
{ $unwind: $floors.rooms.devices }

but the output is always empty. I don't know if I would get the output I want with $unwind at all.

Because I'm also using aggregate for other things a solution with it would be nice.

Body:
You can use $reduce to collect all the devices inside all rooms across all floors in a single document in 3.4 version.

The below query has two parts inner reduce and outer reduce.

The inner reduce will collect all the devices, $reducing one room at a time and concatenating with the previous room's devices arrays in a single floor element.

The output from the inner reduce is piped to the outer $reduce to concat devices across all floors.

Something like

db.collection.aggregate(
    [{
        "$project": {
            "_id": 0,
            "devices": {
                "$reduce": {
                    "input": "$floors",
                    "initialValue": [],
                    "in": {
                        "$concatArrays": [
                            "$$value",
                            {
                                "$reduce": {
                                    "input": "$$this.rooms",
                                    "initialValue": [],
                                    "in": {
                                        "$concatArrays": [
                                            "$$value",
                                            "$$this.devices"
                                        ]
                                    }
                                }
                            }
                        ]
                    }
                }
            }
        }
    }]
)

For MongoDB Version < 3.4

You can use the below pipeline. Use preserveNullAndEmptyArrays option on $unwind to prevent pipeline from dropping documents when any of the below arrays is missing, null or empty.

db.collection.aggregate(
    [
      { "$unwind": "$floors" },
      { "$unwind": "$floors.rooms" },
      { "$unwind": "$floors.rooms.devices" },
      { "$group":{ "_id":"$_id", "devices":{ "$push":"$floors.rooms.devices"} } }
    ]
)


问:
Error in installing Tabulizer
Using the instructions described in github and installing Java accordingly with Chocolatey -- plus installing rJava and setting the path in R with Sys.setenv(JAVA_HOME = "C:/Program Files/Java/jdk1.8.0_131")-- I've done the following in R:

```<code>library(ghit)
library(git2r)
ghit::install_github(c("leeper/tabulizerjars", "leeper/tabulizer"), INSTALL_opts = "--no-multiarch", dependencies = c("Depends", "Imports"))
</code>```

Which is the solution provided in this answer. I get the following error:

```<code>Error in git2r::init(d) :
  Error in 'git2r_repository_init': Unable to init repository
</code>```

Setting the option VERBOSE = TRUE in install_github I get the following additional output:

```<code>Parsing reponame for 'leeper/tabulizerjars'...
Creating local git repository for tabulizerjars in C:\Users\JOOCAR~1\AppData\Local\Temp\RtmpgnitDP\tabulizerjars1643e0126f5...
Error in git2r::init(d) :
  Error in 'git2r_repository_init': Unable to init repository
</code>```

I read this answer and it seems that it has to do with my username, which is spaced and has accents. But how do I configure this?

edit: 6/4/2017 1:57 am

Following user @jaySf answer, I run part of the code of his answer (since I've already installed rJava and devtools):

```<code>library(rJava) # load and attach 'rJava' now
devtools::install_github("ropensci/tabulizer", args="--no-multiarch")
</code>```

And got the following error:

```<code>> library(rJava) # load and attach 'rJava' now
> devtools::install_github("ropensci/tabulizer", args="--no-multiarch")
Downloading GitHub repo ropensci/tabulizer@master
from URL https://api.github.com/repos/ropensci/tabulizer/zipball/master
Installing tabulizer
Downloading GitHub repo ropensci/tabulizerjars@master
from URL https://api.github.com/repos/ropensci/tabulizerjars/zipball/master
Installing tabulizerjars
"C:/R-34~1.0/bin/x64/R" --no-site-file --no-environ --no-save --no-restore --quiet CMD INSTALL "C:/Users/Joo  \
  Caos/AppData/Local/Temp/Rtmpgh9eJi/devtoolsb3c50925145/ropensci-tabulizerjars-c6cc40e" --library="C:/R-3.4.0/library" --install-tests

* installing *source* package 'tabulizerjars' ...
** R
** inst
** preparing package for lazy loading
** help
*** installing help indices
** building package indices
** testing if installed package can be loaded
*** arch - i386
Error: package or namespace load failed for 'tabulizerjars':
 .onLoad failed in loadNamespace() for 'rJava', details:
  call: inDL(x, as.logical(local), as.logical(now), ...)
  error: unable to load shared object 'C:/R-3.4.0/library/rJava/libs/i386/rJava.dll':
  LoadLibrary failure:  %1 is not a valid Win32 application.

Error: loading failed
Execution halted
*** arch - x64
ERROR: loading failed for 'i386'
* removing 'C:/R-3.4.0/library/tabulizerjars'
Installation failed: Command failed (1)
"C:/R-34~1.0/bin/x64/R" --no-site-file --no-environ --no-save --no-restore --quiet CMD INSTALL "C:/Users/Joo  \
  Caos/AppData/Local/Temp/Rtmpgh9eJi/devtoolsb3c4a2835ec/ropensci-tabulizer-a38d957" --library="C:/R-3.4.0/library" --install-tests --no-multiarch

ERROR: dependency 'tabulizerjars' is not available for package 'tabulizer'
* removing 'C:/R-3.4.0/library/tabulizer'
Installation failed: Command failed (1)
</code>```

I believe that I might have a problem with my username in the file directory path, but I'm not sure. I tried using install_github with ggplot2 --`install_github("wch/ggplot2") -- and it worked fine. If my guess is correct, how can I edit the file path?

Problem solved

I was running R with both 32 bit and 64 bit files installed. I cannot clearly state what were the problems in doing this, since as I ran Sys.getenv("R_ARCH") it returned x64 previously, but when I uninstalled the 32 bit files, it ran perfectly well with @jaySf code.

答:
Follow these steps in given order should work:

```<code>install.packages("rJava")
library(rJava) # load and attach 'rJava' now
install.packages("devtools")
devtools::install_github("ropensci/tabulizer", args="--no-multiarch")
</code>```

I'm using R 3.4.0 on win64, and described the procedure in a former answer.

Title: Error in installing Tabulizer

Body:
Using the instructions described in github and installing Java accordingly with Chocolatey -- plus installing rJava and setting the path in R with Sys.setenv(JAVA_HOME = "C:/Program Files/Java/jdk1.8.0_131")-- I've done the following in R:

library(ghit)
library(git2r)
ghit::install_github(c("leeper/tabulizerjars", "leeper/tabulizer"), INSTALL_opts = "--no-multiarch", dependencies = c("Depends", "Imports"))

Which is the solution provided in this answer. I get the following error:

Error in git2r::init(d) :
  Error in 'git2r_repository_init': Unable to init repository

Setting the option VERBOSE = TRUE in install_github I get the following additional output:

Parsing reponame for 'leeper/tabulizerjars'...
Creating local git repository for tabulizerjars in C:\Users\JOOCAR~1\AppData\Local\Temp\RtmpgnitDP\tabulizerjars1643e0126f5...
Error in git2r::init(d) :
  Error in 'git2r_repository_init': Unable to init repository

I read this answer and it seems that it has to do with my username, which is spaced and has accents. But how do I configure this?

edit: 6/4/2017 1:57 am

Following user @jaySf answer, I run part of the code of his answer (since I've already installed rJava and devtools):

library(rJava) # load and attach 'rJava' now
devtools::install_github("ropensci/tabulizer", args="--no-multiarch")

And got the following error:

> library(rJava) # load and attach 'rJava' now
> devtools::install_github("ropensci/tabulizer", args="--no-multiarch")
Downloading GitHub repo ropensci/tabulizer@master
from URL https://api.github.com/repos/ropensci/tabulizer/zipball/master
Installing tabulizer
Downloading GitHub repo ropensci/tabulizerjars@master
from URL https://api.github.com/repos/ropensci/tabulizerjars/zipball/master
Installing tabulizerjars
"C:/R-34~1.0/bin/x64/R" --no-site-file --no-environ --no-save --no-restore --quiet CMD INSTALL "C:/Users/Joo  \
  Caos/AppData/Local/Temp/Rtmpgh9eJi/devtoolsb3c50925145/ropensci-tabulizerjars-c6cc40e" --library="C:/R-3.4.0/library" --install-tests

* installing *source* package 'tabulizerjars' ...
** R
** inst
** preparing package for lazy loading
** help
*** installing help indices
** building package indices
** testing if installed package can be loaded
*** arch - i386
Error: package or namespace load failed for 'tabulizerjars':
 .onLoad failed in loadNamespace() for 'rJava', details:
  call: inDL(x, as.logical(local), as.logical(now), ...)
  error: unable to load shared object 'C:/R-3.4.0/library/rJava/libs/i386/rJava.dll':
  LoadLibrary failure:  %1 is not a valid Win32 application.

Error: loading failed
Execution halted
*** arch - x64
ERROR: loading failed for 'i386'
* removing 'C:/R-3.4.0/library/tabulizerjars'
Installation failed: Command failed (1)
"C:/R-34~1.0/bin/x64/R" --no-site-file --no-environ --no-save --no-restore --quiet CMD INSTALL "C:/Users/Joo  \
  Caos/AppData/Local/Temp/Rtmpgh9eJi/devtoolsb3c4a2835ec/ropensci-tabulizer-a38d957" --library="C:/R-3.4.0/library" --install-tests --no-multiarch

ERROR: dependency 'tabulizerjars' is not available for package 'tabulizer'
* removing 'C:/R-3.4.0/library/tabulizer'
Installation failed: Command failed (1)

I believe that I might have a problem with my username in the file directory path, but I'm not sure. I tried using install_github with ggplot2 --`install_github("wch/ggplot2") -- and it worked fine. If my guess is correct, how can I edit the file path?

Problem solved

I was running R with both 32 bit and 64 bit files installed. I cannot clearly state what were the problems in doing this, since as I ran Sys.getenv("R_ARCH") it returned x64 previously, but when I uninstalled the 32 bit files, it ran perfectly well with @jaySf code.

Body:
Follow these steps in given order should work:

install.packages("rJava")
library(rJava) # load and attach 'rJava' now
install.packages("devtools")
devtools::install_github("ropensci/tabulizer", args="--no-multiarch")

I'm using R 3.4.0 on win64, and described the procedure in a former answer.


问:
Latest Composer version not pulling Laravel
The Latest version of Composer is not pulling Laravel, I thought it could be because of Composer added new secure_http feature for downloading from Packagist and Laravel Packagist are in HTTP. This is what I think, so I need solution. The previous version of Composer doing well.
The error showing on my terminal when I was trying to install Laravel installer, is:

Failed to decode response: zlib_decode(): data error Retrying with degraded mode, check https://getcomposer.org/doc/articles/troubleshooting.md#degraded-mode for more info Your configuration does not allow connection to http://packagist.org. See https://getcomposer.org/doc/06-config.md#secure-http for details. http://packagist.org could not be fully loaded, package information was loaded from the local cache and may be out of date Installation failed, reverting ./composer.json to its original content. [Composer\Downloader\TransportException] Your configuration does not allow connection to http://packagist.org. See https://getcomposer.org/doc/06-config.md#secure-http for details.

答:
When running (downgrade composer by running)

```<code>composer config -g secure-http false
</code>```

i still got an exeption

```<code>Fatal error: Uncaught Error: Call to undefined method Composer\Package\RootPackage::getConfig() ...
</code>```

I got a success finaly using additional --no-plugins

```<code>composer config -g secure-http false --no-plugins
composer self-update --no-plugins
</code>```

Hope this helps anyone :)

Body:
When running (downgrade composer by running)

composer config -g secure-http false

i still got an exeption

Fatal error: Uncaught Error: Call to undefined method Composer\Package\RootPackage::getConfig() ...

I got a success finaly using additional --no-plugins

composer config -g secure-http false --no-plugins
composer self-update --no-plugins

Hope this helps anyone :)


问:
C - How to make sure that an array contains 8 integers with the value 0 or 1?
That's my code so far:

```<code>int main(void) {
    int byte[8], position = 0, match8 = 0;
    printf("Please enter 1 byte as a binary sequence: ");
    match8 = scanf("%1d%1d%1d%1d%1d%1d%1d%1d", &byte[0], &byte[1], &byte[2], &byte[3], &byte[4], &byte[5], &byte[6],&byte[7]);
    return 0;
}
</code>```

Now I want to make sure that the user made a correct input and if not the program should say "Error! Please enter 1 byte as a binary sequence: " and check the input again.

I tried:

```<code>while(getchar() != '\n' || match8 != 8) {
    ...do something
}
</code>```

But I can't figure out how to check if the array contains only 0 and 1.

I hope you can help me with my problem :)

答:
A scanset %8[01] could be used to restrict input to the characters 0 and 1. The 8 will also limit input to 8 characters. The characters can be converted to numbers with number = onezero[i] - '0';

```<code>#include <stdio.h>
#include <string.h>

int main( void) {
    char onezero[9] = "";
    int valid = 0;

    do {
        printf("Please enter 1 byte as a binary sequence: ");
        if ( ( 1 == ( valid = scanf ( " %8[01]", onezero))) && ( 8 == strlen ( onezero))) {
            printf ( "input was %s\n", onezero);
        }
        else {
            if ( valid == EOF) {
                break;
            }
            while ( getchar ( ) != '\n') {}
            valid = 0;
        }
    } while ( !valid);

    return 0;
}
</code>```

Body:
That's my code so far:

int main(void) {
    int byte[8], position = 0, match8 = 0;
    printf("Please enter 1 byte as a binary sequence: ");
    match8 = scanf("%1d%1d%1d%1d%1d%1d%1d%1d", &byte[0], &byte[1], &byte[2], &byte[3], &byte[4], &byte[5], &byte[6],&byte[7]);
    return 0;
}

Now I want to make sure that the user made a correct input and if not the program should say "Error! Please enter 1 byte as a binary sequence: " and check the input again.

I tried:

while(getchar() != '\n' || match8 != 8) {
    ...do something
}

But I can't figure out how to check if the array contains only 0 and 1.

I hope you can help me with my problem :)

Body:
A scanset %8[01] could be used to restrict input to the characters 0 and 1. The 8 will also limit input to 8 characters. The characters can be converted to numbers with number = onezero[i] - '0';

#include <stdio.h>
#include <string.h>

int main( void) {
    char onezero[9] = "";
    int valid = 0;

    do {
        printf("Please enter 1 byte as a binary sequence: ");
        if ( ( 1 == ( valid = scanf ( " %8[01]", onezero))) && ( 8 == strlen ( onezero))) {
            printf ( "input was %s\n", onezero);
        }
        else {
            if ( valid == EOF) {
                break;
            }
            while ( getchar ( ) != '\n') {}
            valid = 0;
        }
    } while ( !valid);

    return 0;
}


问:
Can't get CKEditor plugins to work in django
I am trying to get the CKEditor plugin, codesnippet, to work in the django admin but am unable to. CKEditor works if I don't define any CKEDIT_CONFIGS in my settings.py. It also works if take out the "extraPlugins" line (and it successfully will adjust the height and width as defined in the CKEDITOR_CONFIGS section).

I installed CKEditor using the instructions here: https://github.com/shaunsephton/django-ckeditor

CKeditor is located in /static/ckeditor and codesnippet is in /static/ckeditor/plugins/

In my settings.py

```<code>CKEDITOR_UPLOAD_PATH = 'uploads/'
CKEDITOR_JQUERY_URL = '/static/js/jquery-2.1.1.min.js'
CKEDITOR_CONFIGS = {
       'default': {
           'toolbar': 'Full',
           'height': 400,
           'width': 900,
           'removePlugins': 'stylesheetparser',
           'extraPlugins': 'codesnippet',
       },
   }
</code>```

My admin.py

```<code>from django.contrib import admin
from blog.models import Article, Category
from django.utils import text
from django import forms
from ckeditor.widgets import CKEditorWidget

class ArticleAdminForm(forms.ModelForm):
    body = forms.CharField(widget=CKEditorWidget())
    class Meta:
        model = Article
</code>```

I have also tried using just 'plugins' instead of 'extraPlugins' (although this not recomended), but get the same result (which is it breaks CKEditor and the filed doesn't display at all in the admin).

Thanks in advance for your help!

EDIT 11/26/14

OK so this still isn't working. I am pretty sure the problem is this (from the nginx error log)

```<code>2014/11/26 14:07:20 [error] 3265#0: *1 open() "/srv/www/mysite/static//ckeditor/ckeditor/plugins/codesnippet/plugin.js" failed
</code>```

That path isn't right (erroneous double black slash and an extra "ckeditor" directory").

My settings.py now looks like this.

```<code>CKEDITOR_UPLOAD_PATH = 'uploads/'
CKEDITOR_JQUERY_URL = '/static/js/jquery-2.1.1.min.js'

CKEDITOR_CONFIGS = {
   'default': {
        'toolbar':[ ['CodeSnippet', ], ],
        'height': 400,
        'width': 900,
        'removePlugins': 'stylesheetparser',
        'extraPlugins': 'codesnippet',
   },
}
</code>```

The Extra Plugins line is what is causing the nginx error, I have no idea where it is getting that path.

Below is more further information that may be helpful.

This is my full admin.py file

```<code>from django.contrib import admin
from blog.models import Article, Category
from django.utils import text
from django import forms
from django.db import models
from ckeditor.widgets import CKEditorWidget

class ArticleAdminForm(forms.ModelForm):
    body = forms.CharField(widget=CKEditorWidget())

class Meta:
    model = Article

class ArticleAdmin(admin.ModelAdmin):
    form = ArticleAdminForm

admin.site.register(Article, ArticleAdmin)
admin.site.register(Category)
</code>```

I have copied the following lines into my ckedit.js file and dragged over the appropriate folders in the the plugins folder.

```<code>config.extraPlugins = 'dialog';
config.extraPlugins = 'widget';
config.extraPlugins = 'dialogui';
config.extraPlugins = 'lineutils';
config.extraPlugins = 'clipboard';
config.extraPlugins = 'codesnippet';
config.toolbar_Full.push(['codesnippet']);
</code>```

EDIT 12/1/14

Nginx config file (as requested)

```<code>server {
    listen 8080;
    server_name mysite.com;
    access_log /srv/www/mysite/logs/access-dev.log;
    error_log /srv/www/mysite/logs/error-dev.log;
    charset utf-8;

    #Django admin css
    location /static/admin {
    alias /srv/www/mysite/static/admin;
    }

    #Django static files
    location /static {
    alias /srv/www/mysite/static/;
    }

    #Django media files
    location /media {
    alias /srv/www/mysite/media/;
    }

    #Uwsgi handles all other requests
    location / {
    auth_basic "Restricted";
    auth_basic_user_file /srv/www/mysite/.nginxpwd;
    uwsgi_pass unix:/var/uwsgi/uwsgi_at-dev.sock;
    include uwsgi_params;
    }
}
</code>```

EDIT 12/3/14

Full nginx error:

```<code>2014/11/26 14:36:16 [error] 3461#0: *1 open() "/srv/www/mysite/static//ckeditor/ckeditor/plugins/codesnippet/plugin.js" failed (2: No such file or directory), client: 71.235.164.91, server: 104.131.36.141,, request: "GET /static/ckeditor/ckeditor/plugins/codesnippet/plugin.js?t=E7KD HTTP/1.1", host: "mysite:8080", referrer: "http://mysite:8080/admin/blog/article/3/"
</code>```

In my settings.py

```<code>MEDIA_ROOT = '/srv/www/mysite/media/'
MEDIA_URL = '/media/'

STATIC_ROOT = '/srv/www/mysite/static'
STATIC_URL = '/static/'

CKEDITOR_UPLOAD_PATH = 'uploads/'
CKEDITOR_JQUERY_URL = '/static/js/jquery-2.1.1.min.js'
</code>```

答: The actual cause is that plugin.js is not added by the CKEditor builder. I have no idea why that is, but each plugin's repository does have a plugin.js.

Body:
I am trying to get the CKEditor plugin, codesnippet, to work in the django admin but am unable to. CKEditor works if I don't define any CKEDIT_CONFIGS in my settings.py. It also works if take out the "extraPlugins" line (and it successfully will adjust the height and width as defined in the CKEDITOR_CONFIGS section).

I installed CKEditor using the instructions here: https://github.com/shaunsephton/django-ckeditor

CKeditor is located in /static/ckeditor and codesnippet is in /static/ckeditor/plugins/

In my settings.py

CKEDITOR_UPLOAD_PATH = 'uploads/'
CKEDITOR_JQUERY_URL = '/static/js/jquery-2.1.1.min.js'
CKEDITOR_CONFIGS = {
       'default': {
           'toolbar': 'Full',
           'height': 400,
           'width': 900,
           'removePlugins': 'stylesheetparser',
           'extraPlugins': 'codesnippet',
       },
   }

My admin.py

from django.contrib import admin
from blog.models import Article, Category
from django.utils import text
from django import forms
from ckeditor.widgets import CKEditorWidget

class ArticleAdminForm(forms.ModelForm):
    body = forms.CharField(widget=CKEditorWidget())
    class Meta:
        model = Article

I have also tried using just 'plugins' instead of 'extraPlugins' (although this not recomended), but get the same result (which is it breaks CKEditor and the filed doesn't display at all in the admin).

Thanks in advance for your help!

EDIT 11/26/14

OK so this still isn't working. I am pretty sure the problem is this (from the nginx error log)

2014/11/26 14:07:20 [error] 3265#0: *1 open() "/srv/www/mysite/static//ckeditor/ckeditor/plugins/codesnippet/plugin.js" failed

That path isn't right (erroneous double black slash and an extra "ckeditor" directory").

My settings.py now looks like this.

CKEDITOR_UPLOAD_PATH = 'uploads/'
CKEDITOR_JQUERY_URL = '/static/js/jquery-2.1.1.min.js'

CKEDITOR_CONFIGS = {
   'default': {
        'toolbar':[ ['CodeSnippet', ], ],
        'height': 400,
        'width': 900,
        'removePlugins': 'stylesheetparser',
        'extraPlugins': 'codesnippet',
   },
}

The Extra Plugins line is what is causing the nginx error, I have no idea where it is getting that path.

Below is more further information that may be helpful.

This is my full admin.py file

from django.contrib import admin
from blog.models import Article, Category
from django.utils import text
from django import forms
from django.db import models
from ckeditor.widgets import CKEditorWidget

class ArticleAdminForm(forms.ModelForm):
    body = forms.CharField(widget=CKEditorWidget())

class Meta:
    model = Article

class ArticleAdmin(admin.ModelAdmin):
    form = ArticleAdminForm

admin.site.register(Article, ArticleAdmin)
admin.site.register(Category)

I have copied the following lines into my ckedit.js file and dragged over the appropriate folders in the the plugins folder.

config.extraPlugins = 'dialog';
config.extraPlugins = 'widget';
config.extraPlugins = 'dialogui';
config.extraPlugins = 'lineutils';
config.extraPlugins = 'clipboard';
config.extraPlugins = 'codesnippet';
config.toolbar_Full.push(['codesnippet']);

EDIT 12/1/14

Nginx config file (as requested)

server {
    listen 8080;
    server_name mysite.com;
    access_log /srv/www/mysite/logs/access-dev.log;
    error_log /srv/www/mysite/logs/error-dev.log;
    charset utf-8;

    #Django admin css
    location /static/admin {
    alias /srv/www/mysite/static/admin;
    }

    #Django static files
    location /static {
    alias /srv/www/mysite/static/;
    }

    #Django media files
    location /media {
    alias /srv/www/mysite/media/;
    }

    #Uwsgi handles all other requests
    location / {
    auth_basic "Restricted";
    auth_basic_user_file /srv/www/mysite/.nginxpwd;
    uwsgi_pass unix:/var/uwsgi/uwsgi_at-dev.sock;
    include uwsgi_params;
    }
}

EDIT 12/3/14

Full nginx error:

2014/11/26 14:36:16 [error] 3461#0: *1 open() "/srv/www/mysite/static//ckeditor/ckeditor/plugins/codesnippet/plugin.js" failed (2: No such file or directory), client: 71.235.164.91, server: 104.131.36.141,, request: "GET /static/ckeditor/ckeditor/plugins/codesnippet/plugin.js?t=E7KD HTTP/1.1", host: "mysite:8080", referrer: "http://mysite:8080/admin/blog/article/3/"

In my settings.py

MEDIA_ROOT = '/srv/www/mysite/media/'
MEDIA_URL = '/media/'

STATIC_ROOT = '/srv/www/mysite/static'
STATIC_URL = '/static/'

CKEDITOR_UPLOAD_PATH = 'uploads/'
CKEDITOR_JQUERY_URL = '/static/js/jquery-2.1.1.min.js'


问:
Change only one letter in string
I have 2 string and one letter.

```<code>selectedWords BYTE "BICYCLE"
guessWords BYTE "-------"
inputLetter BYTE 'C'
</code>```

Base on this answers, I write code who compere if selectedWords have letter C and If this is the case he need to change string guessWords:

guessWords "--C-C--"

But from some strange reason I get all other possibilities, just not correct one. Some suggestions on how to solve this problem.

答:
First, forget the so called string instructions (scas, comps, movs). Second, you need a fixed pointer (dispkacement) with an index, e.g [esi+ebx]. Have you considered that WriteString needs a null-terminated string?

```<code>INCLUDE Irvine32.inc

.DATA
selectedWords BYTE "BICYCLE"
guessWords BYTE SIZEOF selectedWords DUP ('-'), 0   ; With null-termination for WriteString
inputLetter BYTE 'C'

.CODE
main PROC

    mov esi, offset selectedWords       ; Source
    mov edi, offset guessWords          ; Destination
    mov ecx, LENGTHOF selectedWords     ; Number of bytes to check
    mov al, inputLetter                 ; Search for that character
    xor ebx, ebx                        ; Index EBX = 0

    ride_hard_loop:
    cmp [esi+ebx], al                   ; Compare memory/register
    jne @F                              ; Skip next line if no match
    mov [edi+ebx], al                   ; Hang 'em lower
    @@:
    inc ebx                             ; Increment pointer
    dec ecx                             ; Decrement counter
    jne ride_hard_loop                  ; Jump if ECX != 0

    mov edx, edi
    call WriteString                    ; Irvine32: Write a null-terminated string pointed to by EDX
    exit                                ; Irvine32: ExitProcess

main ENDP

END main
</code>```

Title: Change only one letter in string

Body:
I have 2 string and one letter.

selectedWords BYTE "BICYCLE"
guessWords BYTE "-------"
inputLetter BYTE 'C'

Base on this answers, I write code who compere if selectedWords have letter C and If this is the case he need to change string guessWords:

guessWords "--C-C--"

But from some strange reason I get all other possibilities, just not correct one. Some suggestions on how to solve this problem.

Body:
First, forget the so called string instructions (scas, comps, movs). Second, you need a fixed pointer (dispkacement) with an index, e.g [esi+ebx]. Have you considered that WriteString needs a null-terminated string?

INCLUDE Irvine32.inc

.DATA
selectedWords BYTE "BICYCLE"
guessWords BYTE SIZEOF selectedWords DUP ('-'), 0   ; With null-termination for WriteString
inputLetter BYTE 'C'

.CODE
main PROC

    mov esi, offset selectedWords       ; Source
    mov edi, offset guessWords          ; Destination
    mov ecx, LENGTHOF selectedWords     ; Number of bytes to check
    mov al, inputLetter                 ; Search for that character
    xor ebx, ebx                        ; Index EBX = 0

    ride_hard_loop:
    cmp [esi+ebx], al                   ; Compare memory/register
    jne @F                              ; Skip next line if no match
    mov [edi+ebx], al                   ; Hang 'em lower
    @@:
    inc ebx                             ; Increment pointer
    dec ecx                             ; Decrement counter
    jne ride_hard_loop                  ; Jump if ECX != 0

    mov edx, edi
    call WriteString                    ; Irvine32: Write a null-terminated string pointed to by EDX
    exit                                ; Irvine32: ExitProcess

main ENDP

END main


问:
I'm trying to draw polyline on coordinates(lat, long) coming from API using swift 3 in map kit but unable to make polyline
```<code>import UIKit
import MapKit
import CoreLocation
import AddressBook

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    @IBOutlet weak var TheMap: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        zoomToRegion()
        location()
    }

    func centerMapOnLocation(location: MKPointAnnotation, regionRadius: Double) {
        let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
                                                                  regionRadius * 2.0, regionRadius * 2.0)
        TheMap.setRegion(coordinateRegion, animated: true)

    }

    //MARK:- MapViewDelegate methods

    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let polylineRenderer = MKPolylineRenderer(overlay: overlay)

        if overlay is MKPolyline {
            polylineRenderer.strokeColor = UIColor.blue
            polylineRenderer.lineWidth = 5

        }
        return polylineRenderer
    }

    //MARK:- Zoom to region

    func zoomToRegion() {
        let location = CLLocationCoordinate2D(latitude: 28.618945, longitude: 77.377347400000005)
        let region = MKCoordinateRegionMakeWithDistance(location, 5000.0, 7000.0)
        TheMap.setRegion(region, animated: true)
    }

    // API CALL FUNCTION

    func location() {

        let user = "userid"
        let password = "password"

        let postString = ["empid":user, "date1": password]
        var request = URLRequest(url:URL(string: "http://mydomainhere.com/airtel_hrm/webapi/api/getpunchdeytails")!)
        request.httpMethod = "POST"
        request.httpBody = try! JSONSerialization.data(withJSONObject: postString, options:.prettyPrinted)

        let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?)in

            if error != nil
            {
                print("error=\(error)")
                return
            }
            do {
                if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any],
                    let data = json["punchdetails"] as? [[String: Any]] {
                    //print(data)

                    for datas in data {
                        let lat  = datas["punch_loc_lat"] as! String
                        let long = datas["punch_loc_long"] as! String

                        var annotations = [MKPointAnnotation]()

                        let latitude = CLLocationDegrees(lat)
                        let longitude = CLLocationDegrees(long)
                        let coordinate = CLLocationCoordinate2D(latitude: latitude!, longitude: longitude!)
                        let annotation = MKPointAnnotation()
                        annotation.coordinate = coordinate
                        annotations.append(annotation)

                        self.TheMap.addAnnotations(annotations)
                        self.TheMap.delegate = self

                        self.centerMapOnLocation(location: annotations[0], regionRadius: 2000.0)

                        // Connect all the mappoints using Poly line.

                        var points: [CLLocationCoordinate2D] = [coordinate] //[CLLocationCoordinate2D]()

                        for annotation in annotations {
                            points.append(annotation.coordinate)
                        }

                        print("this is points = \(points)")

                        let polyline = MKPolyline(coordinates: &points, count: points.count)

                        //self.TheMap.add(polyline)

                    } //for loop closed

                }
            } catch {
                print(error)
            }

        }
        task.resume()

    }

}
</code>```

答:
I'm sure if you shared the results of the print statement, the problem would have been obvious. You're probably seeing lots of print statements. Bottom line, you should define your array outside of the for loop, only append values within the loop, and then add the polyline after the loop:

```<code>do {
    if let json = try JSONSerialization.jsonObject(with: data!) as? [String: Any],
        let data = json["punchdetails"] as? [[String: Any]] {

        var annotations = [MKPointAnnotation]()

        for datas in data {
            let lat  = datas["punch_loc_lat"] as! String
            let long = datas["punch_loc_long"] as! String

            let latitude = CLLocationDegrees(lat)
            let longitude = CLLocationDegrees(long)
            let coordinate = CLLocationCoordinate2D(latitude: latitude!, longitude: longitude!)
            let annotation = MKPointAnnotation()
            annotation.coordinate = coordinate
            annotations.append(annotation)
        }

        self.TheMap.delegate = self  // you really should do this in IB or, if you feel compelled to do it programmatically, in viewDidLoad

        // Connect all the mappoints using Poly line.

        let points = annotations.map { $0.coordinate }

        print("this is points = \(points)")

        let polyline = MKPolyline(coordinates: &points, count: points.count)

        DispatchQueue.main.async {
            self.centerMapOnLocation(location: annotations[0], regionRadius: 2000.0)
            self.TheMap.addAnnotations(annotations)
            self.TheMap.add(polyline)
        }
    }
} catch {
    print(error)
}
</code>```

Note, I'd also do all interaction with the map view from the main queue.

Body:
I'm sure if you shared the results of the print statement, the problem would have been obvious. You're probably seeing lots of print statements. Bottom line, you should define your array outside of the for loop, only append values within the loop, and then add the polyline after the loop:

do {
    if let json = try JSONSerialization.jsonObject(with: data!) as? [String: Any],
        let data = json["punchdetails"] as? [[String: Any]] {

        var annotations = [MKPointAnnotation]()

        for datas in data {
            let lat  = datas["punch_loc_lat"] as! String
            let long = datas["punch_loc_long"] as! String

            let latitude = CLLocationDegrees(lat)
            let longitude = CLLocationDegrees(long)
            let coordinate = CLLocationCoordinate2D(latitude: latitude!, longitude: longitude!)
            let annotation = MKPointAnnotation()
            annotation.coordinate = coordinate
            annotations.append(annotation)
        }

        self.TheMap.delegate = self  // you really should do this in IB or, if you feel compelled to do it programmatically, in viewDidLoad

        // Connect all the mappoints using Poly line.

        let points = annotations.map { $0.coordinate }

        print("this is points = \(points)")

        let polyline = MKPolyline(coordinates: &points, count: points.count)

        DispatchQueue.main.async {
            self.centerMapOnLocation(location: annotations[0], regionRadius: 2000.0)
            self.TheMap.addAnnotations(annotations)
            self.TheMap.add(polyline)
        }
    }
} catch {
    print(error)
}

Note, I'd also do all interaction with the map view from the main queue.


问:
How can I read an Excel Date and store it into my database?
I am trying to read an Excel Date value and store it into my database.

The following code is what I've got:

```<code>Date birthdate = null;
case 8:
       birthdate = cell.getDateCellValue();
       break;
</code>```

The switch case is to store the Date in a variable and to put it into an array afterwards.

```<code>Identity id = new Identity(BSN, sort, birthdate, place);
</code>```

I store multiple of those values into an arraylist.

```<code>for(Identity id : Identities) {
        System.out.println(id.toString());
        idmc.insertID(""+id.getBSN(), id.getSort(), id.getBirthdate(), id.getPlace());
    }
</code>```

The getter and setter for date is obvious, but I'll post it just in case.

```<code>public void Birthdate (Date birthdate) {
    this.birthdate = birthdate;
}

public Date getBirthdate() {
    return birthdate;
}
</code>```

Then to insert the values I get from the Array, I use this method:

```<code>public String insertID(String BSN, String SoortID, Date UitgiftedatumID, String UitgifteplaatsID) {
    String returning = null;
    try {
        query = "insert into Identiteit values(?,?,?,?);";

        pst = connection.prepareStatement(query);
        pst.setInt(1, Integer.parseInt(BSN));
        pst.setString(2, Sort);
        pst.setDate(3, birthdate);
        pst.setString(4, place);

        int response = pst.executeUpdate();
        returning = response +" Records has/have been edited";

    } catch (SQLException e) {
        returning = " ";

    }

    return returning;
}
</code>```

However, the line: pst.setDate(3, UitgiftedatumID); says: Incomatible types: java.util.Date cannot be converted to java.sql.Date.

I've tried casting like: pst.setDate(3, (java.sql.Date) UitgiftedatumID);

But unfortunately that didn't work out for me.

答:
There are two Date classes in Java: java.util.Date (a general-purpose date-time class) and java.sql.Date (JDBC-related class that represents date (with no time component)). PreparedStatement#setDate() method accepts the latter as its second parameter.

To convert an instance of java.util.Date to an instance of java.sql.Date, you could do the following:

```<code>java.util.Date UitgiftedatumID = ... // some value
java.sql.Date sqlDate = UitgiftedatumID == null ? null : new java.sql.Date(UitgiftedatumID.getTime());
</code>```

Body:
I am trying to read an Excel Date value and store it into my database.

The following code is what I've got:

Date birthdate = null;
case 8:
       birthdate = cell.getDateCellValue();
       break;

The switch case is to store the Date in a variable and to put it into an array afterwards.

Identity id = new Identity(BSN, sort, birthdate, place);

I store multiple of those values into an arraylist.

for(Identity id : Identities) {
        System.out.println(id.toString());
        idmc.insertID(""+id.getBSN(), id.getSort(), id.getBirthdate(), id.getPlace());
    }

The getter and setter for date is obvious, but I'll post it just in case.

public void Birthdate (Date birthdate) {
    this.birthdate = birthdate;
}

public Date getBirthdate() {
    return birthdate;
}

Then to insert the values I get from the Array, I use this method:

public String insertID(String BSN, String SoortID, Date UitgiftedatumID, String UitgifteplaatsID) {
    String returning = null;
    try {
        query = "insert into Identiteit values(?,?,?,?);";

        pst = connection.prepareStatement(query);
        pst.setInt(1, Integer.parseInt(BSN));
        pst.setString(2, Sort);
        pst.setDate(3, birthdate);
        pst.setString(4, place);

        int response = pst.executeUpdate();
        returning = response +" Records has/have been edited";

    } catch (SQLException e) {
        returning = " ";

    }

    return returning;
}

However, the line: pst.setDate(3, UitgiftedatumID); says: Incomatible types: java.util.Date cannot be converted to java.sql.Date.

I've tried casting like: pst.setDate(3, (java.sql.Date) UitgiftedatumID);

But unfortunately that didn't work out for me.

Body:
There are two Date classes in Java: java.util.Date (a general-purpose date-time class) and java.sql.Date (JDBC-related class that represents date (with no time component)). PreparedStatement#setDate() method accepts the latter as its second parameter.

To convert an instance of java.util.Date to an instance of java.sql.Date, you could do the following:

java.util.Date UitgiftedatumID = ... // some value
java.sql.Date sqlDate = UitgiftedatumID == null ? null : new java.sql.Date(UitgiftedatumID.getTime());


问:
How Can I use Case clause within WHERE condition in this procedure?
I'm writing a simple stored procedure for retrieve information about all employees but, I'd add 2 parameters to retrieve information only one employee if is passed for parameter. My intention is create a cursor and add condition in WHERE using parameters but It is not working for now. Do you have any idea? Thanks!

First parameter is for employee id.

Second parameter is for a raise salary.

The procedure is:

```<code>CREATE OR REPLACE PROCEDURE test6(
        p_empid        empleados.legajo%TYPE := NULL,
        p_raise_salary empleados.sueldo_basico%TYPE := NULL)
IS
    CURSOR c_emps
    IS
        SELECT legajo, apellido, nombre, fecha_alta, sueldo_basico,
               (CASE
                    WHEN p_raise_salary IS NOT NULL THEN
                        sueldo_basico * p_raise_salary
                    ELSE
                        sueldo_Basico
                END) aumento_sueldo_basico
        FROM    empleados
        WHERE  (legajo = p_empid AND fecha_alta IS NOT NULL)
        OR     fecha_alta IS NOT NULL;
BEGIN
    FOR i IN c_emps
    LOOP
        DBMS_OUTPUT.PUT_LINE(
            'NOMBRE: ' || i.apellido || ' ' || i.nombre || ' ' || i.legajo);
        DBMS_OUTPUT.PUT_LINE(
            'Antiguo Sueldo: ' || i.sueldo_basico);
        DBMS_OUTPUT.PUT_LINE(
            'Nuevo Sueldo: ' || i.aumento_sueldo_basico);

        EXIT WHEN c_emps%NOTFOUND;
    END LOOP;
END test6;
</code>```

Second parameter for raise salary is working but when I add a value for id parameter is currently displaying all employees info.

答: You need to re look into the condition "OR     fecha_alta IS NOT NULL". All of your records may be having a not null value in your table. Can you first try by commenting out this condition ?</p>

Body:
I'm writing a simple stored procedure for retrieve information about all employees but, I'd add 2 parameters to retrieve information only one employee if is passed for parameter. My intention is create a cursor and add condition in WHERE using parameters but It is not working for now. Do you have any idea? Thanks!

First parameter is for employee id.

Second parameter is for a raise salary.

The procedure is:

CREATE OR REPLACE PROCEDURE test6(
        p_empid        empleados.legajo%TYPE := NULL,
        p_raise_salary empleados.sueldo_basico%TYPE := NULL)
IS
    CURSOR c_emps
    IS
        SELECT legajo, apellido, nombre, fecha_alta, sueldo_basico,
               (CASE
                    WHEN p_raise_salary IS NOT NULL THEN
                        sueldo_basico * p_raise_salary
                    ELSE
                        sueldo_Basico
                END) aumento_sueldo_basico
        FROM    empleados
        WHERE  (legajo = p_empid AND fecha_alta IS NOT NULL)
        OR     fecha_alta IS NOT NULL;
BEGIN
    FOR i IN c_emps
    LOOP
        DBMS_OUTPUT.PUT_LINE(
            'NOMBRE: ' || i.apellido || ' ' || i.nombre || ' ' || i.legajo);
        DBMS_OUTPUT.PUT_LINE(
            'Antiguo Sueldo: ' || i.sueldo_basico);
        DBMS_OUTPUT.PUT_LINE(
            'Nuevo Sueldo: ' || i.aumento_sueldo_basico);

        EXIT WHEN c_emps%NOTFOUND;
    END LOOP;
END test6;

Second parameter for raise salary is working but when I add a value for id parameter is currently displaying all employees info.


问:
Weighted accuracy for image segmentation using FCN
I have built a FCN for image segmentation. The object to be segmented is only very few pixels relatively to the image size (1024x1024). This results in that the accuracy is very high, even if I only train with 10 images instead of 18000 (my full training set).

My approach to solve this is to use some kind of weighted accuracy, so that the accuracy actually say something about the performance of identifying the small object (now it gets high accuracy since so many pixels are not the object and by not classifying anything the accuracy still gets high).

How do I decide the weight, anybody with some experience?

答: As you wrote, use a custom weight function which penalizes misclassification of underrepresented pixels more. You can get the weight by calculating the quotient between the number of object pixels versus all of the pixels in the image, or you can try it by hand - just make sure you follow the metrics which tell you the accuracy of object pixels. Hope it helps.</p>


问:
What does this code mean? Implementation
Can someone explain what this formula is doing, please.</p>

```<code>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int k = in.nextInt();
        int q = in.nextInt();
        int[] a = new int[n];
        for(int a_i=0; a_i < n; a_i++){
            a[a_i] = in.nextInt();
        }
        for(int a0 = 0; a0 < q; a0++){
            int m = in.nextInt();
            System.out.println(a[((m-k)%n+n)%n]);
        }
    }
}
</code>```

答:
```<code>import java.io.*;//importing all the classes in java.io package and same with all below import statements.
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution{ //creating a class named Solution
    public static void main(String[] args) { //main methid where the execution of the program begins.
        Scanner in = new Scanner(System.in);//scanner is class by using which you can take the input from the user through the console. so you are creating an object of "Scanner" class here.
        int n = in.nextInt();//this will take the next int type from the user through the console
        int k = in.nextInt();//this will take the next int type from the user through the console
        int q = in.nextInt();//this will take the next int type from the user through the console
        int[] a = new int[n];//creating an array of size n.this means you can store n number of values in the array.rememeber n is the  number given by user.if user says 5 i.e you can store 5 values in the array.
        for(int a_i=0; a_i < n; a_i++){//itrating over the n value
            a[a_i] = in.nextInt();//taking the integer value from the user and pusing in to the 'a_i' index
        }
        for(int a0 = 0; a0 < q; a0++){//iterating till value q
            int m = in.nextInt();//taking the m value from the use
            System.out.println(a[((m-k)%n+n)%n]);//performing mathematical operation

        }
    }
}
</code>```

a[((m-k)%n+n)%n]) means 1st m-k --> result%n(gives you the reminder)-->+n -->%n= result. at the end a[result] will be given. if the result is a valid index then you will get valid result from array if not that mean if result is more than size of the array you will get ArrayIndexOutOfBoundsException.

Body:
Can someone explain what this formula is doing, please.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int k = in.nextInt();
        int q = in.nextInt();
        int[] a = new int[n];
        for(int a_i=0; a_i < n; a_i++){
            a[a_i] = in.nextInt();
        }
        for(int a0 = 0; a0 < q; a0++){
            int m = in.nextInt();
            System.out.println(a[((m-k)%n+n)%n]);
        }
    }
}

Body:
import java.io.*;//importing all the classes in java.io package and same with all below import statements.
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution{ //creating a class named Solution
    public static void main(String[] args) { //main methid where the execution of the program begins.
        Scanner in = new Scanner(System.in);//scanner is class by using which you can take the input from the user through the console. so you are creating an object of "Scanner" class here.
        int n = in.nextInt();//this will take the next int type from the user through the console
        int k = in.nextInt();//this will take the next int type from the user through the console
        int q = in.nextInt();//this will take the next int type from the user through the console
        int[] a = new int[n];//creating an array of size n.this means you can store n number of values in the array.rememeber n is the  number given by user.if user says 5 i.e you can store 5 values in the array.
        for(int a_i=0; a_i < n; a_i++){//itrating over the n value
            a[a_i] = in.nextInt();//taking the integer value from the user and pusing in to the 'a_i' index
        }
        for(int a0 = 0; a0 < q; a0++){//iterating till value q
            int m = in.nextInt();//taking the m value from the use
            System.out.println(a[((m-k)%n+n)%n]);//performing mathematical operation

        }
    }
}

a[((m-k)%n+n)%n]) means 1st m-k --> result%n(gives you the reminder)-->+n -->%n= result. at the end a[result] will be given. if the result is a valid index then you will get valid result from array if not that mean if result is more than size of the array you will get ArrayIndexOutOfBoundsException.


问:
data.frame rows to a list
I have a data.frame which I would like to convert to a list by rows, meaning each row would correspond to its own list elements. In other words, I would like a list that is as long as the data.frame has rows.

So far, I've tackled this problem in the following manner, but I was wondering if there's a better way to approach this.

```<code>xy.df <- data.frame(x = runif(10),  y = runif(10))

# pre-allocate a list and fill it with a loop
xy.list <- vector("list", nrow(xy.df))
for (i in 1:nrow(xy.df)) {
    xy.list[[i]] <- xy.df[i,]
}
</code>```

答:
The by_row function from the purrrlyr package will do this for you.

This example demonstrates

```<code>myfn <- function(row) {
  #row is a tibble with one row, and the same number of columns as the original df
  l <- as.list(row)
  return(l)
}

list_of_lists <- purrrlyr::by_row(df, myfn, .labels=FALSE)$.out
</code>```

By default, the returned value from myfn is put into a new list column in the df called .out.  The $.out at the end of the above statement immediately selects this column, returning a list of lists.

Title: data.frame rows to a list

Body:
I have a data.frame which I would like to convert to a list by rows, meaning each row would correspond to its own list elements. In other words, I would like a list that is as long as the data.frame has rows.

So far, I've tackled this problem in the following manner, but I was wondering if there's a better way to approach this.

xy.df <- data.frame(x = runif(10),  y = runif(10))

# pre-allocate a list and fill it with a loop
xy.list <- vector("list", nrow(xy.df))
for (i in 1:nrow(xy.df)) {
    xy.list[[i]] <- xy.df[i,]
}

Body:
The by_row function from the purrrlyr package will do this for you.

This example demonstrates

myfn <- function(row) {
  #row is a tibble with one row, and the same number of columns as the original df
  l <- as.list(row)
  return(l)
}

list_of_lists <- purrrlyr::by_row(df, myfn, .labels=FALSE)$.out

By default, the returned value from myfn is put into a new list column in the df called .out.  The $.out at the end of the above statement immediately selects this column, returning a list of lists.


问:
iPhone OS: Fetching a random entity instance using NSPredicate Nsfetchrequest and core data
Working on an app where I have a large collections of managed objects against which I want to fetch a few random instances.

My question is, is there any way I can use NSPredicate and NSFetchRequest to return several objects at random.

I saw that you could actually add a NSFetchRequest into the entity using the data modeler, any way to do the random fetch using this?

Also what would be the best method for determining the "count" of a table so I can set the bounds of the random number generator.

let me know if you need more details.

Thanks!

Nick

答:
If you are fetching all the objects anyway, there is no need for the first request to get the object count. You can just use something like: </p>

```<code>myEntityCount = [myEntities count]
</code>```

Body:
If you are fetching all the objects anyway, there is no need for the first request to get the object count. You can just use something like:

myEntityCount = [myEntities count]


问:
How to merge two programs on processing ide in order to run them sequentially?
I am trying to merge two programs. One is for a video player that plays the intro video, and the other is for displaying a radar (I found the coding online). What I want to do is, play the video first, which is an introduction to the Radar, and then have the radar displayed. The radar display is linked with Arduino Mega 2560 and that has its own coding. Here are the two codes.

```<code>import processing.video.*;

String PATH = "D:\\FullZord.mp4";
Movie mov;

void setup()
  {
   size(1920, 1080);
   frameRate(30);
   mov = new Movie(this, PATH);
   mov.play();
   mov.speed(1);
   mov.volume(10);
  }

void movieEvent(Movie m)
  {
   m.read();
  }

void draw()
  {
   image(mov, 0, 0, width, height);
  }
</code>```

and

```<code>import processing.serial.*; // imports library for serial communication
import java.awt.event.KeyEvent; // imports library for reading the data from the serial port
import java.io.IOException;
Serial myPort; // defines Object Serial
// defubes variables
String angle="";
String distance="";
String data="";
String noObject;
float pixsDistance;
int iAngle, iDistance;
int index1=0;
int index2=0;
PFont orcFont;

void setup()
  {

    size (1920, 1080);
    smooth();
    myPort = new Serial(this,"COM4", 9600); // starts the serial communication
    myPort.bufferUntil('.'); // reads the data from the serial port up to the character '.'. So actually it reads this: angle,distance.
    orcFont = loadFont("OCRAExtended-30.vlw");
  }

void draw()
  {

   fill(98,245,31);
   textFont(orcFont);
   // simulating motion blur and slow fade of the moving line
   noStroke();
   fill(0,4);
   rect(0, 0, width, 1010);

   fill(98,245,31); // green color
   // calls the functions for drawing the radar
   drawRadar();
   drawLine();
   drawObject();
   drawText();
  }

void serialEvent (Serial myPort)
  { // starts reading data from the Serial Port
// reads the data from the Serial Port up to the character '.' and puts it into the String variable "data".
   data = myPort.readStringUntil('.');
   data = data.substring(0,data.length()-1);

   index1 = data.indexOf(","); // find the character ',' and puts it into
   the
   variable "index1"
   angle= data.substring(0, index1); // read the data from position "0" to position of the variable index1 or thats the value of the angle the Arduino Board sent into the Serial Port
   distance= data.substring(index1+1, data.length()); // read the data from position "index1" to the end of the data pr thats the value of the distance

// converts the String variables into Integer
   iAngle = int(angle);
   iDistance = int(distance);
  }

void drawRadar()
  {
   pushMatrix();
   translate(960,1000); // moves the starting coordinats to new location
   noFill();
   strokeWeight(2);
   stroke(98,245,31);
// draws the arc lines
   arc(0,0,1800,1800,PI,TWO_PI);
   arc(0,0,1400,1400,PI,TWO_PI);
   arc(0,0,1000,1000,PI,TWO_PI);
   arc(0,0,600,600,PI,TWO_PI);
// draws the angle lines
   line(-960,0,960,0);
   line(0,0,-960*cos(radians(30)),-960*sin(radians(30)));
   line(0,0,-960*cos(radians(60)),-960*sin(radians(60)));
   line(0,0,-960*cos(radians(90)),-960*sin(radians(90)));
   line(0,0,-960*cos(radians(120)),-960*sin(radians(120)));
   line(0,0,-960*cos(radians(150)),-960*sin(radians(150)));
   line(-960*cos(radians(30)),0,960,0);
   popMatrix();
  }

void drawObject()
  {
   pushMatrix();
   translate(960,1000); // moves the starting coordinats to new location
   strokeWeight(9);
   stroke(255,10,10); // red color
   pixsDistance = iDistance*22.5; // covers the distance from the sensor from cm to pixels
// limiting the range to 40 cms
   if(iDistance<40){
// draws the object according to the angle and the distance
   line(pixsDistance*cos(radians(iAngle)),-pixsDistance*sin(radians(iAngle)),950*cos(radians(iAngle)),-950*sin(radians(iAn
 gle)));
   }
    popMatrix();
   }
 void drawLine()
   {
    pushMatrix();
    strokeWeight(9);
    stroke(30,250,60);
    translate(960,1000); // moves the starting coordinats to new location
    line(0,0,950*cos(radians(iAngle)),-950*sin(radians(iAngle))); // draws the line according to the angle
    popMatrix();
   }

 void drawText()
   { // draws the texts on the screen

     pushMatrix();
     if(iDistance>40)
       {
        noObject = "Out of Range";
       }
     else
         {
          noObject = "In Range";
         }
     fill(0,0,0);
     noStroke();
     rect(0, 1010, width, 1080);
     fill(98,245,31);
     textSize(25);
     text("10cm",1180,990);
     text("20cm",1380,990);
     text("30cm",1580,990);
     text("40cm",1780,990);
     textSize(40);
     text("Object: " + noObject, 240, 1050);
     text("Angle: " + iAngle +" °", 1050, 1050);
     text("Distance: ", 1380, 1050);

     if(iDistance<40)
       {
        text("        " + iDistance +" cm", 1400, 1050);
       }
     textSize(25);
     fill(98,245,60);
     translate(961+960*cos(radians(30)),982-960*sin(radians(30)));
     rotate(-radians(-60));
     text("30°",0,0);
     resetMatrix();
     translate(954+960*cos(radians(60)),984-960*sin(radians(60)));
     rotate(-radians(-30));
     text("60°",0,0);
     resetMatrix();
     translate(945+960*cos(radians(90)),990-960*sin(radians(90)));
     rotate(radians(0));
     text("90°",0,0);
     resetMatrix();
     translate(935+960*cos(radians(120)),1003-960*sin(radians(120)));
     rotate(radians(-30));
     text("120°",0,0);
     resetMatrix();
     translate(940+960*cos(radians(150)),1018-960*sin(radians(150)));
     rotate(radians(-60));
     text("150°",0,0);
     popMatrix();
    }
</code>```

答:
Solved it! I just used a time-delay function. This one. </p>

```<code>if (millis() > 1000) {
  // do something
   }
</code>```

Body:
I am trying to merge two programs. One is for a video player that plays the intro video, and the other is for displaying a radar (I found the coding online). What I want to do is, play the video first, which is an introduction to the Radar, and then have the radar displayed. The radar display is linked with Arduino Mega 2560 and that has its own coding. Here are the two codes.

import processing.video.*;

String PATH = "D:\\FullZord.mp4";
Movie mov;

void setup()
  {
   size(1920, 1080);
   frameRate(30);
   mov = new Movie(this, PATH);
   mov.play();
   mov.speed(1);
   mov.volume(10);
  }

void movieEvent(Movie m)
  {
   m.read();
  }

void draw()
  {
   image(mov, 0, 0, width, height);
  }

and

import processing.serial.*; // imports library for serial communication
import java.awt.event.KeyEvent; // imports library for reading the data from the serial port
import java.io.IOException;
Serial myPort; // defines Object Serial
// defubes variables
String angle="";
String distance="";
String data="";
String noObject;
float pixsDistance;
int iAngle, iDistance;
int index1=0;
int index2=0;
PFont orcFont;

void setup()
  {

    size (1920, 1080);
    smooth();
    myPort = new Serial(this,"COM4", 9600); // starts the serial communication
    myPort.bufferUntil('.'); // reads the data from the serial port up to the character '.'. So actually it reads this: angle,distance.
    orcFont = loadFont("OCRAExtended-30.vlw");
  }

void draw()
  {

   fill(98,245,31);
   textFont(orcFont);
   // simulating motion blur and slow fade of the moving line
   noStroke();
   fill(0,4);
   rect(0, 0, width, 1010);

   fill(98,245,31); // green color
   // calls the functions for drawing the radar
   drawRadar();
   drawLine();
   drawObject();
   drawText();
  }

void serialEvent (Serial myPort)
  { // starts reading data from the Serial Port
// reads the data from the Serial Port up to the character '.' and puts it into the String variable "data".
   data = myPort.readStringUntil('.');
   data = data.substring(0,data.length()-1);

   index1 = data.indexOf(","); // find the character ',' and puts it into
   the
   variable "index1"
   angle= data.substring(0, index1); // read the data from position "0" to position of the variable index1 or thats the value of the angle the Arduino Board sent into the Serial Port
   distance= data.substring(index1+1, data.length()); // read the data from position "index1" to the end of the data pr thats the value of the distance

// converts the String variables into Integer
   iAngle = int(angle);
   iDistance = int(distance);
  }

void drawRadar()
  {
   pushMatrix();
   translate(960,1000); // moves the starting coordinats to new location
   noFill();
   strokeWeight(2);
   stroke(98,245,31);
// draws the arc lines
   arc(0,0,1800,1800,PI,TWO_PI);
   arc(0,0,1400,1400,PI,TWO_PI);
   arc(0,0,1000,1000,PI,TWO_PI);
   arc(0,0,600,600,PI,TWO_PI);
// draws the angle lines
   line(-960,0,960,0);
   line(0,0,-960*cos(radians(30)),-960*sin(radians(30)));
   line(0,0,-960*cos(radians(60)),-960*sin(radians(60)));
   line(0,0,-960*cos(radians(90)),-960*sin(radians(90)));
   line(0,0,-960*cos(radians(120)),-960*sin(radians(120)));
   line(0,0,-960*cos(radians(150)),-960*sin(radians(150)));
   line(-960*cos(radians(30)),0,960,0);
   popMatrix();
  }

void drawObject()
  {
   pushMatrix();
   translate(960,1000); // moves the starting coordinats to new location
   strokeWeight(9);
   stroke(255,10,10); // red color
   pixsDistance = iDistance*22.5; // covers the distance from the sensor from cm to pixels
// limiting the range to 40 cms
   if(iDistance<40){
// draws the object according to the angle and the distance
   line(pixsDistance*cos(radians(iAngle)),-pixsDistance*sin(radians(iAngle)),950*cos(radians(iAngle)),-950*sin(radians(iAn
 gle)));
   }
    popMatrix();
   }
 void drawLine()
   {
    pushMatrix();
    strokeWeight(9);
    stroke(30,250,60);
    translate(960,1000); // moves the starting coordinats to new location
    line(0,0,950*cos(radians(iAngle)),-950*sin(radians(iAngle))); // draws the line according to the angle
    popMatrix();
   }

 void drawText()
   { // draws the texts on the screen

     pushMatrix();
     if(iDistance>40)
       {
        noObject = "Out of Range";
       }
     else
         {
          noObject = "In Range";
         }
     fill(0,0,0);
     noStroke();
     rect(0, 1010, width, 1080);
     fill(98,245,31);
     textSize(25);
     text("10cm",1180,990);
     text("20cm",1380,990);
     text("30cm",1580,990);
     text("40cm",1780,990);
     textSize(40);
     text("Object: " + noObject, 240, 1050);
     text("Angle: " + iAngle +" °", 1050, 1050);
     text("Distance: ", 1380, 1050);

     if(iDistance<40)
       {
        text("        " + iDistance +" cm", 1400, 1050);
       }
     textSize(25);
     fill(98,245,60);
     translate(961+960*cos(radians(30)),982-960*sin(radians(30)));
     rotate(-radians(-60));
     text("30°",0,0);
     resetMatrix();
     translate(954+960*cos(radians(60)),984-960*sin(radians(60)));
     rotate(-radians(-30));
     text("60°",0,0);
     resetMatrix();
     translate(945+960*cos(radians(90)),990-960*sin(radians(90)));
     rotate(radians(0));
     text("90°",0,0);
     resetMatrix();
     translate(935+960*cos(radians(120)),1003-960*sin(radians(120)));
     rotate(radians(-30));
     text("120°",0,0);
     resetMatrix();
     translate(940+960*cos(radians(150)),1018-960*sin(radians(150)));
     rotate(radians(-60));
     text("150°",0,0);
     popMatrix();
    }

Body:
Solved it! I just used a time-delay function. This one.

if (millis() > 1000) {
  // do something
   }