问:
Pre-populate modal textarea with text
Currently a button opens a modal that includes a text box. I need have that text box pre-populated, so I have attempted to mess around with the modal with no luck.

I have tried the following and nothing appears to happen.

function testFunc(){
    $('#contactUsDlg').modal('show');
    $('#contactUsDlg').on('shown.bs.modal', function {
       $('#message-text').text("test");
    });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" name="btn-ask" id="nonconform-btn" data-form-action-url="${newMessageUrl}"
                                data-pns="<%=OrderStatusPortletConstants.MESSAGE_CENTER_PORTLET_NAMESPACE %>"
                                data-use-ajax="true"
                                class="btn btn-submit btn-ask contact-us-dlg"
                                data-hidden-fields="message-order-id,message-source-url"
                                data-message-order-id="${selectedOrder.id}" data-message-source-url="${sourceUrl}" >
                                Contact Us
</button></code>```

答:
This is a possible solution basen on your snippets (not complete, IMHO)

$(document).ready(function() {
  $('#contactUsModal').on('show.bs.modal', function(e) {
    var text = $(e.relatedTarget).data('default-text');
    $(this).find('#message-text').text(text);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">

<button type="button" name="btn-ask" class="btn btn-submit btn-ask contact-us-dlg" data-form-action-url="${newMessageUrl}" data-pns="<%=OrderStatusPortletConstants.MESSAGE_CENTER_PORTLET_NAMESPACE %>" data-use-ajax="true" data-hidden-fields="message-order-id,message-source-url"
data-message-order-id="${selectedOrder.id}" data-message-source-url="${sourceUrl}" data-toggle="modal" data-target="#contactUsModal" data-default-text="Initial contact us textarea modal content">
  Contact Us
</button>

<div class="modal fade" id="contactUsModal" tabindex="-1" role="dialog" aria-labelledby="contactUsModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h4 class="modal-title" id="exampleModalLabel">New message</h4>
      </div>
      <div class="modal-body">
        <form>
          <div class="form-group">
            <label for="recipient-name" class="control-label">Recipient:</label>
            <input type="text" class="form-control" id="recipient-name">
          </div>
          <div class="form-group">
            <label for="message-text" class="control-label">Message:</label>
            <textarea class="form-control" id="message-text"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Send message</button>
      </div>
    </div>
  </div>
</div></code>```

Title: Pre-populate modal textarea with text

Body:
Currently a button opens a modal that includes a text box. I need have that text box pre-populated, so I have attempted to mess around with the modal with no luck.

I have tried the following and nothing appears to happen.

function testFunc(){
    $('#contactUsDlg').modal('show');
    $('#contactUsDlg').on('shown.bs.modal', function {
       $('#message-text').text("test");
    });
}

<button type="button" name="btn-ask" id="nonconform-btn" data-form-action-url="${newMessageUrl}"
                                data-pns="<%=OrderStatusPortletConstants.MESSAGE_CENTER_PORTLET_NAMESPACE %>"
                                data-use-ajax="true"
                                class="btn btn-submit btn-ask contact-us-dlg"
                                data-hidden-fields="message-order-id,message-source-url"
                                data-message-order-id="${selectedOrder.id}" data-message-source-url="${sourceUrl}" >
                                Contact Us
</button>

Body:
This is a possible solution basen on your snippets (not complete, IMHO)

$(document).ready(function() {
  $('#contactUsModal').on('show.bs.modal', function(e) {
    var text = $(e.relatedTarget).data('default-text');
    $(this).find('#message-text').text(text);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">

<button type="button" name="btn-ask" class="btn btn-submit btn-ask contact-us-dlg" data-form-action-url="${newMessageUrl}" data-pns="<%=OrderStatusPortletConstants.MESSAGE_CENTER_PORTLET_NAMESPACE %>" data-use-ajax="true" data-hidden-fields="message-order-id,message-source-url"
data-message-order-id="${selectedOrder.id}" data-message-source-url="${sourceUrl}" data-toggle="modal" data-target="#contactUsModal" data-default-text="Initial contact us textarea modal content">
  Contact Us
</button>

<div class="modal fade" id="contactUsModal" tabindex="-1" role="dialog" aria-labelledby="contactUsModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="exampleModalLabel">New message</h4>
      </div>
      <div class="modal-body">
        <form>
          <div class="form-group">
            <label for="recipient-name" class="control-label">Recipient:</label>
            <input type="text" class="form-control" id="recipient-name">
          </div>
          <div class="form-group">
            <label for="message-text" class="control-label">Message:</label>
            <textarea class="form-control" id="message-text"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Send message</button>
      </div>
    </div>
  </div>
</div>


来源: stackexchange

问:
Problems on AWS Firehose intermediate S3 bucket and delivery stream dependency

Is is a good idea to set one s3 bucket for multiple delivery streams? (ex: consider two delivery streams having different streaming throughput, s3 buffer size / buffer interval...)

If two delivery streams (S1, S2) are routing data into redshift. S1 is delivering data into T1, and S2 to T2. In T2 there's a foreign key constraint on T1. Is it possible to guarantee that when S2 delivers data (D2) to T2, all records in T1 referenced by D2 have already been delivered by S1 ? (i.e. there are dependencies in delivery streams)

BTW I'm using firehose to push my application log into redshift for analytics.

答:
Assumptions: T1 and T2 are tables in the same Redshift cluster.

You can (virtually) have as many S3 buckets as you want. It's not a good idea to use the same S3 bucket for two delivery streams, as the COPY command performed by Redshift to load the data into the cluster will look into the same Manifest folder, for both delivery streams.

From Amazon Kinesis Firehose FAQ:

Q: What is the manifests folder in my Amazon S3 bucket?

For Amazon Redshift destination, Amazon Kinesis Firehose generates manifest files to load Amazon S3 objects to Redshift cluster in batch. The manifests folder stores the manifest files generated by Firehose.

ContentLicense: CC BY-SA 3.0


问:
Count Stored Procedures in Database?
How can i count the number of stored procedures in my database and is it a bad practice to have too many stored procedures?</p>

答:
If you use them, then there really is no such thing as "too many".

I had a developer concerned his stored procs were using too much space in the database, so I had to actually calculate the total SIZE of all stored procs. Good answer for that here. The upshot was that the size of the stored procs together was responsible for maybe .001% of the total size of the database.

OwnerDisplayName: Jack

Title: Count Stored Procedures in Database?

LastEditorDisplayName: Cade Roux

OwnerDisplayName: BradC

ContentLicense: CC BY-SA 2.5


问:
How do I keep the divs side by side in the container?
I want to create container that has two elements with colors given in the picture.  The two are different divs and must stay side by side.  How do I do it?

Here is my code:

  <title>Testing</title>

```

答:
How about using css-flex.</p>

```<code>#main {
width: 100%;
border: 1px solid #c3c3c3;
display: -webkit-flex; /* Safari */
-webkit-flex-direction: row-reverse; /* Safari 6.1+ */
display: flex;
flex-direction: row-reverse;
}
.div1 {
width: 25%;
height: 50px;
}
.div2 {
width: 75%;
height: 50px;
}
<div id="main">
  <div class="div1" style="background-color:coral;">A</div>
  <div class="div2" style="background-color:lightblue;">B</div>
</div>
</code>```

Body:
How about using css-flex.

#main {
width: 100%;
border: 1px solid #c3c3c3;
display: -webkit-flex; /* Safari */
-webkit-flex-direction: row-reverse; /* Safari 6.1+ */
display: flex;
flex-direction: row-reverse;
}
.div1 {
width: 25%;
height: 50px;
}
.div2 {
width: 75%;
height: 50px;
}
<div id="main">
  <div class="div1" style="background-color:coral;">A</div>
  <div class="div2" style="background-color:lightblue;">B</div>
</div>


问:
Displaying all aggregated results from Elasticsearch query in PHP
I have a field called "arrivalDate" and this field is a string. Each document has an arrivalDate in string format (ex: 20110128). I want my output to be something like this (date and the number of records that have that date):

Date : how many records have that date

20110105 : 5 records

20120501 : 2 records

20120602 : 15 records

I already have the query to get these results.

I am trying to display aggregated results in PHP from Elasticsearch. I want my output to be something like this:

Date : how many records have that date

20110105 : 5 records

20120501 : 2 records

20120602 : 15 records
This is what I have so far:

```<code>    $json = '{"aggs": { "group_by_date": { "terms": { "field": "arrivalDate" } } } }';

        $params = [
            'index' => 'pickups',
            'type' => 'external',
            'body' => $json
            ];

$results = $es->search($params);
</code>```

However, I don't know how to display the results in PHP. For example, if I wanted to display the total number of documents I would do echo $results['hits']['total'] How could I display all the dates with the number of records they have in PHP?

答:
I'd suggest using aggregations in the same way you construct the query, from my experience it seems to work quicker. Please see the below code:

```<code>'aggs' => [
    'group_by_date' => [
        'terms' => [
            'field' => 'arrivalDate',
            'size' => 500
        ]
    ]
]
</code>```

Following that, instead of using the typical results['hits']['hits'] you would switch out the hits parts to results['aggregations']. Then access the returning data by accessing the buckets in the response.

For accessing the data from the aggregation shown above, it would likely be something along the lines of:

```<code>foreach ($results as $result){
    foreach($result['buckets'] as $record){
        echo($record['key']);
    }
}
</code>```

There will be a better way of accessing the array within the array, however, the above loop system works well for me. If you have any issues with accessing the data, let me know.

Body:
I have a field called "arrivalDate" and this field is a string. Each document has an arrivalDate in string format (ex: 20110128). I want my output to be something like this (date and the number of records that have that date):

Date : how many records have that date

20110105 : 5 records

20120501 : 2 records

20120602 : 15 records

I already have the query to get these results.

I am trying to display aggregated results in PHP from Elasticsearch. I want my output to be something like this:

Date : how many records have that date

20110105 : 5 records

20120501 : 2 records

20120602 : 15 records
This is what I have so far:

    $json = '{"aggs": { "group_by_date": { "terms": { "field": "arrivalDate" } } } }';

        $params = [
            'index' => 'pickups',
            'type' => 'external',
            'body' => $json
            ];

$results = $es->search($params);

However, I don't know how to display the results in PHP. For example, if I wanted to display the total number of documents I would do echo $results['hits']['total'] How could I display all the dates with the number of records they have in PHP?

Body:
I'd suggest using aggregations in the same way you construct the query, from my experience it seems to work quicker. Please see the below code:

'aggs' => [
    'group_by_date' => [
        'terms' => [
            'field' => 'arrivalDate',
            'size' => 500
        ]
    ]
]

Following that, instead of using the typical results['hits']['hits'] you would switch out the hits parts to results['aggregations']. Then access the returning data by accessing the buckets in the response.

For accessing the data from the aggregation shown above, it would likely be something along the lines of:

foreach ($results as $result){
    foreach($result['buckets'] as $record){
        echo($record['key']);
    }
}

There will be a better way of accessing the array within the array, however, the above loop system works well for me. If you have any issues with accessing the data, let me know.


问:
box/spout - freeze 1st row (pane) of spreadsheet
Is it possible to freeze 1st row (freeze pane) of the spreadsheet using box/spout?

With PHPexcel I do like that:

```<code>$objPHPExcel=new PHPExcel();
$ActiveSheet=$objPHPExcel->getActiveSheet();
$ActiveSheet->freezePane('A2');
</code>```

Cannot use PHPexcel, as I am working with big files.

答: It's not possible to freeze panes with Spout yet. But you can always fork the repo and implement this feature :)</p>

Body:
Is it possible to freeze 1st row (freeze pane) of the spreadsheet using box/spout?

With PHPexcel I do like that:

$objPHPExcel=new PHPExcel();
$ActiveSheet=$objPHPExcel->getActiveSheet();
$ActiveSheet->freezePane('A2');

Cannot use PHPexcel, as I am working with big files.


问:
Pythonanywhere - Error code: Unhandled Exception
Using Python 2.7 and Django 1.10.4, I was trying to deploy my app to pythonanywhere, but I keep getting this error.

Error Log

wsgi.py

```<code>import os
import sys

path = '/home/hellcracker/First-Blog'
if path not in sys.path:
    sys.path.append(path)

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

from django.core.wsgi import get_wsgi_application
from django.contrib.staticfiles.handlers import StaticFilesHandler
application = StaticFilesHandler(get_wsgi_application())
</code>```

I can't tell where the error is coming from.

Any help would be appreciated!

答:
Make sure that your project name is "mysite" if not update this line

```<code>os.environ['DJANGO_SETTINGS_MODULE'] = '<your-project-name>.settings'
</code>```

Project name will be the directory name parent to your app name, see that in your local machine.

Body:
Using Python 2.7 and Django 1.10.4, I was trying to deploy my app to pythonanywhere, but I keep getting this error.

Error Log

wsgi.py

import os
import sys

path = '/home/hellcracker/First-Blog'
if path not in sys.path:
    sys.path.append(path)

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

from django.core.wsgi import get_wsgi_application
from django.contrib.staticfiles.handlers import StaticFilesHandler
application = StaticFilesHandler(get_wsgi_application())

I can't tell where the error is coming from.

Any help would be appreciated!

Body:
Make sure that your project name is "mysite" if not update this line

os.environ['DJANGO_SETTINGS_MODULE'] = '<your-project-name>.settings'

Project name will be the directory name parent to your app name, see that in your local machine.


问:
Get list of classes from array of elements
I have the following array that holds a number of option elements, depending on if it has the hidden class or not.

```<code>var list = $('#condition option').not('.hidden');
</code>```

How can I get an array of classes these elements have?

What I have tried:

```<code>var list = $('#condition option').not('.hidden').attr('class');
</code>```

However, this only returns classes associated with the last element in the array.

答:
You can do that using jQuery.each() function

Example:

var list = $('#condition option').not('.hidden'),
    classes = [];

$(list).each(function () {
  classes.push($(this).attr('class'));
});

console.log(classes);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="condition">
   <option class="some-class-1" > some option </option>
   <option class="some-class-2" > some option </option>
   <option class="some-class-3" > some option </option>
   <option class="some-class-4" > some option </option>
   <option class="some-class-5" > some option </option>
   <option class="some-class-6" > some option </option>
   <option class="some-class-7" > some option </option>
   <option class="some-class-8" > some option </option>
</select></code>```

Update

If you want to split/separate every single element, for example if some option have some classes like class-1-a, class-1-b .. etc

in this case you may need String.prototype.split()

Example

var list = $('#condition option').not('.hidden'),
    allClasses = [];

$(list).each(function () {
  var elemClasses = $(this).attr('class');
    elemClasses.trim().split(/\s+/).map(function (x) {
        allClasses.push(x);
    })

});

console.log(allClasses);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="condition">
   <option class="some-class-1-a        some-class-1-b" > some option </option>
   <option class="some-class-2-a some-class-1-b " > some option </option>
   <option class="some-class-3" > some option </option>
   <option class="some-class-4" > some option </option>
   <option class="some-class-5" > some option </option>
   <option class="some-class-6" > some option </option>
   <option class="some-class-7" > some option </option>
   <option class="some-class-8" > some option </option>
</select></code>```

Body:
I have the following array that holds a number of option elements, depending on if it has the hidden class or not.

var list = $('#condition option').not('.hidden');

How can I get an array of classes these elements have?

What I have tried:

var list = $('#condition option').not('.hidden').attr('class');

However, this only returns classes associated with the last element in the array.

Body:
You can do that using jQuery.each() function

Example:

var list = $('#condition option').not('.hidden'),
    classes = [];

$(list).each(function () {
  classes.push($(this).attr('class'));
});

console.log(classes);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="condition">
   <option class="some-class-1" > some option </option>
   <option class="some-class-2" > some option </option>
   <option class="some-class-3" > some option </option>
   <option class="some-class-4" > some option </option>
   <option class="some-class-5" > some option </option>
   <option class="some-class-6" > some option </option>
   <option class="some-class-7" > some option </option>
   <option class="some-class-8" > some option </option>
</select>

Update

If you want to split/separate every single element, for example if some option have some classes like class-1-a, class-1-b .. etc

in this case you may need String.prototype.split()

Example

var list = $('#condition option').not('.hidden'),
    allClasses = [];

$(list).each(function () {
  var elemClasses = $(this).attr('class');
    elemClasses.trim().split(/\s+/).map(function (x) {
        allClasses.push(x);
    })

});

console.log(allClasses);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="condition">
   <option class="some-class-1-a        some-class-1-b" > some option </option>
   <option class="some-class-2-a some-class-1-b " > some option </option>
   <option class="some-class-3" > some option </option>
   <option class="some-class-4" > some option </option>
   <option class="some-class-5" > some option </option>
   <option class="some-class-6" > some option </option>
   <option class="some-class-7" > some option </option>
   <option class="some-class-8" > some option </option>
</select>


问:
Opening an iframe from another iframe using JQuery's Colorbox plug-in
I need to open an iframe (Frame 1) and from frame1 i need to open frame2 using jquery colorbox.

I have used the following script from a page to open frame1:

```<code>function ViewUser(Id) {
       $.colorbox({ href: '/user/View/' + Id + '?popup=1', iframe: true, width: "100%", height: "100%", title: 'View User', overlayClose: false, escKey: false, onLoad: function() { $('#cboxClose').hide() }, onComplete: function() { $('#cboxClose').show() } });
}
</code>```

I have added the following script from frame1 to open frame2, but its not opening the page (just opens a blank colorbox).

```<code>function UpdateUser(Id) {
  parent.$.colorbox.close();
  parent.$.colorbox({ href: '/User/Update/' + Id + '?popup=1', iframe: true, width: "100%", height: "100%", title: 'Update User', overlayClose: false, escKey: false, onLoad: function() { $('#cboxClose').hide() }, onComplete: function() { $('#cboxClose').show() } });
}
</code>```

Am i missing anything here?

答:
For me, it worked by simply by leaving out the close() call:

```<code>function UpdateUser(Id) {
  parent.$.colorbox({ href: '/User/Update/' + Id + '?popup=1', iframe: true, width: "100%", height: "100%", title: 'Update User', overlayClose: false, escKey: false, onLoad: function() { $('#cboxClose').hide() }, onComplete: function() { $('#cboxClose').show() } });
}
</code>```

This will load the new content into the old colorbox.

Body:
I need to open an iframe (Frame 1) and from frame1 i need to open frame2 using jquery colorbox.

I have used the following script from a page to open frame1:

function ViewUser(Id) {
       $.colorbox({ href: '/user/View/' + Id + '?popup=1', iframe: true, width: "100%", height: "100%", title: 'View User', overlayClose: false, escKey: false, onLoad: function() { $('#cboxClose').hide() }, onComplete: function() { $('#cboxClose').show() } });
}

I have added the following script from frame1 to open frame2, but its not opening the page (just opens a blank colorbox).

function UpdateUser(Id) {
  parent.$.colorbox.close();
  parent.$.colorbox({ href: '/User/Update/' + Id + '?popup=1', iframe: true, width: "100%", height: "100%", title: 'Update User', overlayClose: false, escKey: false, onLoad: function() { $('#cboxClose').hide() }, onComplete: function() { $('#cboxClose').show() } });
}

Am i missing anything here?

Body:
For me, it worked by simply by leaving out the close() call:

function UpdateUser(Id) {
  parent.$.colorbox({ href: '/User/Update/' + Id + '?popup=1', iframe: true, width: "100%", height: "100%", title: 'Update User', overlayClose: false, escKey: false, onLoad: function() { $('#cboxClose').hide() }, onComplete: function() { $('#cboxClose').show() } });
}

This will load the new content into the old colorbox.


问:
Get all possible strings in printable ASCII
How can I get all possible strings in printable ASCII (eg. 0x20 () to  0x7E (~)) using a generator? It should output (if continually called with .next()):

```<code>
!
"
#
$
</code>```

...

```<code>~

 !
 "
 #
 $
</code>```

and so on. How can I do this?

```<code>var gen = function * (){
    var counter = 0x20;
    while(true) yield String.fromCharCode(++counter);
};
</code>```

works up to 94 tries (~). How I get this to work after that?

答:
I propose a recursive generator solution:

// Generate chars:
function* chars(from, to) {
  while (from <= to) yield String.fromCharCode(from++);
}

// Generate words from chars:
function* words(from, to) {
  yield* chars(from, to);
  for (let word of words(from, to)) {
    for (let char of chars(from, to)) {
      yield word + char;
    }
  }
}

// Example:
let w = words(0x20, 0x7E);
setInterval(() => console.log(w.next().value), 50);```

Body:
How can I get all possible strings in printable ASCII (eg. 0x20 () to  0x7E (~)) using a generator? It should output (if continually called with .next()):

!
"
#
$

...

~

 !
 "
 #
 $

and so on. How can I do this?

var gen = function * (){
    var counter = 0x20;
    while(true) yield String.fromCharCode(++counter);
};

works up to 94 tries (~). How I get this to work after that?


问:
make a string a new instant of a class in C#
I am facing a problem I can not solve. and I hope someone can.

// I got Table saved in M.SQL server as in Picture

// Code

DB_Context MYDB = new DB_Context();
var ALL = MYDB.select(x => x );

I want to instantiate every string ( i.Position) as a new instant name of class ARTICLE.like the followings

 foreach ( var i in ALL)
{
ARTICLE "i.Position" = new ARTICLE();
"i.Name".A_STOCK = i.Stock ;
}

// The Class
public Class ARTICLE
{
public int A_STOCK { get; set;}

}

// later I want to recall it to get its A_STOCK value , for example

int k1 = A1.A_STOCK ;
int k2 = A2.A_STOCK ;```

//
In short , I want to retrieve all strings in Position Column and convert every string of them into a a new instant of class (ARTICLE) carries then instant name ...

Thank you very much ...

答:
Pretty easy, just do it in your select using object initialization syntax.

```<code>DB_Context MYDB = new DB_Context();
var ALL = MYDB.select(x => { new ARTICLE { A_STOCK = x.Stock};  );
</code>```

After making this change, ALL will contain a list of ARTICLE objects instead of a list of strings.

Body:
I am facing a problem I can not solve. and I hope someone can.

// I got Table saved in M.SQL server as in Picture

// Code

DB_Context MYDB = new DB_Context();
var ALL = MYDB.select(x => x );

I want to instantiate every string ( i.Position) as a new instant name of class ARTICLE.like the followings

 foreach ( var i in ALL)
{
ARTICLE "i.Position" = new ARTICLE();
"i.Name".A_STOCK = i.Stock ;
}

// The Class
public Class ARTICLE
{
public int A_STOCK { get; set;}

}

// later I want to recall it to get its A_STOCK value , for example

int k1 = A1.A_STOCK ;
int k2 = A2.A_STOCK ;

//
In short , I want to retrieve all strings in Position Column and convert every string of them into a a new instant of class (ARTICLE) carries then instant name ...

Thank you very much ...

Body:
Pretty easy, just do it in your select using object initialization syntax.

DB_Context MYDB = new DB_Context();
var ALL = MYDB.select(x => { new ARTICLE { A_STOCK = x.Stock};  );

After making this change, ALL will contain a list of ARTICLE objects instead of a list of strings.


问:
How Would I write this Regular Expression?
How would I write a Regular Expression for this?

```<code>Backup 1 of (anything here, maybe multiple words).html
</code>```

I thought it would be this

```<code>Backup\s1\sof(.*)\.html
</code>```

but it's not working. I'm using power grep... am I supposed to put something at the beginning and end? Thanks!

答:
```<code>^Backup\s\d+\sof\s\([^\(\)]+\)\.html$
</code>```

^ assert start of string

Backup matches characters "Backup"

\s matches any whitespace character

\d+ matches one or more numbers

\s matches any whitespace character

of matches characters "of"

\s matches any whitespace character

\( matches character '('

[^\(\)]+ matches one or more characters not including '(' or ')' characters

\) matches character ')'

\. matches character '.'

html matches characters "html"

$ assert end of string

Body:
How would I write a Regular Expression for this?

Backup 1 of (anything here, maybe multiple words).html

I thought it would be this

Backup\s1\sof(.*)\.html

but it's not working. I'm using power grep... am I supposed to put something at the beginning and end? Thanks!

Body:
^Backup\s\d+\sof\s\([^\(\)]+\)\.html$

^ assert start of string

Backup matches characters "Backup"

\s matches any whitespace character

\d+ matches one or more numbers

\s matches any whitespace character

of matches characters "of"

\s matches any whitespace character

\( matches character '('

[^\(\)]+ matches one or more characters not including '(' or ')' characters

\) matches character ')'

\. matches character '.'

html matches characters "html"

$ assert end of string


问:
Error: Uncaught (in promise): Error: Cannot find primary outlet to load 'AppComponent'
I changed my routes so that my homepage is the appcomponent, and now I'm getting this error:

```<code>Error: Uncaught (in promise): Error: Cannot find primary outlet to load 'AppComponent'
</code>```

Any thoughts as to what this could be?

My routes:

```<code>import {Routes} from "@angular/router";
import {PatientComponent} from "./patient/patient.component";
import {AppComponent} from "./app.component";

export const routes: Routes = [
  {path: '', component: AppComponent},
  {path: 'patient/:id', component: PatientComponent},

];
</code>```

my app component:

```<code>import {Component, OnInit} from '@angular/core';
import {AfdelingService} from './afdeling.service';
import {PatientService} from './patient.service';
import 'rxjs/Rx';
import {Router} from "@angular/router";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [AfdelingService, PatientService]
})
export class AppComponent implements OnInit {
  errorMessage: string;
  afdeling = [];

  constructor(private afdelingService: AfdelingService, private router: Router) {
  }

  ngOnInit() {
    this.getData()
  }

  goToAfdeling(afdeling) {
    console.log(afdeling.afdelingsNaam);
    this.router.navigate(["/afdelingen", afdeling.afdelingsNaam]);
  }

  getData() {
    this.afdelingService.getAfdelingen()
      .subscribe(
        data => {
          this.afdeling = data;
          console.log(this.afdeling);
        }, error => this.errorMessage = <any> error);

  }
}
</code>```

答:
AppComponent should not be a routed component. Instead, it should only be the entry point for your application. This means, that the template should at least contain the router outlet in some part of it, the css selector of app component should be in your index.html file and AppComponent should be declared inside of the bootstrap list of you AppModule.

See this SO question for more info

Body:
I changed my routes so that my homepage is the appcomponent, and now I'm getting this error:

Error: Uncaught (in promise): Error: Cannot find primary outlet to load 'AppComponent'

Any thoughts as to what this could be?

My routes:

import {Routes} from "@angular/router";
import {PatientComponent} from "./patient/patient.component";
import {AppComponent} from "./app.component";

export const routes: Routes = [
  {path: '', component: AppComponent},
  {path: 'patient/:id', component: PatientComponent},

];

my app component:

import {Component, OnInit} from '@angular/core';
import {AfdelingService} from './afdeling.service';
import {PatientService} from './patient.service';
import 'rxjs/Rx';
import {Router} from "@angular/router";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [AfdelingService, PatientService]
})
export class AppComponent implements OnInit {
  errorMessage: string;
  afdeling = [];

  constructor(private afdelingService: AfdelingService, private router: Router) {
  }

  ngOnInit() {
    this.getData()
  }

  goToAfdeling(afdeling) {
    console.log(afdeling.afdelingsNaam);
    this.router.navigate(["/afdelingen", afdeling.afdelingsNaam]);
  }

  getData() {
    this.afdelingService.getAfdelingen()
      .subscribe(
        data => {
          this.afdeling = data;
          console.log(this.afdeling);
        }, error => this.errorMessage = <any> error);

  }
}


问:
click the bottom part of an element?
I have a link that I need to click on that is halfway underneath another element.  Something like this:

```<code>______________________
| A  ____________    | <-- on top
|____|B_________|____|
     |__________| < - on bottom (need to click this one)
</code>```

When I try to click on the bottom link, I get

```<code>(B) is not clickable at point (254, 5). Other element would receive the click: (A).
</code>```

Here is an image (I need to click on the PO Box link).  I don't know exactly what to do here.  Thanks!

Here is the HTML in question.  Selenium is sending the click action to the span labelFieldWrapper:

```<code><div class='clr type_address formFieldContainer'>
    <span class="labelFieldWrapper">
        <label class="placeholder" for="address1">
            <span class="labelText">Address 1</span>
        </label>
        <input id="address1" name="address1" type="text" value="" autofillparam="ON" size="20" maxlength="60"/><span class="asterisk">*</span>
    </span>
    <p class="helpLink">
        <a href="javascript: void(0)"
           onclick="window.open('/checkout/canadian_province_support.jsp',
          'pobox',
          'width=450, \
           height=200, \
           directories=no, \
           location=no, \
           menubar=no, \
           resizable=no, \
           scrollbars=1, \
           status=no, \
           toolbar=no');
          return false;">PO Box?</a>  <-- Trying to click on this link
        </p>
    </div><!-- /formFieldContainer -->
</code>```

答:
This mostly happens in Chrome. Chrome does not calculate the exact location of element and always click in the middle of Element.

To fix this, get the element coordinate and then click on the link

```<code>WebElement link= driver.findElement(By.xpath("xpath of link"));
((JavascriptExecutor)driver).executeScript("window.scrollTo(0,"+link.getLocation().x+")");
link.click();
</code>```

Title: click the bottom part of an element?

Body:
I have a link that I need to click on that is halfway underneath another element.  Something like this:

______________________
| A  ____________    | <-- on top
|____|B_________|____|
     |__________| < - on bottom (need to click this one)

When I try to click on the bottom link, I get

(B) is not clickable at point (254, 5). Other element would receive the click: (A).

Here is an image (I need to click on the PO Box link).  I don't know exactly what to do here.  Thanks!

Here is the HTML in question.  Selenium is sending the click action to the span labelFieldWrapper:

            Address 1

        <input id="address1" name="address1" type="text" value="" autofillparam="ON" size="20" maxlength="60"/>*

        PO Box?  <-- Trying to click on this link

Body:
This mostly happens in Chrome. Chrome does not calculate the exact location of element and always click in the middle of Element.

To fix this, get the element coordinate and then click on the link

WebElement link= driver.findElement(By.xpath("xpath of link"));
((JavascriptExecutor)driver).executeScript("window.scrollTo(0,"+link.getLocation().x+")");
link.click();


问:
extract structs values into variable named as the field
I have a 1x1 Matlab struct with 5 fields ('a', 'b', 'c', 'd', 'e'). Each field contains some sort of data (which doesn't really matter for my question) and I would like to extract each value out of the struct and assign it to a variable named as the field. Any idea for a code that will do it?</p>

答:
While it is generally not best practice to spread data out to a bunch of variables when you already have it neatly stored in a structure, an easy way to move structure fields to variables that doesn't require hard-coding your field/variables names would be to use the save and load commands like so:

```<code>s = struct('a', 1, 'b', 2, 'c', 3);  % A sample structure
save('temp.mat', '-struct', 's');    % Save fields to a .mat file
clear all                            % Clear local variables (just for display purposes)
load('temp.mat');                    % Load the variables from the file
whos                                 % Display local variables

  Name      Size            Bytes  Class     Attributes

  a         1x1                 8  double
  b         1x1                 8  double
  c         1x1                 8  double
</code>```

Pro: this is very easy and works for any structure. Con: it involves moving data into and out of a file.

Body:
While it is generally not best practice to spread data out to a bunch of variables when you already have it neatly stored in a structure, an easy way to move structure fields to variables that doesn't require hard-coding your field/variables names would be to use the save and load commands like so:

s = struct('a', 1, 'b', 2, 'c', 3);  % A sample structure
save('temp.mat', '-struct', 's');    % Save fields to a .mat file
clear all                            % Clear local variables (just for display purposes)
load('temp.mat');                    % Load the variables from the file
whos                                 % Display local variables

  Name      Size            Bytes  Class     Attributes

  a         1x1                 8  double
  b         1x1                 8  double
  c         1x1                 8  double

Pro: this is very easy and works for any structure. Con: it involves moving data into and out of a file.


问:
PHPUnit can't find Phalcon's Callback validator (namespace issue)
I'm using Phalcon 3.0.3 and PHP 7.0.15-0ubuntu0.16.04.4 with PHPUnit 6.0.8. If I try to use Phalcon\Validation\Validator\Callback I'll always end up with those kind of errros:

1) Test\ConfirmActivityTest::testConfirm
Error: Class 'Phalcon\Validation\Validator\Callback' not found

So far the only way I found to solve this problem is to create a copy of that class in my codebase:

namespace Phapp\Validators;

```<code>/**
 * A workaround to fix the namespace problem of
 * Phalcon\Validation\Validator\Callback
 *
 */
class CallbackValidator extends \Phalcon\Validation\Validator
{

    /**
     * Executes the validation
     *
     * @param \Phalcon\Validation $validation
     * @param string $field
     * @return bool
     */
    public function validate(\Phalcon\Validation $validation, $field) {}

}
</code>```

Is there any other workaround I could use to solve this problem? Is it a Phalcon bug?

答: Callback validator was added in 3.1.0. Docs were by mistake merged as i remember.</p>

Body:
I'm using Phalcon 3.0.3 and PHP 7.0.15-0ubuntu0.16.04.4 with PHPUnit 6.0.8. If I try to use Phalcon\Validation\Validator\Callback I'll always end up with those kind of errros:

1) Test\ConfirmActivityTest::testConfirm
Error: Class 'Phalcon\Validation\Validator\Callback' not found

So far the only way I found to solve this problem is to create a copy of that class in my codebase:

namespace Phapp\Validators;

/**
 * A workaround to fix the namespace problem of
 * Phalcon\Validation\Validator\Callback
 *
 */
class CallbackValidator extends \Phalcon\Validation\Validator
{

    /**
     * Executes the validation
     *
     * @param \Phalcon\Validation $validation
     * @param string $field
     * @return bool
     */
    public function validate(\Phalcon\Validation $validation, $field) {}

}

Is there any other workaround I could use to solve this problem? Is it a Phalcon bug?


问:
What would prevent code running in a Docker container from connecting to a database on a separate server?
I have a .NET Core 1.1 app running in a Docker container on Ubuntu 14.04, and it fails to connect to the SQL Server database running on a separate server.

The error is:

Unhandled Exception: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 25 - Connection string is not valid)

I have deployed the same image with the same command line on another Ubuntu 14.04 server, and it connects fine.

A console app running on the problem server (outside of Docker) can connect with the same connection string.

As far as I can see from the documentation, an app running in a container has access to the external network by default, so what could be blocking this connection?

答:
an app running in a container has access to the external network by default

It could have access only if a valid IP address is assigned to the container. Sometimes the IP which Docker choose for the container can conflict with external networks.

By default, containers run in bridge network, so look at it:

```<code>docker network inspect bridge
</code>```

Find the container and check its IP.

To resolve conflicts, it is possible to customize bridge network and set bip parameter to change the network's IP range (config file location depends on host's OS):

```<code>"bip": "192.168.1.5/24"
</code>```

Or create a new docker network.

Or experiment with net=host option: docker run network settings

Body:
an app running in a container has access to the external network by default

It could have access only if a valid IP address is assigned to the container. Sometimes the IP which Docker choose for the container can conflict with external networks.

By default, containers run in bridge network, so look at it:

docker network inspect bridge

Find the container and check its IP.

To resolve conflicts, it is possible to customize bridge network and set bip parameter to change the network's IP range (config file location depends on host's OS):

"bip": "192.168.1.5/24"

Or create a new docker network.

Or experiment with net=host option: docker run network settings


问:
Add docker host into docker network
Step1: create a docker network

```<code>docker network create my-work-network
</code>```

Step2: add some container into this network

```<code>docker run ... --name my-work-pg --network my-work-network image1
docker run ... --name my-work-redis --network my-work-network image2
</code>```

My question is:

Current, in my-work-pg, I could ping my-work-redis, and vice versa.
But, in my docker host, I have to parse two container IP address and
access those container, is there exist a solution to make my docker host can JOIN IN this virtual network?

purpose

Just for development conveniency, I want to access all started container
in this network directly as if docker host is a container. e.g. I can access postgresql database with following config

```<code>host: my-work-pg     # pg container host name
port: 5432
</code>```

But, this not exactly what I want.

答:
For your purpose the best way is used link option --link and pass docker_image:name_to_binding, for example to link redis with pg with your configuration it something like that

```<code>docker run ... --name my-work-redis --link my-work-pg image2
</code>```

In these case the same name of container of pg it used as internal name in redis container, and not need something like my-work-pg:name-pg-internal-redis

Title: Add docker host into docker network

Body:
Step1: create a docker network

docker network create my-work-network

Step2: add some container into this network

docker run ... --name my-work-pg --network my-work-network image1
docker run ... --name my-work-redis --network my-work-network image2

My question is:

Current, in my-work-pg, I could ping my-work-redis, and vice versa.
But, in my docker host, I have to parse two container IP address and
access those container, is there exist a solution to make my docker host can JOIN IN this virtual network?

purpose

Just for development conveniency, I want to access all started container
in this network directly as if docker host is a container. e.g. I can access postgresql database with following config

host: my-work-pg     # pg container host name
port: 5432

But, this not exactly what I want.

Body:
For your purpose the best way is used link option --link and pass docker_image:name_to_binding, for example to link redis with pg with your configuration it something like that

docker run ... --name my-work-redis --link my-work-pg image2

In these case the same name of container of pg it used as internal name in redis container, and not need something like my-work-pg:name-pg-internal-redis


问:
Alias nested struct columns
How can I alias field1 as index & & field 2 as value

The query gives me an error:

```<code>#standardsql
with q1 as (select 1 x, ARRAY<struct<id string, cd ARRAY<STRUCT<index STRING,value STRING>>>>
                    [struct('h1',[('1','a')
                                 ,('2','b')
                                 ])
                          ,('h2',[('3','c')
                                 ,('4','d')
                                 ])] hits
       )

Select * from q1
ORDER by x

Error: Array element type STRUCT<STRING, ARRAY<STRUCT<STRING, STRING>>> does not coerce to STRUCT<id STRING, cd ARRAY<STRUCT<index STRING, value STRING>>> at [5:26]
</code>```

Thanks a lot for your time in responding

Cheers!

答:
<pre class="lang-sql prettyprint-override"><code>#standardsql
WITH q1 AS (
  SELECT
    1 AS x,
      [
        STRUCT('h1' AS id, [STRUCT('1' AS index, 'a' AS value), ('2','b')] AS cd),
        STRUCT('h2', [STRUCT('3' AS index, 'c' AS value), ('4','d')] AS cd)
      ] AS hits
)
SELECT *
FROM q1
-- ORDER BY x
</code>```

<p>or below might be even more "readable"   </p>

<pre class="lang-sql prettyprint-override"><code>#standardsql
WITH q1 AS (
  SELECT
    1 AS x,
      [
        STRUCT('h1' AS id, [STRUCT<index STRING, value STRING>('1', 'a'), ('2','b')] AS cd),
        STRUCT('h2', [STRUCT<index STRING, value STRING>('3', 'c'), ('4','d')] AS cd)
      ] AS hits
)
SELECT *
FROM q1
-- ORDER BY x
</code>```

Title: Alias nested struct columns

Body:
How can I alias field1 as index & & field 2 as value

The query gives me an error:

#standardsql
with q1 as (select 1 x, ARRAY<struct<id string, cd ARRAY<STRUCT<index STRING,value STRING>>>>
                    [struct('h1',[('1','a')
                                 ,('2','b')
                                 ])
                          ,('h2',[('3','c')
                                 ,('4','d')
                                 ])] hits
       )

Select * from q1
ORDER by x

Error: Array element type STRUCT<STRING, ARRAY<STRUCT<STRING, STRING>>> does not coerce to STRUCT<id STRING, cd ARRAY<STRUCT<index STRING, value STRING>>> at [5:26]

Thanks a lot for your time in responding

Cheers!

Body:
#standardsql
WITH q1 AS (
  SELECT
    1 AS x,
      [
        STRUCT('h1' AS id, [STRUCT('1' AS index, 'a' AS value), ('2','b')] AS cd),
        STRUCT('h2', [STRUCT('3' AS index, 'c' AS value), ('4','d')] AS cd)
      ] AS hits
)
SELECT *
FROM q1
-- ORDER BY x

or below might be even more "readable"

#standardsql
WITH q1 AS (
  SELECT
    1 AS x,
      [
        STRUCT('h1' AS id, [STRUCT<index STRING, value STRING>('1', 'a'), ('2','b')] AS cd),
        STRUCT('h2', [STRUCT<index STRING, value STRING>('3', 'c'), ('4','d')] AS cd)
      ] AS hits
)
SELECT *
FROM q1
-- ORDER BY x


问:
Filtering Dataframe Using Headers From Other Dataframes in Python
I am trying to filter a dataframe based on the columns I have previously obtained from filtering the dataframe below.

```<code>AA BB CC DD EE FF GG
0  1  1  0  1  0  0
</code>```

The dataframe is coming from a file where the data in each row is either a 0 or a 1 and will change based on the file that is loaded in. I have used the following code to filter this dataframe so that my output consists of only columns with a value of 1 in them.

```<code>with open('Factors.txt') as b:
    IncludedFactors = pd.read_table(b, sep=',' )
print IncludedFactors

InterestingFactors = IncludedFactors.drop(IncludedFactors.columns[~IncludedFactors.iloc[0].astype(bool)],axis=1)
print InterestingFactors

output:
BB CC EE
1  1  1
</code>```

I then need to filter out a bigger dataframe that has many headers, however I only need the ID, Xposition, Yposition and the headers of the InterestingFactors dataframe.

Below is the code I have tried, however the output still only consists of 3 headers instead of the 6 I need.

```<code>headers = InterestingFactors.columns.values
print headers
PivotTable = InfoTable.filter(items=['ID', 'Postion_X','Position_Y','headers'])
print PivotTable
</code>```

Any help on how to do this correctly is greatly appreciated!

答:
Here's one way you can do this:

```<code>headers = InterestingFactors.columns.append(pd.Index(['ID','Postion_X','Position_Y']))
PivotTable = InfoTable.loc[:, headers]
</code>```

This combines the columns you're looking for from InterestingFactors with the 3 columns you mention above. This Index is passed to .loc[].

This also works:

```<code>headers = InterestingFactors.columns
PivotTable = InfoTable.loc[:, (pd.Index(['ID','Postion_X','Position_Y']) | headers)]
</code>```

The datatypes for comparison (I believe) must be the same. Converting your list of 3 standard columns to pd.Index will allow you to use | within .loc[].

Body:
I am trying to filter a dataframe based on the columns I have previously obtained from filtering the dataframe below.

AA BB CC DD EE FF GG
0  1  1  0  1  0  0

The dataframe is coming from a file where the data in each row is either a 0 or a 1 and will change based on the file that is loaded in. I have used the following code to filter this dataframe so that my output consists of only columns with a value of 1 in them.

with open('Factors.txt') as b:
    IncludedFactors = pd.read_table(b, sep=',' )
print IncludedFactors

InterestingFactors = IncludedFactors.drop(IncludedFactors.columns[~IncludedFactors.iloc[0].astype(bool)],axis=1)
print InterestingFactors

output:
BB CC EE
1  1  1

I then need to filter out a bigger dataframe that has many headers, however I only need the ID, Xposition, Yposition and the headers of the InterestingFactors dataframe.

Below is the code I have tried, however the output still only consists of 3 headers instead of the 6 I need.

headers = InterestingFactors.columns.values
print headers
PivotTable = InfoTable.filter(items=['ID', 'Postion_X','Position_Y','headers'])
print PivotTable

Any help on how to do this correctly is greatly appreciated!

Body:
Here's one way you can do this:

headers = InterestingFactors.columns.append(pd.Index(['ID','Postion_X','Position_Y']))
PivotTable = InfoTable.loc[:, headers]

This combines the columns you're looking for from InterestingFactors with the 3 columns you mention above. This Index is passed to .loc[].

This also works:

headers = InterestingFactors.columns
PivotTable = InfoTable.loc[:, (pd.Index(['ID','Postion_X','Position_Y']) | headers)]

The datatypes for comparison (I believe) must be the same. Converting your list of 3 standard columns to pd.Index will allow you to use | within .loc[].


问:
How to write MongoDB query to filter selectively
I want to write a query where we have 2 types of employees stored in a database.  I want a list of all the employees sorted by their start date, but if an employee is on ‘contract’ then I want to include only those employees whose end date is still in future.

Example of such a collection would be:

```<code>{
  "_id": 123,
  "startDate": some date
  "endDate": some date
  "type": “FULL_TIME",
},
{
  "_id": 123,
  "startDate": some date
  "endDate": some date
  "type": “CONTRACT",
},
</code>```

答:
You can try below $or find query.

First condition to get all active CONTRACT employees and second part to get all FULL_TIME employees followed by asc sorting on  startDate.

db.collection.find(
  { $or:
    [
      { $and:
        [
          { type: "CONTRACT" },
          { endDate: { $gt: new ISODate() } }
        ]
      },
      { type:"FULL_TIME" }
    ]
  }
).sort( { startDate: 1 } );
```

Body:
I want to write a query where we have 2 types of employees stored in a database.  I want a list of all the employees sorted by their start date, but if an employee is on ‘contract’ then I want to include only those employees whose end date is still in future.

Example of such a collection would be:

{
  "_id": 123,
  "startDate": some date
  "endDate": some date
  "type": “FULL_TIME",
},
{
  "_id": 123,
  "startDate": some date
  "endDate": some date
  "type": “CONTRACT",
},


问:
C# how to enable button from another class
I have a form1, there's a "download" button, and a "next" button. By default, the "next" button is disabled. When I click "download" button, I will call a method from download.cs, different from form1.cs. After downloading, I want the "next" button to be enabled, so in download.cs, after receiving all files, I put

form1.btnNext.Enabled = true;

But it doesn't work. I also put this in form1.cs

public void enableButton(bool enabled)

{
     btnNext.Enabled = enabled;
  }

and in download.cs I put:

private form1 form1;
  ...

form1.enableButton(true);

but it doesn't work either. Could any1 show me where I'm wrong? thanks in advance.

答:
You could do it via a Callback. So in your Download.cs, you have something like this:

```<code>public delegate void EnableNextCallback (bool enable);

public static void Download(EnableNextCallback n) {
   // stuff
   // when you're done
   n(true);
}
</code>```

That way, you can pass your EnableButton method to your download method.

Body:
You could do it via a Callback. So in your Download.cs, you have something like this:

public delegate void EnableNextCallback (bool enable);

public static void Download(EnableNextCallback n) {
   // stuff
   // when you're done
   n(true);
}

That way, you can pass your EnableButton method to your download method.


问:
When I run this code only data of two nodes and the data of new node is shown but data third and fourth node is not shown
In this code only data of first second and new node is shown but I want the data of all the nodes.

```<code>package linkedlispack;

 public class InsertLast {
  Node head;
  static class Node{
    int data;
    Node next;
    Node(int d){
        data=d;
        next=null;

    }
   }
    public void printlist()
    {
    Node n = head;
    while(n!=null){
        System.out.println(n.data+"");
        n=n.next;
    }
      }
     public void push(int new_data){
      Node new_node=new Node(new_data);
       if(head==null){
        head=new Node(new_data);
        return;
       }

    new_node.next=null;

    Node last=head;
    while(last!=null){
        last=last.next;

        last.next=new_node;
        return;
    }
</code>```

upto last node is created

```<code>     }
     public static void main(String[] args) {
    // TODO Auto-generated method stub
       InsertLast list=new InsertLast();
       list.head=new Node(4);
       Node second=new Node(10);
</code>```

here third and fourth node

```<code>       Node third=new Node(12);
       Node fourth=new Node(20);

        list.head.next=second;

        second.next=third;
        third.next=fourth;

        list.push(15);
        list.printlist();

}

 }
</code>```

output shown 4 10 15 .But I want output 4 10 12 20 15

答:
Your problem is in that you are assigning the next element to Nodes created outside the list. You have to push the elements. If you create them outside instead of pushing them you have to point them using the object list. You did it here:
list.head.next=second;

If you want to keep linking elements to the list use the push method or you have to do it manually by using a lot of next's like this:list.head.next.next.next=new Node(element) but as previously said the push method is the recommendation here.

Body:
In this code only data of first second and new node is shown but I want the data of all the nodes.

package linkedlispack;

 public class InsertLast {
  Node head;
  static class Node{
    int data;
    Node next;
    Node(int d){
        data=d;
        next=null;

    }
   }
    public void printlist()
    {
    Node n = head;
    while(n!=null){
        System.out.println(n.data+"");
        n=n.next;
    }
      }
     public void push(int new_data){
      Node new_node=new Node(new_data);
       if(head==null){
        head=new Node(new_data);
        return;
       }

    new_node.next=null;

    Node last=head;
    while(last!=null){
        last=last.next;

        last.next=new_node;
        return;
    }

upto last node is created

     }
     public static void main(String[] args) {
    // TODO Auto-generated method stub
       InsertLast list=new InsertLast();
       list.head=new Node(4);
       Node second=new Node(10);

here third and fourth node

       Node third=new Node(12);
       Node fourth=new Node(20);

        list.head.next=second;

        second.next=third;
        third.next=fourth;

        list.push(15);
        list.printlist();

}

 }

output shown 4 10 15 .But I want output 4 10 12 20 15


问:
Undefined trying to parse through this xml file
so I am definately a beginner when it comes to javascript and jquery, and I am currently trying to parse through this xml (which is a response from an API call).  The problem I am having is I am not sure how to parse through the xml file in order to get some values.

```<code><group_user>
<id type="integer">2671029</id>
<created_at type="datetime">2013-01-20T21:42:01+00:00</created_at>
<comments_count type="integer">0</comments_count>
<moderator_at type="datetime" nil="true"/>
<user>
<id type="integer">5586131</id>
<first_name>Melora</first_name>
</user>
</group_user>
<group_user>
<id type="integer">2026289</id>
<created_at type="datetime">2012-06-08T04:22:38+00:00</created_at>
<comments_count type="integer">38</comments_count>
<moderator_at type="datetime" nil="true"/>
<user>
<id type="integer">6082517</id>
<first_name>Cindy</first_name>
</user>
</code>```

for all the users (not group_users) I want to store/ consolelog all of the id's and all of the first names.

Right now I am doing:

```<code>   var name = $(xml).find("first_name").text();
   console.log(name);

  var id = $(xml).find("id").text();
  console.log(id);
</code>```

but that just gives me a giant list of all id's and names concatenated together. I want to be able to see them as separate elements.

答:
```<code>var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4 && xhr.status == 200) {
    var parser = new DOMParser();
    var xmlDoc = parser.parseFromString(xhr.responseText, 'text/xml');
    var name = xmlDoc.getElementsByTagName('first_name')[0].childNodes[0].nodeValue;
    var id = xmlDoc.getElementsByTagName('id')[0].childNodes[0].nodeValue;

    console.log(id, name);
  }
};
xhr.open('GET', 'sample.xml', true);
xhr.send(null);
</code>```

// raw xml data
// ================================

var data = `
<data>
  <group_user>
    <id type="integer">2671029</id>
    <created_at type="datetime">2013-01-20T21:42:01+00:00</created_at>
    <comments_count type="integer">0</comments_count>
    <moderator_at type="datetime" nil="true"/>
    <user>
      <id type="integer">5586131</id>
      <first_name>Melora</first_name>
    </user>
  </group_user>
  <group_user>
    <id type="integer">2026289</id>
    <created_at type="datetime">2012-06-08T04:22:38+00:00</created_at>
    <comments_count type="integer">38</comments_count>
    <moderator_at type="datetime" nil="true"/>
    <user>
      <id type="integer">6082517</id>
      <first_name>Cindy</first_name>
    </user>
  </group_user>
</data>
`;

var parser = new DOMParser();

// parse xml
var xmlDoc = parser.parseFromString(data, 'text/xml');

// all <user> tags
var userTags = xmlDoc.querySelectorAll('user');

// variable to store user objects
var users = []

// each <user>
userTags.forEach(function(tag) {
  // use object creation
  var user = {
    // find first <id> tag within <user>
    id: tag.querySelector('id').textContent,
    // find first <first_name> tag within <user>
    name: tag.querySelector('first_name').textContent
  };
  users.push(user);
});

// console.log('users:', users);

// each user object in users array
users.forEach(function(user) {
  console.log(user.id, user.name);
});```

Body:
so I am definately a beginner when it comes to javascript and jquery, and I am currently trying to parse through this xml (which is a response from an API call).  The problem I am having is I am not sure how to parse through the xml file in order to get some values.

<group_user>
<id type="integer">2671029</id>
<created_at type="datetime">2013-01-20T21:42:01+00:00</created_at>
<comments_count type="integer">0</comments_count>
<moderator_at type="datetime" nil="true"/>
<user>
<id type="integer">5586131</id>
<first_name>Melora</first_name>
</user>
</group_user>
<group_user>
<id type="integer">2026289</id>
<created_at type="datetime">2012-06-08T04:22:38+00:00</created_at>
<comments_count type="integer">38</comments_count>
<moderator_at type="datetime" nil="true"/>
<user>
<id type="integer">6082517</id>
<first_name>Cindy</first_name>
</user>

for all the users (not group_users) I want to store/ consolelog all of the id's and all of the first names.

Right now I am doing:

   var name = $(xml).find("first_name").text();
   console.log(name);

  var id = $(xml).find("id").text();
  console.log(id);

but that just gives me a giant list of all id's and names concatenated together. I want to be able to see them as separate elements.

Body:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4 && xhr.status == 200) {
    var parser = new DOMParser();
    var xmlDoc = parser.parseFromString(xhr.responseText, 'text/xml');
    var name = xmlDoc.getElementsByTagName('first_name')[0].childNodes[0].nodeValue;
    var id = xmlDoc.getElementsByTagName('id')[0].childNodes[0].nodeValue;

    console.log(id, name);
  }
};
xhr.open('GET', 'sample.xml', true);
xhr.send(null);

// raw xml data
// ================================

var data = `
<data>
  <group_user>
    <id type="integer">2671029</id>
    <created_at type="datetime">2013-01-20T21:42:01+00:00</created_at>
    <comments_count type="integer">0</comments_count>
    <moderator_at type="datetime" nil="true"/>
    <user>
      <id type="integer">5586131</id>
      <first_name>Melora</first_name>
    </user>
  </group_user>
  <group_user>
    <id type="integer">2026289</id>
    <created_at type="datetime">2012-06-08T04:22:38+00:00</created_at>
    <comments_count type="integer">38</comments_count>
    <moderator_at type="datetime" nil="true"/>
    <user>
      <id type="integer">6082517</id>
      <first_name>Cindy</first_name>
    </user>
  </group_user>
</data>
`;

var parser = new DOMParser();

// parse xml
var xmlDoc = parser.parseFromString(data, 'text/xml');

// all <user> tags
var userTags = xmlDoc.querySelectorAll('user');

// variable to store user objects
var users = []

// each <user>
userTags.forEach(function(tag) {
  // use object creation
  var user = {
    // find first <id> tag within <user>
    id: tag.querySelector('id').textContent,
    // find first <first_name> tag within <user>
    name: tag.querySelector('first_name').textContent
  };
  users.push(user);
});

// console.log('users:', users);

// each user object in users array
users.forEach(function(user) {
  console.log(user.id, user.name);
});


问:
"no such column" after adding a field to the model
environment
DJANGO VERSION 1.9
Python 2.7.6

I added a field (scores) to a model class in models.py like this

```<code>from django.db import models
from django.contrib.auth.models import User
import urllib
import hashlib

class profile(models.Model):
    user = models.OneToOneField(User)
    nickname = models.CharField(max_length=12, blank=True, null=True)
    use_gravatar = models.BooleanField(default=True)
    location = models.CharField(max_length=20, blank=True, null=True)
    avatar_url = models.URLField(blank=True, null=True)
    website = models.URLField(blank=True, null=True)
    **scores = models.IntegerField(default = 0)**
</code>```

and I run the following commands to sync the database.

```<code>python manage.py makemigrations
python manage.py migrate
</code>```

But got this

```<code>OperationalError at /
no such column: account_profile.scores
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 1.8.4
Exception Type: OperationalError
Exception Value:
no such column: account_profile.scores
Exception Location: C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 318
Python Executable:  C:\Python27\python.exe
Python Version: 2.7.5
Python Path:
['c:\\FairyBBS',
 'C:\\Users\\user\\AppData\\Roaming\\Python\\Python27\\site-packages\\setuptools-5.4.1-py2.7.egg',
 'C:\\Users\\user\\AppData\\Roaming\\Python\\Python27\\site-packages\\urlobject-2.4.0-py2.7.egg',
 'C:\\Users\\user\\AppData\\Roaming\\Python\\Python27\\site-packages\\djangorestframework-0.4.0-py2.7.egg',
 'C:\\WINDOWS\\SYSTEM32\\python27.zip',
 'C:\\Python27\\DLLs',
 'C:\\Python27\\lib',
 'C:\\Python27\\lib\\plat-win',
 'C:\\Python27\\lib\\lib-tk',
 'C:\\Python27',
 'C:\\Users\\user\\AppData\\Roaming\\Python\\Python27\\site-packages',
 'C:\\Python27\\lib\\site-packages']
Server time:    星期四, 17 三月 2016 14:08:04 +0800
</code>```

答:
Keeping it short and precise, give that field a default value.

For example:

```<code>nickname = models.CharField(max_length=12, default=" ")
</code>```

and not default=True

If that doesn't work delete the migrations in your app's migration folder except

```<code>__init__.py file and type both the commands again.
python manage.py migrate
python manage.py makemigrations appname
python manage.py migrate(again)
</code>```

Body:
environment
DJANGO VERSION 1.9
Python 2.7.6

I added a field (scores) to a model class in models.py like this

from django.db import models
from django.contrib.auth.models import User
import urllib
import hashlib

class profile(models.Model):
    user = models.OneToOneField(User)
    nickname = models.CharField(max_length=12, blank=True, null=True)
    use_gravatar = models.BooleanField(default=True)
    location = models.CharField(max_length=20, blank=True, null=True)
    avatar_url = models.URLField(blank=True, null=True)
    website = models.URLField(blank=True, null=True)
    **scores = models.IntegerField(default = 0)**

and I run the following commands to sync the database.

python manage.py makemigrations
python manage.py migrate

But got this

OperationalError at /
no such column: account_profile.scores
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 1.8.4
Exception Type: OperationalError
Exception Value:
no such column: account_profile.scores
Exception Location: C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 318
Python Executable:  C:\Python27\python.exe
Python Version: 2.7.5
Python Path:
['c:\\FairyBBS',
 'C:\\Users\\user\\AppData\\Roaming\\Python\\Python27\\site-packages\\setuptools-5.4.1-py2.7.egg',
 'C:\\Users\\user\\AppData\\Roaming\\Python\\Python27\\site-packages\\urlobject-2.4.0-py2.7.egg',
 'C:\\Users\\user\\AppData\\Roaming\\Python\\Python27\\site-packages\\djangorestframework-0.4.0-py2.7.egg',
 'C:\\WINDOWS\\SYSTEM32\\python27.zip',
 'C:\\Python27\\DLLs',
 'C:\\Python27\\lib',
 'C:\\Python27\\lib\\plat-win',
 'C:\\Python27\\lib\\lib-tk',
 'C:\\Python27',
 'C:\\Users\\user\\AppData\\Roaming\\Python\\Python27\\site-packages',
 'C:\\Python27\\lib\\site-packages']
Server time:    星期四, 17 三月 2016 14:08:04 +0800

Body:
Keeping it short and precise, give that field a default value.

For example:

nickname = models.CharField(max_length=12, default=" ")

and not default=True

If that doesn't work delete the migrations in your app's migration folder except

__init__.py file and type both the commands again.
python manage.py migrate
python manage.py makemigrations appname
python manage.py migrate(again)


问:
Are <form/> name clash risks real with Liferay?
I followed the liferay helloword tutorial:
https://dev.liferay.com/develop/tutorials/-/knowledge_base/6-2/writing-your-first-liferay-application#creating-a-form

It says forms in a liferay application form should always have contain the portlet basename as the name, not to clash with the form name of another portlet.

```<code><aui:form action="<%= addEntryURL %>" name="<portlet:namespace />fm">
</aui:form>
</code>```

Why is this precaution not necessary with buttons from unnamed button rows?

```<code><aui:button-row cssClass="guestbook-buttons">
    <portlet:renderURL var="addEntryURL">
        <portlet:param name="mvcPath" value="/html/guestbook/edit_entry.jsp"></portlet:param>
    </portlet:renderURL>
    <aui:button onClick="<%= addEntryURL.toString() %>" value="Add Entry">
    </aui:button>
</aui:button-row>
</code>```

I mean, any portlet could have a page nammed "/html/guestbook/edit_entry.jsp", right?

Plus, I tried to remove this precaution for the form and duplicate my portlet, and did not have any name clash problem. So how is it useful?

Using Liferay 6.2.

答:
About Namespacing

Your portlet's namespace is automatically prefixed to the name of AUI tags in my 6.2 portal.  These two are equivalent in name

```<code><form name="<portlet:namespace />fm"</form>
<aui:form name="fm"></aui:form>
</code>```

As a side not they also both with have an id attribute that is just a copy of the name attribute.  If you look at the Liferay source code you will see that almost all the forms are given the name "fm".  This convention is used for convenient and conflicts do not occur because of the namespace prefix.

Your example

I think your example is a bit off though.  In the case of the unnamed button row, it will always go to the current portlets edit_entry.jsp because of your path specification unless otherwise specified.  However even if you have the same portlet instantiated twice on the same page that really wouldn't make a different.  I don't see to much of an issue with unnamed button rows.

Conflicts can occur

What would make a difference is if you had the same portlet instantiated twice on the same page. Let's assume for an instance that you have a "pitch" portlet and a "catch" portlet.  Both of them have a class "Portlet" that extends MVCPortlet.  Both of them have fm forms with no namespace.  When posted the form goes triggers an action url which goes to the portlet and subtracts a point.  In this case there could possibly be a conflict and a point subtracted from the wrong portlet.

Testing it out

To witness a conflict for yourself you can stage the following example.

Create two Liferay Plugin Portlets with different names.

In both portlets create a Portlet.java file that extends MVCPortlet (see below).  Make sure the fully qualified class name is simply Portlet (IE: don't create any packages)

In your view.jsp file create a form and an action url (see below).

In your Liferay-portlet.xml file add the code below.

Portlet.java

```<code>public class DashboardRequestPortlet extends MVCPortlet {
    public void testAction(ActionRequest actionRequest, ActionRequest actionResponse) {
    System.out.println("test");
    }
}
</code>```

View.jsp

```<code><portlet:actionURL name="testAction" var="testActionURL" />
<form id="fm" name="fm" action="<%= testActionURL.toString() %>" method="post"></form>
</code>```

liferay-portlet.xml

```<code><requires-namespaced-parameters>false</requires-namespaced-parameters>
</code>```

Put breakpoints in the testAction method on both portlets.  Drag both portlets onto the same page.  Start submitting...

Body:
I followed the liferay helloword tutorial:
https://dev.liferay.com/develop/tutorials/-/knowledge_base/6-2/writing-your-first-liferay-application#creating-a-form

It says forms in a liferay application form should always have contain the portlet basename as the name, not to clash with the form name of another portlet.

<aui:form action="<%= addEntryURL %>" name="<portlet:namespace />fm">
</aui:form>

Why is this precaution not necessary with buttons from unnamed button rows?

<aui:button-row cssClass="guestbook-buttons">
    <portlet:renderURL var="addEntryURL">
        <portlet:param name="mvcPath" value="/html/guestbook/edit_entry.jsp"></portlet:param>
    </portlet:renderURL>
    <aui:button onClick="<%= addEntryURL.toString() %>" value="Add Entry">
    </aui:button>
</aui:button-row>

I mean, any portlet could have a page nammed "/html/guestbook/edit_entry.jsp", right?

Plus, I tried to remove this precaution for the form and duplicate my portlet, and did not have any name clash problem. So how is it useful?

Using Liferay 6.2.

Body:
About Namespacing

Your portlet's namespace is automatically prefixed to the name of AUI tags in my 6.2 portal.  These two are equivalent in name

<form name="<portlet:namespace />fm"</form>
<aui:form name="fm"></aui:form>

As a side not they also both with have an id attribute that is just a copy of the name attribute.  If you look at the Liferay source code you will see that almost all the forms are given the name "fm".  This convention is used for convenient and conflicts do not occur because of the namespace prefix.

Your example

I think your example is a bit off though.  In the case of the unnamed button row, it will always go to the current portlets edit_entry.jsp because of your path specification unless otherwise specified.  However even if you have the same portlet instantiated twice on the same page that really wouldn't make a different.  I don't see to much of an issue with unnamed button rows.

Conflicts can occur

What would make a difference is if you had the same portlet instantiated twice on the same page. Let's assume for an instance that you have a "pitch" portlet and a "catch" portlet.  Both of them have a class "Portlet" that extends MVCPortlet.  Both of them have fm forms with no namespace.  When posted the form goes triggers an action url which goes to the portlet and subtracts a point.  In this case there could possibly be a conflict and a point subtracted from the wrong portlet.

Testing it out

To witness a conflict for yourself you can stage the following example.

Create two Liferay Plugin Portlets with different names.

In both portlets create a Portlet.java file that extends MVCPortlet (see below).  Make sure the fully qualified class name is simply Portlet (IE: don't create any packages)

In your view.jsp file create a form and an action url (see below).

In your Liferay-portlet.xml file add the code below.

Portlet.java

public class DashboardRequestPortlet extends MVCPortlet {
    public void testAction(ActionRequest actionRequest, ActionRequest actionResponse) {
    System.out.println("test");
    }
}

View.jsp

<portlet:actionURL name="testAction" var="testActionURL" />
<form id="fm" name="fm" action="<%= testActionURL.toString() %>" method="post"></form>

liferay-portlet.xml

<requires-namespaced-parameters>false</requires-namespaced-parameters>

Put breakpoints in the testAction method on both portlets.  Drag both portlets onto the same page.  Start submitting...


问:
Webalizer not picking up on server-side redirects
I'm using Webalizer on an intranet, and I want statistics for clicks on outbound links. I set up the links to point to a simple ASP redirection page -
each link resembles "redirect.asp?url=http://outsidesite.com". But Webalizer is not tracking the redirections. Is there a setting in the Webalizer config file that needs to be changed? Or do I need to set up the redirection differently?</p>

答: I found a solution - I used a META refresh in my ASP page instead of a server-side redirect. The server-side code puts the query string's URL in the refresh's CONTENT value.</p>


问:
Does dereferencing a pointer make a copy of it?
Does dereferencing a pointer and passing that to a function which takes its argument by reference create a copy of the object?</p>

答:
In the simple case, no. There are more complicated cases, though:

```<code>void foo(float const& arg);
int * p = new int(7);
foo(*p);
</code>```

Here, a temporary object is created, because the type of the dereferenced pointer (int) does not match the base type of the function parameter (float). A conversion sequence exists, and the converted temporary can be bound to arg since that's a const reference.

Body:
In the simple case, no. There are more complicated cases, though:

void foo(float const& arg);
int * p = new int(7);
foo(*p);

Here, a temporary object is created, because the type of the dereferenced pointer (int) does not match the base type of the function parameter (float). A conversion sequence exists, and the converted temporary can be bound to arg since that's a const reference.


问:
Keep dynamic form field values after form submission
Using form with select dropdown. When user selects option, it gets posted to ajax.php via Ajax. The file then returns dynamic input fields. The form.php looks like this before option is selected:

```<code><form action="form.php" method="post" id="myform">
    <select name="raw_ids_array[]" class="select2" multiple="multiple" id="raw_ids_array"><option></option><option value="1">first</option><option value="2">second</option></select>
    <div id="raws_list_hidden"></div>
<input type="submit" id="submit_me" name="submit_me" value="go">
</form>
</code>```

The form.php looks like this after option is selected:

```<code><form action="form.php" method="post" id="myform">
    <select name="raw_ids_array[]" class="select2" multiple="multiple" id="raw_ids_array"><option></option><option value="1">first</option><option value="2">second</option></select>
    <div id="raws_list_hidden"><input type="text" name="dynamic_field"></div>
<input type="submit" id="submit_me" name="submit_me" value="go">
</form>
</code>```

I use this code to do Ajax posting:

```<code><script>
  $(function () {
  function ajax_post_data(parameters) {
    $.ajax({
      method: "POST",
      url: "ajax.php",
      cache: false,
      data: parameters,
      success: function(data) {
        $("#raws_list_hidden").html(data);
      }
    });
  }

  $('#raw_ids_array').on("change", function(e) {
  parameters=$("#myform").serialize();
  ajax_post_data(parameters);
  });
});
</script>
</code>```

However, if form submission fails, I need all the previously selected options/entered values to be displayed again. So added this:

```<code>$(document).ready(function() {
  parameters=$("#myform").serialize();
  ajax_post_data(parameters);
  });
</code>```

When form.php is submitted (gets "reloaded"), it posts selected options from raw_ids_array[] to ajax.php, which then adds dynamic fields into raws_list_hidden div again. The only thing which doesn't work - user's entered value from dynamic_field is NOT serialized; therefore, it becomes empty.

How should I modify the code, so values from dynamic fields also get posted to ajax.php?

P.S. I can serialize all fields if I use code:

```<code>$('#submit_me').click(function() {
    parameters=$("#myform").serialize();
  ajax_post_data(parameters);
});
</code>```

but it's not useful because data is serialized before posting form.php, so I don't know if form will fail (in case some invalid values were submitted) or not.

答:
If understood you correctly, you're posting your form twice without noticing it.

To get it working, you'll first need to replace the input type submit in your form for another type of element, like the code example below, where I used button instead:

EDIT: added proper function call for the form and ajax posts.

```<code><form id="myform">
    <select name="raw_ids_array[]" class="select2" multiple="multiple" id="raw_ids_array">
        <option></option>
        <option value="1">first</option>
        <option value="2">second</option>
    </select>
    <div id="raws_list_hidden"></div>

    <button id="submit_me" name="submit_me">go</button>

</form>
</code>```

This will prevent your form to be submitted automatically When the button is pressed: we'll restrict the button's actions to what we write in our JS.

As you can see, there are no method or action properties for the form element either.

The idea of using ajax is exactly to NOT have to reload a page when something is submitted. Ajax will post the data and handle the results behind the curtins, so the user won't ever be redirected to another page nor anything will be automatically reloaded.

I believe if you keep your JS as:

```<code>function post_data(params, dest) {
    $.ajax({
        method: 'POST',
        url: dest+'.php',
        cache: false,
        data: params,
        success: function(data) {
            $('#raws_list_hidden').html(data);
        },
        error: function(data) {
            console.log('something went wrong - ', data);
        }
    });
}

$('#raw_ids_array').on("change", function(e) {
    parameters = $("#myform").serialize();
    post_data(parameters, 'ajax');
});

$('#submit_me').click(function() {
    parameters=$("#myform").serialize();
    post_data(parameters, 'form');
});
</code>```

It will work.

On the "success" property of the ajax request declaration we'll deal with positive responses (http codes 200 to 299). To deal with errors (http codes 400 to 599), you can declare a function on the "error" property, like the example above.

For more info on JQuery Ajax: https://www.w3schools.com/jquery/ajax_ajax.asp
For more information on http status codes: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

I hope this helped! :)

EDIT: Added proper function call for the form and ajax posts. If you want to deal with the post responses separately, you can either create two distinct functions to make the calls, or edit the code so you could send a callback functions:

```<code>function postData(params, dest, successCallback, errorCallback) {
    $.ajax({
        method: 'POST',
        url: dest+'.php',
        cache: false,
        data: params,
        success: successCallback,
        error: errorCallback
    });
}

$('#raw_ids_array').on('change', function(e) {
    postData($('#myform').serialize(), 'ajax', ajaxSuccess, ajaxError);

    function ajaxSuccess(response) {
         $('#raws_list_hidden').html(response);
    }

    function ajaxError(response) {
         console.log('something went wrong with ajax post - ', response);
    }
});

$('#submit_me').on('click', function() {
    postData($('#myform').serialize(), 'form', formSuccess, formError);

    function formSuccess(response) {
         console.log('form submit worked successfully - ', response);
    }

    function formError(response) {
         console.log('something went wrong with form post - ', response);
    }
});
</code>```

Body:
Using form with select dropdown. When user selects option, it gets posted to ajax.php via Ajax. The file then returns dynamic input fields. The form.php looks like this before option is selected:

<form action="form.php" method="post" id="myform">
    <select name="raw_ids_array[]" class="select2" multiple="multiple" id="raw_ids_array"><option></option><option value="1">first</option><option value="2">second</option></select>

<input type="submit" id="submit_me" name="submit_me" value="go">
</form>

The form.php looks like this after option is selected:

<form action="form.php" method="post" id="myform">
    <select name="raw_ids_array[]" class="select2" multiple="multiple" id="raw_ids_array"><option></option><option value="1">first</option><option value="2">second</option></select>

<input type="text" name="dynamic_field">

<input type="submit" id="submit_me" name="submit_me" value="go">
</form>

I use this code to do Ajax posting:

However, if form submission fails, I need all the previously selected options/entered values to be displayed again. So added this:

$(document).ready(function() {
  parameters=$("#myform").serialize();
  ajax_post_data(parameters);
  });

When form.php is submitted (gets "reloaded"), it posts selected options from raw_ids_array[] to ajax.php, which then adds dynamic fields into raws_list_hidden div again. The only thing which doesn't work - user's entered value from dynamic_field is NOT serialized; therefore, it becomes empty.

How should I modify the code, so values from dynamic fields also get posted to ajax.php?

P.S. I can serialize all fields if I use code:

$('#submit_me').click(function() {
    parameters=$("#myform").serialize();
  ajax_post_data(parameters);
});

but it's not useful because data is serialized before posting form.php, so I don't know if form will fail (in case some invalid values were submitted) or not.

Body:
If understood you correctly, you're posting your form twice without noticing it.

To get it working, you'll first need to replace the input type submit in your form for another type of element, like the code example below, where I used button instead:

EDIT: added proper function call for the form and ajax posts.

<form id="myform">
    <select name="raw_ids_array[]" class="select2" multiple="multiple" id="raw_ids_array">
        <option></option>
        <option value="1">first</option>
        <option value="2">second</option>
    </select>
    <div id="raws_list_hidden"></div>

    <button id="submit_me" name="submit_me">go</button>

</form>

This will prevent your form to be submitted automatically When the button is pressed: we'll restrict the button's actions to what we write in our JS.

As you can see, there are no method or action properties for the form element either.

The idea of using ajax is exactly to NOT have to reload a page when something is submitted. Ajax will post the data and handle the results behind the curtins, so the user won't ever be redirected to another page nor anything will be automatically reloaded.

I believe if you keep your JS as:

function post_data(params, dest) {
    $.ajax({
        method: 'POST',
        url: dest+'.php',
        cache: false,
        data: params,
        success: function(data) {
            $('#raws_list_hidden').html(data);
        },
        error: function(data) {
            console.log('something went wrong - ', data);
        }
    });
}

$('#raw_ids_array').on("change", function(e) {
    parameters = $("#myform").serialize();
    post_data(parameters, 'ajax');
});

$('#submit_me').click(function() {
    parameters=$("#myform").serialize();
    post_data(parameters, 'form');
});

It will work.

On the "success" property of the ajax request declaration we'll deal with positive responses (http codes 200 to 299). To deal with errors (http codes 400 to 599), you can declare a function on the "error" property, like the example above.

For more info on JQuery Ajax: https://www.w3schools.com/jquery/ajax_ajax.asp
For more information on http status codes: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

I hope this helped! :)

EDIT: Added proper function call for the form and ajax posts. If you want to deal with the post responses separately, you can either create two distinct functions to make the calls, or edit the code so you could send a callback functions:

function postData(params, dest, successCallback, errorCallback) {
    $.ajax({
        method: 'POST',
        url: dest+'.php',
        cache: false,
        data: params,
        success: successCallback,
        error: errorCallback
    });
}

$('#raw_ids_array').on('change', function(e) {
    postData($('#myform').serialize(), 'ajax', ajaxSuccess, ajaxError);

    function ajaxSuccess(response) {
         $('#raws_list_hidden').html(response);
    }

    function ajaxError(response) {
         console.log('something went wrong with ajax post - ', response);
    }
});

$('#submit_me').on('click', function() {
    postData($('#myform').serialize(), 'form', formSuccess, formError);

    function formSuccess(response) {
         console.log('form submit worked successfully - ', response);
    }

    function formError(response) {
         console.log('something went wrong with form post - ', response);
    }
});


问:
Is it possible to connect 300 devices with openthread?
I am looking for a stack allowing to connect several hundred devices,

Openthread has max numbers of hopes equal 16.
Is it possible to extend that number to have 300 devices connected sequentially?
What are requirements to the chip in this case if possible or what limits the max number of connected routing devices?

答: The Thread Protocol Specification currently has a limit of 15 hops between routers (or 17 hops between end devices).  It is not possible to connect hundreds of devices sequentially.  At the same time, the Thread Protocol does connecting hundreds of end devices to each router.  However, in most practical cases, the number of end devices a router supports is determined by its memory resources.</p>


问:
khan academy: javascript loop taking too long to run

I'm reading through the khan academy course on algorithms. I'm at https://www.khanacademy.org/computing/computer-science/algorithms/sorting-algorithms/p/challenge-find-minimum-in-subarray

The code challenge is supposed to loop through the array find and return the lowest number in the subarray. I've written code which I think should work, but I'm getting the error in the title. Why?

```<code>var indexOfMinimum = function(array, startIndex) {
    // Set initial values for minValue and minIndex,
    // based on the leftmost entry in the subarray:
    var minValue = array[startIndex];
    var minIndex = startIndex;
    var i = minIndex + 1;
    for( i ; array.length ; i+1) {
        if( array[i]< minValue) {
            minIndex = i ;
            minValue = array[i];
        }
    }

    // Loop over items starting with startIndex,
    // updating minValue and minIndex as needed:

    return minIndex;
};

var array = [18, 6, 66, 44, 9, 22, 14];
var index = indexOfMinimum(array, 2);
</code>```

答:
The second part of your for loop needs to be something that actually tests for something.  right now it's an infinite loop because its something that's always true

This should fix it:

```<code>for( i ; i < array.length ; i++) {
if( array[i]< minValue) {
    minIndex = i ;
    minValue = array[i];
    }
}
</code>```

Body:
I'm reading through the khan academy course on algorithms. I'm at https://www.khanacademy.org/computing/computer-science/algorithms/sorting-algorithms/p/challenge-find-minimum-in-subarray

The code challenge is supposed to loop through the array find and return the lowest number in the subarray. I've written code which I think should work, but I'm getting the error in the title. Why?

var indexOfMinimum = function(array, startIndex) {
    // Set initial values for minValue and minIndex,
    // based on the leftmost entry in the subarray:
    var minValue = array[startIndex];
    var minIndex = startIndex;
    var i = minIndex + 1;
    for( i ; array.length ; i+1) {
        if( array[i]< minValue) {
            minIndex = i ;
            minValue = array[i];
        }
    }

    // Loop over items starting with startIndex,
    // updating minValue and minIndex as needed:

    return minIndex;
};

var array = [18, 6, 66, 44, 9, 22, 14];
var index = indexOfMinimum(array, 2);

Body:
The second part of your for loop needs to be something that actually tests for something.  right now it's an infinite loop because its something that's always true

This should fix it:

for( i ; i < array.length ; i++) {
if( array[i]< minValue) {
    minIndex = i ;
    minValue = array[i];
    }
}


问:
Does macOS Safari use the same version of WebKit as iOS Safari (assuming the macOS and iOS Safari versions are equal)?
For example, does macOS Safari 10.2 use the same version of WebKit as iOS Safari 10.2?

I know that the WebKit revision number included in a release of Safari isn't publicly available, but if there's a WebKit bug that I know is fixed in macOS Safari 10.2 can I also assume that it's fixed in iOS Safari 10.2?

答:
The answer is no, you cannot assume they are using the same version. Maybe they sometimes match up but thats not a guarantee.

Source: I checked wikipedia for the OS X version of Safari https://en.wikipedia.org/wiki/Safari_version_history agains my iPads/iPhones versions. They don't match up at all.

iOS 10.2.1 - Safari 10.0 - WebKit 602.4.6

iOS 8.1.3 - Safari 8.0 - WebKit 600.1.4

Even if they would, don't you think you should support all sorts of browsers and versions?


问:
Dynamically, continously, set a cell's value according to ActiveCell's value (which is on another worksheet)
I have a workbook with a two sheets, Rep and Aux.

I want to dynamically set Aux!A2 to the value of the ActiveCell, which is on sheet Rep, but only if the ActiveCell is on column D of that sheet (in the range Rep!D2:D5000).

To top it all of I need this mechanism to run as long as the workbook is active, not just a one-shot.

For example: While being on sheet Rep I place the cursor, i.e. ActiveCell on cell D2. I expect Aux!A2 to be set to the value of Rep!D2. I move the cursor to, say, Rep!F5 and expect nothing to happen to Aux!A2, lastly, I activate cell Rep!D7 and again, expect Aux!A2 to get the ActiveCell's value. Continue till I close the workbook.

My VBA skills are non-existent and Googling, the only thing remotely close to what I described was:

```<code>Sub Macro1()
    If Not Intersect(ActiveCell, Sheets("Rep").Range("D2:D5000")) Is Nothing Then Sheets("Aux").Range("A2").Value = ActiveCell.Value
End Sub
</code>```

Which fails completely.

答:
Put this in the code of the "Rep" worksheet.  Triggers anytime a cell is selected on that sheet, if the cell is in column 4 (D) then it sets the value of the cell on Aux to match.

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
    If Target.Column = 4 Then
      ThisWorkbook.Worksheets("Aux").Cells(2, 1).value = Target.Value
    End If
End Sub
</code>```

EDIT:  In response to comments.

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
End Sub
</code>```

This subroutine is an event that exists on every worksheet.  Any time a selection changes it will run any code you put in it.  The "ByVal Target as Excel.Range" part is saying it's giving you a copy of the target range being selected, because you could select more then one cell.

```<code>If Target.Column = 4 Then
end if
</code>```

This is an If Block.  If the condition is true, any code between the "Then" and the "End If" will execute.  The condition is if the target's column is 4 in this case.

```<code>ThisWorkbook.Worksheets("Aux").Cells(2, 1).value = Target.Value
</code>```

This sets the cell at row 2 column 1 value to match the value of the target that was selected.

Now that I think about it I wonder what this code will do if you select a range of cells.....

Body:
I have a workbook with a two sheets, Rep and Aux.

I want to dynamically set Aux!A2 to the value of the ActiveCell, which is on sheet Rep, but only if the ActiveCell is on column D of that sheet (in the range Rep!D2:D5000).

To top it all of I need this mechanism to run as long as the workbook is active, not just a one-shot.

For example: While being on sheet Rep I place the cursor, i.e. ActiveCell on cell D2. I expect Aux!A2 to be set to the value of Rep!D2. I move the cursor to, say, Rep!F5 and expect nothing to happen to Aux!A2, lastly, I activate cell Rep!D7 and again, expect Aux!A2 to get the ActiveCell's value. Continue till I close the workbook.

My VBA skills are non-existent and Googling, the only thing remotely close to what I described was:

Sub Macro1()
    If Not Intersect(ActiveCell, Sheets("Rep").Range("D2:D5000")) Is Nothing Then Sheets("Aux").Range("A2").Value = ActiveCell.Value
End Sub

Which fails completely.

Body:
Put this in the code of the "Rep" worksheet.  Triggers anytime a cell is selected on that sheet, if the cell is in column 4 (D) then it sets the value of the cell on Aux to match.

Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
    If Target.Column = 4 Then
      ThisWorkbook.Worksheets("Aux").Cells(2, 1).value = Target.Value
    End If
End Sub

EDIT:  In response to comments.

Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
End Sub

This subroutine is an event that exists on every worksheet.  Any time a selection changes it will run any code you put in it.  The "ByVal Target as Excel.Range" part is saying it's giving you a copy of the target range being selected, because you could select more then one cell.

If Target.Column = 4 Then
end if

This is an If Block.  If the condition is true, any code between the "Then" and the "End If" will execute.  The condition is if the target's column is 4 in this case.

ThisWorkbook.Worksheets("Aux").Cells(2, 1).value = Target.Value

This sets the cell at row 2 column 1 value to match the value of the target that was selected.

Now that I think about it I wonder what this code will do if you select a range of cells.....