问:
flink apache : What is the most efficient : read file and split text to tuple or read csv
I did this small code to put files from a folder in a data stream:

```<code>public class TextFromDirStream {

//
//  Program
//

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

    // set up the execution environment
    final StreamExecutionEnvironment env = StreamExecutionEnvironment
            .getExecutionEnvironment();

    // monitor directory, checking for new files
    // every 100 milliseconds
    TextInputFormat format = new TextInputFormat(
            new org.apache.flink.core.fs.Path("file:///tmp/dir/"));

    DataStream<String> inputStream = env.readFile(
            format,
            "file:///tmp/dir/",
            FileProcessingMode.PROCESS_CONTINUOUSLY,
            100,
            FilePathFilter.createDefaultFilter());

    inputStream.print();

    // execute program
    env.execute("Java read file from folder Example");
}
</code>```

}

My next step is the deal with the file content (a csv). What is the most effective way to deal with this ? Do I change my code to parse the text file inputStream and transform it as a Tuple or readFile as a CSV from the beginning. I ask the question because I have difficulty to find example or documentation on how to split text to tuple.

Thank you in advance

答:
Starting with your code, each event in your stream (inputStream) is a line as String. You can just map a line into a TupleX :

```<code>DataStream<Tuple2<Long, String>> parsedStream = inputStream
   .map((line) -> {
     String[] cells = line.split(",");
     // Only keep first and third cells
     return new Tuple2(Long.parseLong(cells[2]), cells[0]);
   });
</code>```

You can also use readCsvFile which includes fields selection and which is able to create TupleX or POJO (but there's no PROCESS_CONTINUOUSLY with readCsvFile). Also note that if you use PROCESS_CONTINUOUSLY, each modified file will be processed entirely (again) which does not match with exactly one!

Body:
I did this small code to put files from a folder in a data stream:

public class TextFromDirStream {

//
//  Program
//

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

    // set up the execution environment
    final StreamExecutionEnvironment env = StreamExecutionEnvironment
            .getExecutionEnvironment();

    // monitor directory, checking for new files
    // every 100 milliseconds
    TextInputFormat format = new TextInputFormat(
            new org.apache.flink.core.fs.Path("file:///tmp/dir/"));

    DataStream<String> inputStream = env.readFile(
            format,
            "file:///tmp/dir/",
            FileProcessingMode.PROCESS_CONTINUOUSLY,
            100,
            FilePathFilter.createDefaultFilter());

    inputStream.print();

    // execute program
    env.execute("Java read file from folder Example");
}

}

My next step is the deal with the file content (a csv). What is the most effective way to deal with this ? Do I change my code to parse the text file inputStream and transform it as a Tuple or readFile as a CSV from the beginning. I ask the question because I have difficulty to find example or documentation on how to split text to tuple.

Thank you in advance

Body:
Starting with your code, each event in your stream (inputStream) is a line as String. You can just map a line into a TupleX :

DataStream<Tuple2<Long, String>> parsedStream = inputStream
   .map((line) -> {
     String[] cells = line.split(",");
     // Only keep first and third cells
     return new Tuple2(Long.parseLong(cells[2]), cells[0]);
   });

You can also use readCsvFile which includes fields selection and which is able to create TupleX or POJO (but there's no PROCESS_CONTINUOUSLY with readCsvFile). Also note that if you use PROCESS_CONTINUOUSLY, each modified file will be processed entirely (again) which does not match with exactly one!


来源: stackexchange

问:
Share videos on Twitter via iOS App
Is it possible to share a video using SLRequest ?

I'm able to share Images using the same

```<code>SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:requestURL parameters:message];

if (isImage)
{
    NSData *data = UIImagePNGRepresentation(imgSelected);
    [postRequest addMultipartData:data withName:@"media" type:@"image/png" filename:@"TestImage.png"];
}

postRequest.account = account;

[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
    if (!error)
    {
        NSLog(@"Upload Sucess !");
    }
}];
</code>```

答:
I was able to upload video to twitter successfully!
Below are steps referred from twitter docs:

Request for twitter account

```<code>accountStore.requestAccessToAccounts(with: twitterAccountType,options:nil){(granted, error) in
</code>```

POST media/upload (INIT)

```<code>params["command"] = "INIT"
params["total_bytes"]  = String(videoData.length)
params["media_type"]  = "video/mov"
</code>```

POST media/upload (APPEND)

```<code>params["command"] = "APPEND"
params["media_id"]  = mediaId
params["segment_index"]  = String(chunk)
</code>```

POST media/upload (FINALIZE)

```<code>params["command"] = "FINALIZE"
params["media_id"]  = mediaId
</code>```

POST media/upload

```<code>params["status"] = twitterDescription
params["media_ids"]  = mediaId
</code>```

Here is twitter doc link https://dev.twitter.com/rest/media/uploading-media.html

Please fine the detailed solution for video upload to twitter using SLRequest here.

http://swiftoverflow.blogspot.in/2017/04/upload-video-to-twitter-using-slrequest.html

ContentLicense: CC BY-SA 3.0

Title: Share videos on Twitter via iOS App

Body:
Is it possible to share a video using SLRequest ?

I'm able to share Images using the same

SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:requestURL parameters:message];

if (isImage)
{
    NSData *data = UIImagePNGRepresentation(imgSelected);
    [postRequest addMultipartData:data withName:@"media" type:@"image/png" filename:@"TestImage.png"];
}

postRequest.account = account;

[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
    if (!error)
    {
        NSLog(@"Upload Sucess !");
    }
}];

Body:
I was able to upload video to twitter successfully!
Below are steps referred from twitter docs:

Request for twitter account

accountStore.requestAccessToAccounts(with: twitterAccountType,options:nil){(granted, error) in

POST media/upload (INIT)

params["command"] = "INIT"
params["total_bytes"]  = String(videoData.length)
params["media_type"]  = "video/mov"

POST media/upload (APPEND)

params["command"] = "APPEND"
params["media_id"]  = mediaId
params["segment_index"]  = String(chunk)

POST media/upload (FINALIZE)

params["command"] = "FINALIZE"
params["media_id"]  = mediaId

POST media/upload

params["status"] = twitterDescription
params["media_ids"]  = mediaId

Here is twitter doc link https://dev.twitter.com/rest/media/uploading-media.html

Please fine the detailed solution for video upload to twitter using SLRequest here.

http://swiftoverflow.blogspot.in/2017/04/upload-video-to-twitter-using-slrequest.html


问:
Odoo 10 - Form view opened in edit mode
I'm developing on Odoo 10.

I created a dynamic form view which search and display a product from its barcode, but I've got a problem.

Since the view has no initial record to display it is opened in edit mode, and that's ok, because I want to type the 'barcode' field.

But, after the product is displayed, when I exit from that view the 'can_be_discarded' function is fired, opening the confirm dialog.

Have I to create a new view type inheriting from FormView or is there a way to workaround this problem?

The view is a classic form view, with nothing special.

Here's the server code instead.

class ProductFromBarcode(models.TransientModel):
    _name = 'levelprime_product_general_status.product_from_barcode'
    _inherits = { 'product.product': 'product_id' }

    product_id      = fields.Many2one(
                            comodel_name='product.product',
                            store=False)
    product_barcode = fields.Integer(help='Insert the barcode to search '
                                          'the correspondent product',
                                     store=False)

    @api.onchange('product_barcode')
    def on_barcode_changed(self):
        if self.product_barcode != 0:
            self.product_id = self.get_product_from_barcode(self.product_barcode)

    @api.model
    def get_product_from_barcode(self, barcode):
        r = self.env['product.product'].search([('barcode', '=', barcode)])
        if r:
            return r
```

答:
Ok, I think I'm in the right way, there are some rendering problem to solve, but the main behavior is what I was searching for.

I created a new type of view which inherit from the 'FormView' one and override the 'can_be_discarded' method to not execute controls about the data changes.

JS

```<code>odoo.define('levelprime_product_general_status.readonly_formview', function(require) {
    'use strict'

    var core = require('web.core')
    var FormView = require('web.FormView')

    var ReadOnly_FormView = FormView.extend({
        init: function() {
            this._super.apply(this, arguments)
        },
        start: function() {
            this._super.apply(this, arguments)
        },
        can_be_discarded: function() {
            return $.Deferred().resolve()
        }
    })

    core.view_registry.add('readonly_form', ReadOnly_FormView)

    return ReadOnly_FormView
})
</code>```

PY

```<code>class ViewExtension(models.Model):
    _inherit = 'ir.ui.view'

    type = fields.Selection(selection_add=[
        ('readonly_form', 'ReadOnly Form Version')])
</code>```

Then you can simply use the  tag in the xml.

Title: Odoo 10 - Form view opened in edit mode

Body:
Ok, I think I'm in the right way, there are some rendering problem to solve, but the main behavior is what I was searching for.

I created a new type of view which inherit from the 'FormView' one and override the 'can_be_discarded' method to not execute controls about the data changes.

JS

odoo.define('levelprime_product_general_status.readonly_formview', function(require) {
    'use strict'

    var core = require('web.core')
    var FormView = require('web.FormView')

    var ReadOnly_FormView = FormView.extend({
        init: function() {
            this._super.apply(this, arguments)
        },
        start: function() {
            this._super.apply(this, arguments)
        },
        can_be_discarded: function() {
            return $.Deferred().resolve()
        }
    })

    core.view_registry.add('readonly_form', ReadOnly_FormView)

    return ReadOnly_FormView
})

PY

class ViewExtension(models.Model):
    _inherit = 'ir.ui.view'

    type = fields.Selection(selection_add=[
        ('readonly_form', 'ReadOnly Form Version')])

Then you can simply use the  tag in the xml.


问:
Delete automation records in elasticsearch
I am using elastic search. I want to store data in a date range. I want to remove old data.

I use api for deleting data in date range which i want to remove.

I see time to live api in ES but it is deprecated.

Thank you.

答:
You can use time-based idex name patterns such as myindex-YYYY-MM-DD and drop old indexes on demand

See https://www.elastic.co/guide/en/elasticsearch/guide/current/time-based.html

To delete old indices you should use Curator and its index deletion feature.


问:
Java - Pack referenced libraries into jar file and re-use
When I create a new Java project that use third party dependencies such as MySQL-Connector, and export this into a jar file to use in another Java project, how do I avoid having to add (again) the MySQL-Connector library to the new projects build path?

What I would like to achieve is to pack down referenced libraries with the jar file, so when I add it to a new project its dependencies are already met within the jar "container" and I can avoid

Exception in thread "main" java.lang.ClassNotFoundException:
  com.mysql.jdbc.Driver

>>Example<<

When working with my SQL database I first need the MySQL-connector library, this of course have the prepared-statements methods, update query and so on. But it doesn't have (as far as I know) for example a method for multiple query updates or updates with an unknown number of ?,?,? arguments etc. So for my own part I have created a SQL manager project that contains a class that contains all the SQL methods I need.

I then import the MySQL-connector -> into the manager project and I would like to export this entire project as a self-contained jar file so when I import the manager jar into a project that needs a database, I don't need to both import the manager jar and the connector, but just the manager that than contains the connector.

答:
Here is what to do technically (in Eclipse, as you tagged it):

Open your project`s properties and click on "Java Build Path".

Switch to the tab named "Order and Export".

Make sure to check the checkboxes for all the jars you want to have in your jar.

But there is one more thing to do: you should carefully check the licence of the jars you want to include in this way because you may not be allowed to do so.


问:
scikit-learn error: The least populated class in y has only 1 member
I'm trying to split my dataset into a training and a test set by using the train_test_split function from scikit-learn, but I'm getting this error:

```<code>In [1]: y.iloc[:,0].value_counts()
Out[1]:
M2    38
M1    35
M4    29
M5    15
M0    15
M3    15

In [2]: xtrain, xtest, ytrain, ytest = train_test_split(X, y, test_size=1/3, random_state=85, stratify=y)
Out[2]:
Traceback (most recent call last):
  File "run_ok.py", line 48, in <module>
    xtrain,xtest,ytrain,ytest = train_test_split(X,y,test_size=1/3,random_state=85,stratify=y)
  File "/home/aurora/.pyenv/versions/3.6.0/lib/python3.6/site-packages/sklearn/model_selection/_split.py", line 1700, in train_test_split
    train, test = next(cv.split(X=arrays[0], y=stratify))
  File "/home/aurora/.pyenv/versions/3.6.0/lib/python3.6/site-packages/sklearn/model_selection/_split.py", line 953, in split
    for train, test in self._iter_indices(X, y, groups):
  File "/home/aurora/.pyenv/versions/3.6.0/lib/python3.6/site-packages/sklearn/model_selection/_split.py", line 1259, in _iter_indices
    raise ValueError("The least populated class in y has only 1"
ValueError: The least populated class in y has only 1 member, which is too few. The minimum number of groups for any class cannot be less than 2.
</code>```

However, all classes have at least 15 samples. Why am I getting this error?

X is a pandas DataFrame which represents the data points, y is a pandas DataFrame with one column that contains the target variable.

I cannot post the original data because it's proprietary, but it is fairly reproducible by creating a random pandas DataFrame (X) with 1k rows x 500 columns, and a random pandas DataFrame (y) with the same number of rows (1k) of X, and, for each row the target variable (a categorical label).
The y pandas DataFrame should have different categorical labels (e.g. 'class1', 'class2'...) and each labels should have at least 15 occurrences.

答:
The problem was that train_test_split takes as input 2 arrays, but the y array is a one-column matrix. If I pass only the first column of y it works.

```<code>train, xtest, ytrain, ytest = train_test_split(X, y.iloc[:,1], test_size=1/3,
  random_state=85, stratify=y.iloc[:,1])
</code>```

Body:
I'm trying to split my dataset into a training and a test set by using the train_test_split function from scikit-learn, but I'm getting this error:

In [1]: y.iloc[:,0].value_counts()
Out[1]:
M2    38
M1    35
M4    29
M5    15
M0    15
M3    15

In [2]: xtrain, xtest, ytrain, ytest = train_test_split(X, y, test_size=1/3, random_state=85, stratify=y)
Out[2]:
Traceback (most recent call last):
  File "run_ok.py", line 48, in <module>
    xtrain,xtest,ytrain,ytest = train_test_split(X,y,test_size=1/3,random_state=85,stratify=y)
  File "/home/aurora/.pyenv/versions/3.6.0/lib/python3.6/site-packages/sklearn/model_selection/_split.py", line 1700, in train_test_split
    train, test = next(cv.split(X=arrays[0], y=stratify))
  File "/home/aurora/.pyenv/versions/3.6.0/lib/python3.6/site-packages/sklearn/model_selection/_split.py", line 953, in split
    for train, test in self._iter_indices(X, y, groups):
  File "/home/aurora/.pyenv/versions/3.6.0/lib/python3.6/site-packages/sklearn/model_selection/_split.py", line 1259, in _iter_indices
    raise ValueError("The least populated class in y has only 1"
ValueError: The least populated class in y has only 1 member, which is too few. The minimum number of groups for any class cannot be less than 2.

However, all classes have at least 15 samples. Why am I getting this error?

X is a pandas DataFrame which represents the data points, y is a pandas DataFrame with one column that contains the target variable.

I cannot post the original data because it's proprietary, but it is fairly reproducible by creating a random pandas DataFrame (X) with 1k rows x 500 columns, and a random pandas DataFrame (y) with the same number of rows (1k) of X, and, for each row the target variable (a categorical label).
The y pandas DataFrame should have different categorical labels (e.g. 'class1', 'class2'...) and each labels should have at least 15 occurrences.

Body:
The problem was that train_test_split takes as input 2 arrays, but the y array is a one-column matrix. If I pass only the first column of y it works.

train, xtest, ytrain, ytest = train_test_split(X, y.iloc[:,1], test_size=1/3,
  random_state=85, stratify=y.iloc[:,1])


问:
SQL statement to retrieve the last filled column value as result
Using the below sql statement to get the last filled column from a table fields but not getting it to work.

```<code>select
  iif(isnull(AppBy11,true),
  iif(isnull(AppBy10,true),
  iif(isnull(AppBy9,true),
  iif(isnull(AppBy8,true),
  iif(isnull(AppBy7,true),
  iif(isnull(AppBy6,true),
  iif(isnull(AppBy5,true),
  iif(isnull(AppBy4,true),
  iif(isnull(AppBy3,true),
  iif(isnull(AppBy2,true), "", AppBy2), AppBy3), AppBy4), AppBy5), AppBy6), AppBy7), AppBy8), AppBy9, AppBy10), AppBy11) as Result
from entry
</code>```

Is there any other method which works in lightening speed to arrive the expected result?  I am going to run this query for 6 million data.

答:
Make use of COALESCE (Transact-SQL) . It will return first NOT Null column value in the list.</p>

```<code>SELECT COALESCE(AppBy11, AppBy10,AppBy9,AppBy8,AppBy7,AppBy6,AppBy5,AppBy4,AppBy3,AppBy2,AppBy1) as Result
FROM entry
</code>```

Body:
Using the below sql statement to get the last filled column from a table fields but not getting it to work.

select
  iif(isnull(AppBy11,true),
  iif(isnull(AppBy10,true),
  iif(isnull(AppBy9,true),
  iif(isnull(AppBy8,true),
  iif(isnull(AppBy7,true),
  iif(isnull(AppBy6,true),
  iif(isnull(AppBy5,true),
  iif(isnull(AppBy4,true),
  iif(isnull(AppBy3,true),
  iif(isnull(AppBy2,true), "", AppBy2), AppBy3), AppBy4), AppBy5), AppBy6), AppBy7), AppBy8), AppBy9, AppBy10), AppBy11) as Result
from entry

Is there any other method which works in lightening speed to arrive the expected result?  I am going to run this query for 6 million data.

Body:
Make use of COALESCE (Transact-SQL) . It will return first NOT Null column value in the list.

SELECT COALESCE(AppBy11, AppBy10,AppBy9,AppBy8,AppBy7,AppBy6,AppBy5,AppBy4,AppBy3,AppBy2,AppBy1) as Result
FROM entry


问:
ASP.NET C# foreach only print last item in list
I would like to show all valid links in a Literal Control container after clicking a button. However, only the last item in the list can be shown. I have used both for and foreach loop for testing but still not successful.

Any help is appreciated. Thanks in advance.

Here is my code:

```<code>public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ValidateButton.Click += ValidateButtonHandler;
        }

        private void ValidateButtonHandler(object sender, EventArgs e)
        {
            List<string> validPages = new List<string>();
            validPages.Add("www.google.com");
            validPages.Add("www.yahoo.com");
            validPages.Add("www.facebook.com");

            List<string> invalidPages = new List<string>();
            invalidPages.Add("www.gogle.com");
            invalidPages.Add("www.yaoo.com");
            invalidPages.Add("www.facbook.com");

            for (int i = 0; i < validPages.Count; i++)
            {
                ValidLinksBox.Text = "<br/>" + validPages[i] + "<br/>";
            }

            foreach (string invalidPage in invalidPages)
            {
                InvalidLinksBox.Text = string.Format("<div class=\"alert success\"><p>{0}</p></div>", invalidPage);
            }
        }
    }
</code>```

Here is the aspx part:

```<code><div class="admin-page">
      <h1>Valid Links:</h1>
        <asp:Literal ID="ValidLinksBox" runat="server" />
      <h1>Invalid Links:</h1>
        <asp:Literal ID="InvalidLinksBox" runat="server" />
    <asp:Button ID="ValidateButton" runat="server" CssClass="btn btn-default" Text="Validate links" />
  </div>
</code>```

This is the result:

Validate Links result

答:
You have missed concatenation operator. You are actually overwriting your string again n again in all of your iterations. You can replace the following:

```<code>ValidLinksBox.Text = "<br/>" + validPages[i] + "<br/>";
</code>```

with

```<code>ValidLinksBox.Text += ("<br/>" + validPages[i] + "<br/>");
</code>```

The better approach is to use StringBuilder

```<code>StringBuilder builder = new StringBuilder();

for (int i = 0; i < validPages.Count; i++)
{
     builder.Append("<br/>");
     builder.Append(validPages[i]);
     builder.Append("<br/>");
}

ValidLinksBox.Text =  builder.ToString();

builder = new StringBuilder();

foreach (string invalidPage in invalidPages)
{
    builder.Append("<div class=\"alert success\"><p>");
    builder.Append(invalidPage);
    builder.Append("</p></div>");
}

InvalidLinksBox.Text = builder.ToString();
</code>```

StringBuilder is better, more readable and faster than concatenation operator.

Body:
I would like to show all valid links in a Literal Control container after clicking a button. However, only the last item in the list can be shown. I have used both for and foreach loop for testing but still not successful.

Any help is appreciated. Thanks in advance.

Here is my code:

public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ValidateButton.Click += ValidateButtonHandler;
        }

        private void ValidateButtonHandler(object sender, EventArgs e)
        {
            List<string> validPages = new List<string>();
            validPages.Add("www.google.com");
            validPages.Add("www.yahoo.com");
            validPages.Add("www.facebook.com");

            List<string> invalidPages = new List<string>();
            invalidPages.Add("www.gogle.com");
            invalidPages.Add("www.yaoo.com");
            invalidPages.Add("www.facbook.com");

            for (int i = 0; i < validPages.Count; i++)
            {
                ValidLinksBox.Text = "
" + validPages[i] + "
";
            }

            foreach (string invalidPage in invalidPages)
            {
                InvalidLinksBox.Text = string.Format("

{0}

", invalidPage);
            }
        }
    }

Here is the aspx part:

Valid Links:

        <asp:Literal ID="ValidLinksBox" runat="server" />

Invalid Links:

        <asp:Literal ID="InvalidLinksBox" runat="server" />
    <asp:Button ID="ValidateButton" runat="server" CssClass="btn btn-default" Text="Validate links" />

This is the result:

Validate Links result

Body:
You have missed concatenation operator. You are actually overwriting your string again n again in all of your iterations. You can replace the following:

ValidLinksBox.Text = "<br/>" + validPages[i] + "<br/>";

with

ValidLinksBox.Text += ("<br/>" + validPages[i] + "<br/>");

The better approach is to use StringBuilder

StringBuilder builder = new StringBuilder();

for (int i = 0; i < validPages.Count; i++)
{
     builder.Append("<br/>");
     builder.Append(validPages[i]);
     builder.Append("<br/>");
}

ValidLinksBox.Text =  builder.ToString();

builder = new StringBuilder();

foreach (string invalidPage in invalidPages)
{
    builder.Append("<div class=\"alert success\"><p>");
    builder.Append(invalidPage);
    builder.Append("</p></div>");
}

InvalidLinksBox.Text = builder.ToString();

StringBuilder is better, more readable and faster than concatenation operator.


问:
Contiki delay in seconds
I am trying to develop a contiki piece of code in which I need to wait for three seconds for a transducer output. Although this may sound quite un-transducer like, at development time, I want to simulate the behavior at human readable speeds and hence I need to set the timer to say 3 seconds.

The contiki timer library is pretty well documented and has a good series of examples which mention the creation, setting and resetting of the timer. However, if I have code like the following:

```<code>timer_set(&transducerOutputWaitTimer);
bool if_blk_executed;
if(timer_expired(&&transducerOutputWaitTimer)){
    if_blk_executed = true;
    //do something
}
if(if_blk_executed)
   printf("Sunrise");
else
   printf("It is not dawned yet");
</code>```

Now the expiry is not immediately triggered after the timer is set. So the if block is never executed. Effectively it will never dawn.

Now there are two ways in which I can get the system to wait. One, by adding a while loop on the timer like this:
   while(!timer_expired(&&transducerOutputWaitTimer)){};
   //do something

or
   cpu_delay_usecs{mytimerdur_in_secs*10^6*};
   //do something

I do not see that either approaches are elegant. While one wastes CPU cycles, the other enforces an unnecessarily large computation.

Is there any better way? I know that clock

Attached to this question are the following two:

How can I trigger one Contiki protothread from another? If I can do this, I can get the interrupt that causes the transducerOutput to invoke a process from which I can trigger the etimer and process events.

What exactly does the CPU delay mean? Does this mean that the entire CPU clock cycles get held back for the given duration? If yes, how are other processes running currently in the system affected?

Updates
Update 1: the while method did not work. The code possibly went into an infinite loop.
Update 2: I tried with a clock_delay(3*CLOCK_SECOND) approach after setting my timer. It worked. However, in this case, why do I need the timer method at all?

Update 3 (This changes the context of the answer, hence adding this comment as per the suggestion)

My Timer needs to be used outside a process in a different void function. In that case, I need to use the timer() library rather than the etimer (which is specific to a process. So how do I get my method to wait for the desired time in such cases?

答:
There are several Contiki abstractions built on top of the timer library - there is usually no need to user the timer_t structures directly. Instead, there are event timers (struct etimer), which play well together with Contiki processes, and callback timers (struct ctimer), both of which internally use struct timer. For a less RAM hungry option with a more limited API there are second timers (struct stimer). Finally, there is a single real-time timer in the system (struct rtimer).

An example event timer usage: set and wait for 3 seconds:

```<code>static struct etimer timer;
etimer_set(&timer, 3 * CLOCK_SECOND);
PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&timer));
</code>```

How can I trigger one Contiki protothread from another?

There is process_poll - see the process API documentation for more examples.

What exactly does the CPU delay mean?

It's a form of busy waiting. Don't use the delay functions or other forms of busy waiting for delays longer than microseconds - not energy efficient, does not allow other processes to run, and in worst case the watchdog might expire.

Title: Contiki delay in seconds

Body:
I am trying to develop a contiki piece of code in which I need to wait for three seconds for a transducer output. Although this may sound quite un-transducer like, at development time, I want to simulate the behavior at human readable speeds and hence I need to set the timer to say 3 seconds.

The contiki timer library is pretty well documented and has a good series of examples which mention the creation, setting and resetting of the timer. However, if I have code like the following:

timer_set(&transducerOutputWaitTimer);
bool if_blk_executed;
if(timer_expired(&&transducerOutputWaitTimer)){
    if_blk_executed = true;
    //do something
}
if(if_blk_executed)
   printf("Sunrise");
else
   printf("It is not dawned yet");

Now the expiry is not immediately triggered after the timer is set. So the if block is never executed. Effectively it will never dawn.

Now there are two ways in which I can get the system to wait. One, by adding a while loop on the timer like this:
   while(!timer_expired(&&transducerOutputWaitTimer)){};
   //do something

or
   cpu_delay_usecs{mytimerdur_in_secs*10^6*};
   //do something

I do not see that either approaches are elegant. While one wastes CPU cycles, the other enforces an unnecessarily large computation.

Is there any better way? I know that clock

Attached to this question are the following two:

How can I trigger one Contiki protothread from another? If I can do this, I can get the interrupt that causes the transducerOutput to invoke a process from which I can trigger the etimer and process events.

What exactly does the CPU delay mean? Does this mean that the entire CPU clock cycles get held back for the given duration? If yes, how are other processes running currently in the system affected?

Updates
Update 1: the while method did not work. The code possibly went into an infinite loop.
Update 2: I tried with a clock_delay(3*CLOCK_SECOND) approach after setting my timer. It worked. However, in this case, why do I need the timer method at all?

Update 3 (This changes the context of the answer, hence adding this comment as per the suggestion)

My Timer needs to be used outside a process in a different void function. In that case, I need to use the timer() library rather than the etimer (which is specific to a process. So how do I get my method to wait for the desired time in such cases?

Body:
There are several Contiki abstractions built on top of the timer library - there is usually no need to user the timer_t structures directly. Instead, there are event timers (struct etimer), which play well together with Contiki processes, and callback timers (struct ctimer), both of which internally use struct timer. For a less RAM hungry option with a more limited API there are second timers (struct stimer). Finally, there is a single real-time timer in the system (struct rtimer).

An example event timer usage: set and wait for 3 seconds:

static struct etimer timer;
etimer_set(&timer, 3 * CLOCK_SECOND);
PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&timer));

How can I trigger one Contiki protothread from another?

There is process_poll - see the process API documentation for more examples.

What exactly does the CPU delay mean?

It's a form of busy waiting. Don't use the delay functions or other forms of busy waiting for delays longer than microseconds - not energy efficient, does not allow other processes to run, and in worst case the watchdog might expire.


问:
Hibernate Search - applying facet on a query brings back no results
I'm trying to narrow down my original query with one of the returned facets, but this doesn't seem to work, i.e. it brings back no results. The first time I call list() method, I get 8 products (out of 15 total, these are limited by setMaxResults() method) and the list of two facets: one with the count 14 and the other one with count 1. When I apply the first facet to the current query and re-execute the query with the list() method, I am expecting to see a total of 14 products, but an empty list is being returned instead. I can't see anything I'm doing that's different from the documentation.

Bulding query:

```<code>Session session = entityManager.unwrap(Session.class);
        FullTextSession fullTextSession = org.hibernate.search.Search.getFullTextSession(session);

        QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder()
                .forEntity(Product.class).get();

        Query luceneQuery = queryBuilder.all().createQuery();

        FacetingRequest categoryFacetingRequest = queryBuilder.facet()
                .name("categoryFaceting")
                .onField("productCategoryId")
                .discrete()
                .orderedBy(FacetSortOrder.COUNT_DESC)
                .includeZeroCounts(false)
                .createFacetingRequest();

        FullTextQuery hibernateQuery = fullTextSession.createFullTextQuery(luceneQuery, Product.class);

        hibernateQuery.setFirstResult(pageable.getOffset());
        hibernateQuery.setMaxResults(pageable.getPageSize());

        FacetManager facetManager = hibernateQuery.getFacetManager();
        facetManager.enableFaceting(categoryFacetingRequest);

        @SuppressWarnings("unchecked")
        List<Product> products = hibernateQuery.list();

        List<Facet> categoryFacets = facetManager.getFacets("categoryFaceting");

        FacetSelection facetSelection = facetManager.getFacetGroup("categoryFaceting");
        facetSelection.selectFacets(categoryFacets.get(0));
        products = hibernateQuery.list();
</code>```

productCategoryId field on Product entity:

```<code>@Field(analyze = Analyze.NO)
@NumericField
@Facet(encoding = FacetEncodingType.STRING)
private Long productCategoryId;
</code>```

答:
I am afraid this is a bug. Thanks for asking though: now that we are aware of it, we can work on fixing it. The ticket for this bug is HSEARCH-2668.

There is a workaround though: you can make your field non-numeric. Just remove the @NumericField annotation and use org.hibernate.search.bridge.builtin.LongBridge to index it:

```<code>@Field(analyze = Analyze.NO, bridge = @FieldBridge(impl = org.hibernate.search.bridge.builtin.LongBridge.class))
@Facet(encoding = FacetEncodingType.STRING)
private Long productCategoryId;
</code>```

If you need this field for other purposes, you can just create a second field, and apply faceting on that second field:

```<code>@Field(analyze = Analyze.NO)
@NumericField
@Field(name = "productCategoryId_facet", analyze = Analyze.NO, bridge = @FieldBridge(impl = org.hibernate.search.bridge.builtin.LongBridge.class))
@Facet(forField = "productCategoryId_facet", encoding = FacetEncodingType.STRING)
private Long productCategoryId;
// Then use productCategoryId_facet instead of productCategoryId in your facet-enabled queries
</code>```

Body:
I'm trying to narrow down my original query with one of the returned facets, but this doesn't seem to work, i.e. it brings back no results. The first time I call list() method, I get 8 products (out of 15 total, these are limited by setMaxResults() method) and the list of two facets: one with the count 14 and the other one with count 1. When I apply the first facet to the current query and re-execute the query with the list() method, I am expecting to see a total of 14 products, but an empty list is being returned instead. I can't see anything I'm doing that's different from the documentation.

Bulding query:

Session session = entityManager.unwrap(Session.class);
        FullTextSession fullTextSession = org.hibernate.search.Search.getFullTextSession(session);

        QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder()
                .forEntity(Product.class).get();

        Query luceneQuery = queryBuilder.all().createQuery();

        FacetingRequest categoryFacetingRequest = queryBuilder.facet()
                .name("categoryFaceting")
                .onField("productCategoryId")
                .discrete()
                .orderedBy(FacetSortOrder.COUNT_DESC)
                .includeZeroCounts(false)
                .createFacetingRequest();

        FullTextQuery hibernateQuery = fullTextSession.createFullTextQuery(luceneQuery, Product.class);

        hibernateQuery.setFirstResult(pageable.getOffset());
        hibernateQuery.setMaxResults(pageable.getPageSize());

        FacetManager facetManager = hibernateQuery.getFacetManager();
        facetManager.enableFaceting(categoryFacetingRequest);

        @SuppressWarnings("unchecked")
        List<Product> products = hibernateQuery.list();

        List<Facet> categoryFacets = facetManager.getFacets("categoryFaceting");

        FacetSelection facetSelection = facetManager.getFacetGroup("categoryFaceting");
        facetSelection.selectFacets(categoryFacets.get(0));
        products = hibernateQuery.list();

productCategoryId field on Product entity:

@Field(analyze = Analyze.NO)
@NumericField
@Facet(encoding = FacetEncodingType.STRING)
private Long productCategoryId;

Body:
I am afraid this is a bug. Thanks for asking though: now that we are aware of it, we can work on fixing it. The ticket for this bug is HSEARCH-2668.

There is a workaround though: you can make your field non-numeric. Just remove the @NumericField annotation and use org.hibernate.search.bridge.builtin.LongBridge to index it:

@Field(analyze = Analyze.NO, bridge = @FieldBridge(impl = org.hibernate.search.bridge.builtin.LongBridge.class))
@Facet(encoding = FacetEncodingType.STRING)
private Long productCategoryId;

If you need this field for other purposes, you can just create a second field, and apply faceting on that second field:

@Field(analyze = Analyze.NO)
@NumericField
@Field(name = "productCategoryId_facet", analyze = Analyze.NO, bridge = @FieldBridge(impl = org.hibernate.search.bridge.builtin.LongBridge.class))
@Facet(forField = "productCategoryId_facet", encoding = FacetEncodingType.STRING)
private Long productCategoryId;
// Then use productCategoryId_facet instead of productCategoryId in your facet-enabled queries


问:
Make UITextField accept small alphabet letter only in Swift?
I Want to Make textField that accept only small alphabet letter not capital alphabet letter or no any special symbol or not any digit.</p>

答:
check this  updated code:

```<code>- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSLog(@"textField:shouldChangeCharactersInRange:replacementString:");
         NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyz"];
        for (int i = 0; i < [string length]; i++)
        {
            unichar c = [string characterAtIndex:i];
            if (![myCharSet characterIsMember:c])
            {
                return NO;
            }
        }

        return YES;
    }

}
</code>```

in Swift

```<code> func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

        let set = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyz").invertedSet
        return string.rangeOfCharacterFromSet(set) == nil

    }
</code>```

Body:
check this  updated code:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSLog(@"textField:shouldChangeCharactersInRange:replacementString:");
         NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyz"];
        for (int i = 0; i < [string length]; i++)
        {
            unichar c = [string characterAtIndex:i];
            if (![myCharSet characterIsMember:c])
            {
                return NO;
            }
        }

        return YES;
    }

}

in Swift

 func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

        let set = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyz").invertedSet
        return string.rangeOfCharacterFromSet(set) == nil

    }


问:
How to fix SQLAlchemy: SAWarning: DELETE statement on table expected to delete 1 row(s); 0 were matched
I am building a Python Flask app with a directed graph  data model using SQLAlchemy with PostgreSQL.  I am having
trouble setting up the delete cascade.  While deleting appears to work given rudimentary inspection, I am unsure if I
might be corrupting things in ways that I do not understand, because I get the following warning:

```<code>SAWarning: DELETE statement on table 'edges' expected to delete 1 row(s); 0 were matched.
Please set confirm_deleted_rows=False within the mapper configuration to prevent this warning.  (table.description, expected,rows_matched)
</code>```

Here is the core of my data model.

```<code>class Node(db.Model):
    __tablename__ = 'nodes'

    __mapper_args__ = {
        'polymorphic_on': type,
        'polymorphic_identity': 'node'
    }

    id = Column(BigInteger, primary_key=True)
    type = Column(String)

    in_edges = relationship("Edge", cascade="save-update, merge, delete", foreign_keys="Edge.dest", back_populates='dest_node')
    out_edges = relationship("Edge", cascade="save-update, merge, delete", foreign_keys="Edge.src", back_populates='src_node')

class Edge(db.Model):
    __tablename__ = 'edges'

    __mapper_args__ = {
        'polymorphic_on': type,
        'polymorphic_identity': 'edge'
    }

    type = Column(String, primary_key="True")

    src = Column(Integer, ForeignKey('nodes.id'), primary_key=True)
    dest = Column(Integer, ForeignKey('nodes.id'), primary_key=True)

    src_node = relationship("Node", foreign_keys=[src], back_populates='out_edges')
    dest_node = relationship("Node", foreign_keys=[dest], back_populates='in_edges')
</code>```

Nodes are connected by Edges in a directed way.  An Edge's connects a src Node to a dest Node. One thing to note is
that a Node has a primary key of id, while an Edge has a composite primary key of its type, src and dest. Since you
can't have an Edge with src or dest set to NULL, if a Node is deleted, then all Edges that refer to it in any way must
be deleted too.

In the model I have created SQLAlchemy relationships on both Node and Edge which populate each other.  On the Node
side, I can access incoming and outgoing Edges, and an Edge can access the Nodes it connects.

What I'm trying to do is to delete a subset of the graph. To do to this, I'm walking the the graph by starting at a Node
and traversing the Node's out_edges.  I am only explicitly deleting the Nodes.  I am relying on the cascade delete that
I've configured on both of the Node's relationships to take care of deleting the Edges.

When configured as shown, I always seem to get the warning, which seems to indicate that something is not being deleted.
However, if I remove the cascade delete on the Node's in_edges, the warning goes away.

I think what might be happening is that, since an Edge must have both Nodes present, when I delete the src Node,
it deletes the outgoing Edges and then when I delete those Edge's dest Node, it looks for the incoming Edge,
 but it's already been deleted.

So removing cascades fixes the warning and works in some situations, but there are times when I'm deleting a Node that
has an incoming Edge whose src Node is not one I am visiting on my walk.  Therefore it's critcal to make sure that both
relationships cause a delete cascade and so I don't think suppressing the warning in this way is the right thing to do.

Can anyone explain what's happening?  Is this safe to ignore? Am I doing it wrong?

答:
I think your problem is related https://bitbucket.org/zzzeek/sqlalchemy/issues/2403/work-around-mysql-innodb-bug-need-per

You can try this code.

```<code>class Edge(db.Model):
    __tablename__ = 'edges'

    __mapper_args__ = {
        'polymorphic_on': type,
        'polymorphic_identity': 'edge',
        'confirm_deleted_rows': False
    }
</code>```

Body:
I am building a Python Flask app with a directed graph  data model using SQLAlchemy with PostgreSQL.  I am having
trouble setting up the delete cascade.  While deleting appears to work given rudimentary inspection, I am unsure if I
might be corrupting things in ways that I do not understand, because I get the following warning:

SAWarning: DELETE statement on table 'edges' expected to delete 1 row(s); 0 were matched.
Please set confirm_deleted_rows=False within the mapper configuration to prevent this warning.  (table.description, expected,rows_matched)

Here is the core of my data model.

class Node(db.Model):
    __tablename__ = 'nodes'

    __mapper_args__ = {
        'polymorphic_on': type,
        'polymorphic_identity': 'node'
    }

    id = Column(BigInteger, primary_key=True)
    type = Column(String)

    in_edges = relationship("Edge", cascade="save-update, merge, delete", foreign_keys="Edge.dest", back_populates='dest_node')
    out_edges = relationship("Edge", cascade="save-update, merge, delete", foreign_keys="Edge.src", back_populates='src_node')

class Edge(db.Model):
    __tablename__ = 'edges'

    __mapper_args__ = {
        'polymorphic_on': type,
        'polymorphic_identity': 'edge'
    }

    type = Column(String, primary_key="True")

    src = Column(Integer, ForeignKey('nodes.id'), primary_key=True)
    dest = Column(Integer, ForeignKey('nodes.id'), primary_key=True)

    src_node = relationship("Node", foreign_keys=[src], back_populates='out_edges')
    dest_node = relationship("Node", foreign_keys=[dest], back_populates='in_edges')

Nodes are connected by Edges in a directed way.  An Edge's connects a src Node to a dest Node. One thing to note is
that a Node has a primary key of id, while an Edge has a composite primary key of its type, src and dest. Since you
can't have an Edge with src or dest set to NULL, if a Node is deleted, then all Edges that refer to it in any way must
be deleted too.

In the model I have created SQLAlchemy relationships on both Node and Edge which populate each other.  On the Node
side, I can access incoming and outgoing Edges, and an Edge can access the Nodes it connects.

What I'm trying to do is to delete a subset of the graph. To do to this, I'm walking the the graph by starting at a Node
and traversing the Node's out_edges.  I am only explicitly deleting the Nodes.  I am relying on the cascade delete that
I've configured on both of the Node's relationships to take care of deleting the Edges.

When configured as shown, I always seem to get the warning, which seems to indicate that something is not being deleted.
However, if I remove the cascade delete on the Node's in_edges, the warning goes away.

I think what might be happening is that, since an Edge must have both Nodes present, when I delete the src Node,
it deletes the outgoing Edges and then when I delete those Edge's dest Node, it looks for the incoming Edge,
 but it's already been deleted.

So removing cascades fixes the warning and works in some situations, but there are times when I'm deleting a Node that
has an incoming Edge whose src Node is not one I am visiting on my walk.  Therefore it's critcal to make sure that both
relationships cause a delete cascade and so I don't think suppressing the warning in this way is the right thing to do.

Can anyone explain what's happening?  Is this safe to ignore? Am I doing it wrong?

Body:
I think your problem is related https://bitbucket.org/zzzeek/sqlalchemy/issues/2403/work-around-mysql-innodb-bug-need-per

You can try this code.

class Edge(db.Model):
    __tablename__ = 'edges'

    __mapper_args__ = {
        'polymorphic_on': type,
        'polymorphic_identity': 'edge',
        'confirm_deleted_rows': False
    }


问:
how to print null value from javascript array?
I have data from php variable :

```<code>$data['value'] = [null, 24.5, 22.5, null, 30.1];
</code>```

I convert it into javascript using this code :

```<code>var newData = <?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>;
</code>```

I get output like this : , 24.5, 22.5,, 30.1

anyone can tell what's wrong with my code?

UPDATE

PHP variable :

```<code>$data['value'][] = null;
$data['value'][] = 24.5;
$data['value'][] = 22.5;
$data['value'][] = null;
$data['value'][] = 30.1;

$data['value2'][] = 20.5;
$data['value2'][] = 19.5;
$data['value2'][] = 30.1;
$data['value2'][] = null;

    echo json_encode($data, JSON_NUMERIC_CHECK);
</code>```

output : {"value":[null, 24.5, 22.5, null, 30.1],"value2":[20.5,19.5,30.1,null]};

JAVASCRIPT :

```<code>var newData = <?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>;

document.write(newData['value']);
</code>```

output : , 24.5, 22.5,, 30.1

i need javascript output to be like this : null, 24.5, 22.5, null, 30.1

答:
You were not trying to encode the array correctly.

Since the array you were using was actually stored in $data["value"] and not $data it meant that you were not creating the array correctly in JavaScript.

```<code>var newData = <?php echo json_encode($data["value"], JSON_NUMERIC_CHECK); ?>;
</code>```

Following edit

```<code><?php
$data[] = [null, 24.5, 22.5, null, 30.1];
for ($i = 0; $i < count($data); $i++) {
    for ($j = 0; $j < count($data); $j++)
        if ($data[$i][$j] === null) $data[$i][$j] = "null";
?>
<script>
var newData = <?php echo json_encode($data[$i], JSON_NUMERIC_CHECK); ?>
</script>
<?php } // end for ?>
</code>```

Body:
I have data from php variable :

$data['value'] = [null, 24.5, 22.5, null, 30.1];

I convert it into javascript using this code :

var newData = <?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>;

I get output like this : , 24.5, 22.5,, 30.1

anyone can tell what's wrong with my code?

UPDATE

PHP variable :

$data['value'][] = null;
$data['value'][] = 24.5;
$data['value'][] = 22.5;
$data['value'][] = null;
$data['value'][] = 30.1;

$data['value2'][] = 20.5;
$data['value2'][] = 19.5;
$data['value2'][] = 30.1;
$data['value2'][] = null;

    echo json_encode($data, JSON_NUMERIC_CHECK);

output : {"value":[null, 24.5, 22.5, null, 30.1],"value2":[20.5,19.5,30.1,null]};

JAVASCRIPT :

var newData = <?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>;

document.write(newData['value']);

output : , 24.5, 22.5,, 30.1

i need javascript output to be like this : null, 24.5, 22.5, null, 30.1

Body:
You were not trying to encode the array correctly.

Since the array you were using was actually stored in $data["value"] and not $data it meant that you were not creating the array correctly in JavaScript.

var newData = <?php echo json_encode($data["value"], JSON_NUMERIC_CHECK); ?>;

Following edit

<?php
$data[] = [null, 24.5, 22.5, null, 30.1];
for ($i = 0; $i < count($data); $i++) {
    for ($j = 0; $j < count($data); $j++)
        if ($data[$i][$j] === null) $data[$i][$j] = "null";
?>
<script>
var newData = <?php echo json_encode($data[$i], JSON_NUMERIC_CHECK); ?>
</script>
<?php } // end for ?>


问:
Send a String message from my Netty client to my server
I have a Netty Client and a Netty Server, and after following the main tutorials in order to have an EchoClient / Server I wanted to make it so that my Client sends a message to my Server when he first connects to it.

Here are my ClientClassHandler's methods that should take care of that:

```<code> private final ByteBuf firstMessage;

    public ClientClassHandler() {
        firstMessage = Unpooled.buffer(ClientClass.SIZE);
        for (int i = 0; i < firstMessage.capacity(); i++) {
            firstMessage.writeByte((byte) i);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("Channel is active.");
        ctx.writeAndFlush(firstMessage);
    }
</code>```

But as you can see the tutorial uses a ByteBuf and the use of a String does not seem to work !

Here is how I display my received message in my ServerClassHandler's method:

```<code>@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    System.out.println(msg);
}
</code>```

But when using a String for firstMessage and initializing it in the constructor and sending it, my Server does not display anything !

What did I not understand?

答:
Just want add more info about String in netty ,

you can do convert Object into Bytebuff

```<code> ByteBuf in = (ByteBuf) msg;
 String data = in.toString(CharsetUtil.UTF_8);
</code>```

But if you have long String object I suggest using StringEncoder and decoder for netty and LineBasedFrameDecoder and extends you handler to

```<code>SimpleChannelInboundHandler<String>
</code>```

Body:
I have a Netty Client and a Netty Server, and after following the main tutorials in order to have an EchoClient / Server I wanted to make it so that my Client sends a message to my Server when he first connects to it.

Here are my ClientClassHandler's methods that should take care of that:

 private final ByteBuf firstMessage;

    public ClientClassHandler() {
        firstMessage = Unpooled.buffer(ClientClass.SIZE);
        for (int i = 0; i < firstMessage.capacity(); i++) {
            firstMessage.writeByte((byte) i);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("Channel is active.");
        ctx.writeAndFlush(firstMessage);
    }

But as you can see the tutorial uses a ByteBuf and the use of a String does not seem to work !

Here is how I display my received message in my ServerClassHandler's method:

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    System.out.println(msg);
}

But when using a String for firstMessage and initializing it in the constructor and sending it, my Server does not display anything !

What did I not understand?

Body:
Just want add more info about String in netty ,

you can do convert Object into Bytebuff

 ByteBuf in = (ByteBuf) msg;
 String data = in.toString(CharsetUtil.UTF_8);

But if you have long String object I suggest using StringEncoder and decoder for netty and LineBasedFrameDecoder and extends you handler to

SimpleChannelInboundHandler<String>


问:
PHP Mail adding BCC
I have a form that populates a PHP mail to be sent to our clients, I want to BCC most of the clients due to privacy. I have the following code

```<code>$to = "******@e-track.co.za"; //To recipients
$email_from = '*****@etrackbureau.co.za';//<== update the email address
$email_subject = "New Overdue Loaded";
$email_body = "A new High Risk Client has been loaded by $name $company.\n".
    "\n Client Name: $driver_name $driver_surname\n
    \n Client ID or Passport Number: $driver_id\n
    \n Nationality: $driver_nationality\n
    \n Reason for Loading Client: $type\n
    \n Notes: $notes\n
    ".
$headers = "From: $email_from \r\n";
$headers = "Bcc: ******@e-track.co.za;*****@e-track.co.za;******@e-track.co.za\r\n";
//$headers = "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
</code>```

I have added the BCC as a $headers but once I add this it doesn't send mails at all when I remove it I get the mail to the $to recipient.

I have tried spacing between the BCC mails as well. I have replaced the mail names with **** for spamming reasons

答:
You should concatenate $headers

Example :

```<code>$headers  = "From: *****@etrackbureau.co.za\r\nX-Mailer: php\r\n";
$headers .= "MIME-Version: 1.0\r\n"; #Define MIME Version
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; #Set content type
$headers .= "Bcc: $EmailListHere\r\n"; #Your BCC Mail List
</code>```

Title: PHP Mail adding BCC

Body:
I have a form that populates a PHP mail to be sent to our clients, I want to BCC most of the clients due to privacy. I have the following code

$to = "******@e-track.co.za"; //To recipients
$email_from = '*****@etrackbureau.co.za';//<== update the email address
$email_subject = "New Overdue Loaded";
$email_body = "A new High Risk Client has been loaded by $name $company.\n".
    "\n Client Name: $driver_name $driver_surname\n
    \n Client ID or Passport Number: $driver_id\n
    \n Nationality: $driver_nationality\n
    \n Reason for Loading Client: $type\n
    \n Notes: $notes\n
    ".
$headers = "From: $email_from \r\n";
$headers = "Bcc: ******@e-track.co.za;*****@e-track.co.za;******@e-track.co.za\r\n";
//$headers = "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);

I have added the BCC as a $headers but once I add this it doesn't send mails at all when I remove it I get the mail to the $to recipient.

I have tried spacing between the BCC mails as well. I have replaced the mail names with **** for spamming reasons

Body:
You should concatenate $headers

Example :

$headers  = "From: *****@etrackbureau.co.za\r\nX-Mailer: php\r\n";
$headers .= "MIME-Version: 1.0\r\n"; #Define MIME Version
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; #Set content type
$headers .= "Bcc: $EmailListHere\r\n"; #Your BCC Mail List


问:
Unfortunately MyApp has stopped. How can I solve this?
I am developing an application, and everytime I run it, I get the message:

Unfortunately, MyApp has stopped.

What can I do to solve this?

About this question - obviously inspired by What is a stack trace, and how can I use it to debug my application errors?, there are lots of questions stating that their application has crashed, without any further detail. This question aims to instruct novice Android programmers on how to try and fix their problems themselves, or ask the right questions.

答:
In below showToast() method you have to pass another parameter for context or application context by doing so you can try it.</p>

```<code>  public void showToast(String error, Context applicationContext){
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.custom_toast, (ViewGroup)
        findViewById(R.id.toast_root));
        TextView text = (TextView) findViewById(R.id.toast_error);
        text.setText(error);
        Toast toast = new Toast(applicationContext);
        toast.setGravity(Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(view);
        toast.show();
}
</code>```

Body:
In below showToast() method you have to pass another parameter for context or application context by doing so you can try it.

  public void showToast(String error, Context applicationContext){
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.custom_toast, (ViewGroup)
        findViewById(R.id.toast_root));
        TextView text = (TextView) findViewById(R.id.toast_error);
        text.setText(error);
        Toast toast = new Toast(applicationContext);
        toast.setGravity(Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(view);
        toast.show();
}


问:
Changing date format in access table
I have a field in which users should enter either a date for an order or specify if that order was 'CANCELLED'. I therefore made the field of type text. In order to keep the date format consistent in the database, I would like that field to store the date entered in Medium Date. I don't think I can use the Format function to fix this. I am using VBA for this Access application.
Should I rather use a checkbox/check type field for CANCELLED value and make the 'Order_Date' field of type date?</p>

答: The latter, don't mix types in a field. Have nullable Order_Date field a date and a boolean field for whether the order was cancelled.

Title: Changing date format in access table


问:
How to add "Vary: Accept-Encoding" header in yaws to cacheable files
I was testing my website for optimization and I got this recommendation:

```<code>The following publicly cacheable, compressible resources should have a "Vary: Accept-Encoding" header:
</code>```

So, How do I add Vary: Accept-Encoding header using an embedded yaws to css and js files?

I am an arg_rewrite_mod I believe I should do something from there but i am not quite sure how.

答:
According to the yaws.hyber.org:

Yaws will add Accept-Encoding in Vary header if the support of gzip compression is enabled or if the response is compressed.

The Vary header can be set using yaws:outh_set_vary(Fields) or by returning {header, {vary, Fields}} from scripts (where Fields is a list of header names).

Body:
I was testing my website for optimization and I got this recommendation:

The following publicly cacheable, compressible resources should have a "Vary: Accept-Encoding" header:

So, How do I add Vary: Accept-Encoding header using an embedded yaws to css and js files?

I am an arg_rewrite_mod I believe I should do something from there but i am not quite sure how.


问:
Android geofence with mock location provider
I have started developing on Android with last Location services feature : Geofences !! Is there any known problem with mock location provider ? Following example here (https://developer.android.com/training/location/geofencing.html) my intent service never fired even if the current location is inside geofence. I'm using FakeGPS android app as mock location provider and if I simulate a route I see the location changes on Google Maps app, so the mock location provider is working well. Any ideas ?

Thanks.
Paolo.

答:
Actually  Intent service used in the mentioned example works good if your app is in foreground but when the app is in background, this IntentService is never called.So we need to use Broadcast-Receiver instead of Intent service.

I found this blog helpful in getting solution.

http://davehiren.blogspot.in/2015/01/android-geofence-stop-getting.html


问:
how to call a function within an if statement (vba)
I am trying to call a function within my if statement. The function is called classyear and is just after the if. I am trying to run through a timetable and see what classes belong to each year. so if it ends in a 1 it will be counted. Does anyone know how I would go about calling the function? Any help is appreciated

```<code>Public Sub time()
Dim rgTimeTable As Range, rgClass As Range, counter As Integer

Set rgTimeTable = Range("B3, N11")

For Each rgClass In rgTimeTable
If rgClass.Value = classyear Then counter = counter + 1     ' classyear is the function

Next rgClass
MsgBox test     ' also a function

End Sub
</code>```

EDIT
Code for the function i am trying to call

```<code>Public Function classyear(class As String) As Integer

Dim yr As String

yr = Right(class, 1)
If IsNumeric(yr) Then classyear = yr Else classyear = 0

End Function
</code>```

答:
Your classyear function takes a string input, so you need to give it one. Something like:

```<code>If CInt(rgClass.Value) = classyear("Year1") Then counter = counter + 1
</code>```

Also you can neaten up your classyear function:

```<code>Public Function classyear(class As String) As Integer
    On Error Resume Next 'if error classyear will return 0
    classyear = CInt(Right(class, 1))
End Function
</code>```

Body:
I am trying to call a function within my if statement. The function is called classyear and is just after the if. I am trying to run through a timetable and see what classes belong to each year. so if it ends in a 1 it will be counted. Does anyone know how I would go about calling the function? Any help is appreciated

Public Sub time()
Dim rgTimeTable As Range, rgClass As Range, counter As Integer

Set rgTimeTable = Range("B3, N11")

For Each rgClass In rgTimeTable
If rgClass.Value = classyear Then counter = counter + 1     ' classyear is the function

Next rgClass
MsgBox test     ' also a function

End Sub

EDIT
Code for the function i am trying to call

Public Function classyear(class As String) As Integer

Dim yr As String

yr = Right(class, 1)
If IsNumeric(yr) Then classyear = yr Else classyear = 0

End Function

Body:
Your classyear function takes a string input, so you need to give it one. Something like:

If CInt(rgClass.Value) = classyear("Year1") Then counter = counter + 1

Also you can neaten up your classyear function:

Public Function classyear(class As String) As Integer
    On Error Resume Next 'if error classyear will return 0
    classyear = CInt(Right(class, 1))
End Function


问:
IDataErrorInfo reduce redundancy
A code contains some redundant data how do i remove redundancy and simplify my code without changing its functionality..

Also i wanted to know  the right way of implementing IDataErrorInfo

public string Error and public string this[string columnName] both property does the work of checking null values i dont want both to check for nulls.

答:
In general it's better to use validation attributes for that, but if speak about your concrete example - you can remove redundancy like this:</p>

```<code>public string Error
{
    get { return this[null]; }
}

public string this[string columnName]
{
    get
    {
        if (columnName == null || columnName == "UnitCode") {
            if (String.IsNullOrEmpty(UnitCode)) {
                return "Unit Code cannot be empty";
            }
        }
        if (columnName == null || columnName == "UnitName") {
            if (string.IsNullOrEmpty(UnitName)) {
                return "Unit Name cannot be Empty";
            }
        }
        return null;
    }
}
</code>```

Title: IDataErrorInfo reduce redundancy

Body:
In general it's better to use validation attributes for that, but if speak about your concrete example - you can remove redundancy like this:

public string Error
{
    get { return this[null]; }
}

public string this[string columnName]
{
    get
    {
        if (columnName == null || columnName == "UnitCode") {
            if (String.IsNullOrEmpty(UnitCode)) {
                return "Unit Code cannot be empty";
            }
        }
        if (columnName == null || columnName == "UnitName") {
            if (string.IsNullOrEmpty(UnitName)) {
                return "Unit Name cannot be Empty";
            }
        }
        return null;
    }
}


问:
how to do multiple sums in single query
let's say that I have this tables :

table num1 :

```<code>+----+-----+
| no | val |
+----+-----+
| 1  | 10  |
| 2  | 15  |
| 3  | 20  |
+----+-----+
</code>```

table num2:

```<code>+----+-----+
| no | tot |
+----+-----+
| 1  | 15  |
| 2  | 20  |
| 3  | 25  |
+----+-----+
</code>```

so, i want to select sum value of table nu1.val and table num2.tot in single query

```<code> Select sum(a.val),sum(b.tot) from num1 a, num2 b
</code>```

the query is not working
please help

答:
```<code>select max(num1) ,max(num2) from (
  select sum(val) as num1,0 from num1
  union
  select 0,sum(tot) as num2 from num2)
</code>```

Title: how to do multiple sums in single query

Body:
let's say that I have this tables :

table num1 :

+----+-----+
| no | val |
+----+-----+
| 1  | 10  |
| 2  | 15  |
| 3  | 20  |
+----+-----+

table num2:

+----+-----+
| no | tot |
+----+-----+
| 1  | 15  |
| 2  | 20  |
| 3  | 25  |
+----+-----+

so, i want to select sum value of table nu1.val and table num2.tot in single query

 Select sum(a.val),sum(b.tot) from num1 a, num2 b

the query is not working
please help


问:
android - notification tone over bluetooth
is there a way to play a tone over bluetooth?

I'm not trying to stream audio or anything fancy, I just want the headset to make a beep sound like when pressing an on screen button or getting a call.

答:
There is no current way to assign the device to play a sound. It will always play to the default output device.

If the Bluetooth headset is the default output device at that time, the MediaPlayer sounds will be heard in it.

Audio and Video

Audio and Video Playback

Media can be played from anywhere:
  from a raw resource, from a file from
  the system, or from an available
  network (URL).

You can play back the audio data only
  to the standard output device;
  currently, that is the mobile device
  speaker or Bluetooth headset. You
  cannot play sound files in the
  conversation audio.

ContentLicense: CC BY-SA 2.5


问:
Best way to check NULL for objects in Java
I have a solution to check NULL values extracted from object, However i feel there might be best approach than i am doing here. So please suggest me the best ways with code snippet :)

I will be passing my xml Content to unmarshalling method & then pass the unmarshalledValues to null check method (i.e ValidateInputFiled )

```<code>Contents unmarshalledValues = unmarshalingContent( xml );
inputCheck = ValidateInputField( unmarshalledValues );
</code>```

I have a POJO for my XML elements as mentioned below,

```<code> @XmlRootElement( name = "contents" )
    public class Contents
    {
        @XmlElement
        String A;

        @XmlElement
        String B;

        @XmlElement
        String C;

        @XmlAttribute
        String D;

       public String getA()
      {
        return A;
      }

       public String getB()
      {
        return B;
      }

       public String getC()
      {
        return C;
      }

       public String getD()
      {
        return D;
      }
}
</code>```

I have defined ValidateInputFiled as mentioned below

```<code>public Boolean ValidateInputField( Contents unmarshalledValues )
    {
        int checker = 0;
        Boolean listCheck = false;

        // Extracting unmarshalled values from xml
        String A= unmarshalledValues.getA();
        String B= unmarshalledValues.getB();
        String C = unmarshalledValues.getC();
        String D= unmarshalledValues.getD();

        if ( A== null || A.isEmpty() )
        {
            checker++;
        }

        if ( B== null || B.isEmpty() )
        {
            checker++;
        }

        if ( C== null || C.isEmpty() )
        {
            checker++;
        }

        if ( D== null || D.isEmpty() )
        {
            checker++;
        }

        if ( checker == 0 )
        {
            listCheck = true;
        }

        return listCheck;

    }
</code>```

Here i am looking to avoid NULL check for each String Values ( i.e A, B, C, D ) instead can i just do null check for Contents or for unmarshalledValues using collection or list ?

答:
Non-reflective solution for Java 8, without using a series of if's, would be to stream all fields and check for nullness:

```<code>return Stream.of(id, name).allMatch(Objects::isNull);
</code>```

This remains quite easy to maintain while avoiding the reflection hammer. This will return true for null attributes.

Body:
I have a solution to check NULL values extracted from object, However i feel there might be best approach than i am doing here. So please suggest me the best ways with code snippet :)

I will be passing my xml Content to unmarshalling method & then pass the unmarshalledValues to null check method (i.e ValidateInputFiled )

Contents unmarshalledValues = unmarshalingContent( xml );
inputCheck = ValidateInputField( unmarshalledValues );

I have a POJO for my XML elements as mentioned below,

 @XmlRootElement( name = "contents" )
    public class Contents
    {
        @XmlElement
        String A;

        @XmlElement
        String B;

        @XmlElement
        String C;

        @XmlAttribute
        String D;

       public String getA()
      {
        return A;
      }

       public String getB()
      {
        return B;
      }

       public String getC()
      {
        return C;
      }

       public String getD()
      {
        return D;
      }
}

I have defined ValidateInputFiled as mentioned below

public Boolean ValidateInputField( Contents unmarshalledValues )
    {
        int checker = 0;
        Boolean listCheck = false;

        // Extracting unmarshalled values from xml
        String A= unmarshalledValues.getA();
        String B= unmarshalledValues.getB();
        String C = unmarshalledValues.getC();
        String D= unmarshalledValues.getD();

        if ( A== null || A.isEmpty() )
        {
            checker++;
        }

        if ( B== null || B.isEmpty() )
        {
            checker++;
        }

        if ( C== null || C.isEmpty() )
        {
            checker++;
        }

        if ( D== null || D.isEmpty() )
        {
            checker++;
        }

        if ( checker == 0 )
        {
            listCheck = true;
        }

        return listCheck;

    }

Here i am looking to avoid NULL check for each String Values ( i.e A, B, C, D ) instead can i just do null check for Contents or for unmarshalledValues using collection or list ?

Body:
Non-reflective solution for Java 8, without using a series of if's, would be to stream all fields and check for nullness:

return Stream.of(id, name).allMatch(Objects::isNull);

This remains quite easy to maintain while avoiding the reflection hammer. This will return true for null attributes.


问:
Get an input from tkinter and then close the window
I have two python files, one in which i store the code inputData.py and one which is the main file, main_project.py.

In inputData i have this code:

```<code>class Prompt(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="Get", command=self.on_button)
        self.button.pack()
        self.entry.pack()

    def on_button(self):
        self.inputDt = self.entry.get()
</code>```

In main_project i have this code:

```<code>from inputData import Prompt
promptData = Prompt()
promptData.mainloop()

class Hearing(object):
    numberBirths = promptData.inputDt
</code>```

What i am trying to do is to assign the value numberBirths the value from the input in tkinter, and after i do that, i need the prompt to close and continue with the rest of the code.
Can you help me with that?

答:
You can use the .quit() and .destroy() methods:

inputData.py:

```<code>import tkinter as tk

class Prompt(tk.Tk):
    def __init__(self):
        self.answer = None
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="Get", command=self.on_button)
        self.button.pack()
        self.entry.pack()

    def on_button(self):
        self.answer = self.entry.get()
        self.quit()
</code>```

main_project.py:

```<code>from inputData import Prompt

class Hearing(object):
    def __init__(self):
        promptData = Prompt()
        promptData.mainloop()
        promptData.destroy()
        self.numberBirths = promptData.answer
        print("Births:", self.numberBirths)
        # do something else with self.numberBirths

Hearing()
</code>```

Body:
I have two python files, one in which i store the code inputData.py and one which is the main file, main_project.py.

In inputData i have this code:

class Prompt(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="Get", command=self.on_button)
        self.button.pack()
        self.entry.pack()

    def on_button(self):
        self.inputDt = self.entry.get()

In main_project i have this code:

from inputData import Prompt
promptData = Prompt()
promptData.mainloop()

class Hearing(object):
    numberBirths = promptData.inputDt

What i am trying to do is to assign the value numberBirths the value from the input in tkinter, and after i do that, i need the prompt to close and continue with the rest of the code.
Can you help me with that?

Body:
You can use the .quit() and .destroy() methods:

inputData.py:

import tkinter as tk

class Prompt(tk.Tk):
    def __init__(self):
        self.answer = None
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="Get", command=self.on_button)
        self.button.pack()
        self.entry.pack()

    def on_button(self):
        self.answer = self.entry.get()
        self.quit()

main_project.py:

from inputData import Prompt

class Hearing(object):
    def __init__(self):
        promptData = Prompt()
        promptData.mainloop()
        promptData.destroy()
        self.numberBirths = promptData.answer
        print("Births:", self.numberBirths)
        # do something else with self.numberBirths

Hearing()


问:
How to set stroke opacity attribute on InkCanvas in UWP
I tried this, without success:

```<code>  var drawingAttributes = inkCanvas.InkPresenter.CopyDefaultDrawingAttributes();
  drawingAttributes.Color =Color.FromArgb(100,0,0,0);
  inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes);
</code>```

The code above changes the color properly but the alpha channel is ignored. I do not want to use the highlighter because its opacity is fixed and one would need to resize it (it is larger than a pen size).

答:
I do not want to use the highlighter because its opacity is fixed and one would need to resize it (it is larger than a pen size).

There is the opacity attributes of class InkDrawingAttributesPencilProperties. So you could get or set the level of transparency used for rendering a pencil stroke on an InkCanvas. Please reference the following code.

```<code>InkDrawingAttributes pencilAttributes = InkDrawingAttributes.CreateForPencil();
pencilAttributes.Color = Windows.UI.Colors.Red;
pencilAttributes.Size = new Windows.Foundation.Size(3, 3);
pencilAttributes.PencilProperties.Opacity = 0.5f;

// Update InkPresenter with the pencil attributes.

inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(pencilAttributes);
</code>```

Body:
I tried this, without success:

  var drawingAttributes = inkCanvas.InkPresenter.CopyDefaultDrawingAttributes();
  drawingAttributes.Color =Color.FromArgb(100,0,0,0);
  inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes);

The code above changes the color properly but the alpha channel is ignored. I do not want to use the highlighter because its opacity is fixed and one would need to resize it (it is larger than a pen size).

Body:
I do not want to use the highlighter because its opacity is fixed and one would need to resize it (it is larger than a pen size).

There is the opacity attributes of class InkDrawingAttributesPencilProperties. So you could get or set the level of transparency used for rendering a pencil stroke on an InkCanvas. Please reference the following code.

InkDrawingAttributes pencilAttributes = InkDrawingAttributes.CreateForPencil();
pencilAttributes.Color = Windows.UI.Colors.Red;
pencilAttributes.Size = new Windows.Foundation.Size(3, 3);
pencilAttributes.PencilProperties.Opacity = 0.5f;

// Update InkPresenter with the pencil attributes.

inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(pencilAttributes);


问:
How do you pass a value to an API in Swift?
I am pretty much a beginner in Swift and I am trying to pass a value to make a call to an API with the value being from an input field.
The API is given below. How do I write code to pass value for ZIP_CODE from a text field?

https://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/ZIP_CODE/JSON

```<code>@IBOutlet var zipLabel: UILabel!
@IBOutlet var zipInput: UITextField!
@IBOutlet var jsondataLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    getJSON()
}

@IBAction func btnAction() {
    zipLabel.text = zipInput.text
}

func getJSON(){
    let url = NSURL(string :"https://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/10001/JSON")
    let request = URLRequest(url: url as! URL )
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    let task = session.dataTask(with: request){(data, response, error ) -> Void in
        if error == nil{
            DispatchQueue.main.async(execute: {
                let jsondata = JSON(data : data!)

                print(jsondata)
                print("-----")
                print(jsondata[0]["UV_INDEX"])

                let result =  jsondata[0]["UV_INDEX"].stringValue

                self.jsondataLabel.text = result
            })
        }else{
            print("There was an error")
        }
    }
    task.resume()
}
</code>```

答:
If your API gives you the response on GET Request you can use the following code -

```<code>@IBOutlet var zipLabel: UILabel!
@IBOutlet var zipInput: UITextField!
@IBOutlet var jsondataLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

}

@IBAction func btnAction() {
    zipLabel.text = zipInput.text
    getJSON(zipcode: zipInput.text)
}

func getJSON(zipcode: String){
    let url = NSURL(string :"https://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/10001/JSON&zipcode="+zipcode)
    let request = URLRequest(url: url as! URL )
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    let task = session.dataTask(with: request){(data, response, error ) -> Void in
        if error == nil{
            DispatchQueue.main.async(execute: {
                let jsondata = JSON(data : data!)

                print(jsondata)
                print("-----")
                print(jsondata[0]["UV_INDEX"])

                let result =  jsondata[0]["UV_INDEX"].stringValue

                self.jsondataLabel.text = result
            })
        }else{
            print("There was an error")
        }
    }
    task.resume()
}
</code>```

But Please note that this code won't work if your API gives you the response on POST request.

Body:
I am pretty much a beginner in Swift and I am trying to pass a value to make a call to an API with the value being from an input field.
The API is given below. How do I write code to pass value for ZIP_CODE from a text field?

https://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/ZIP_CODE/JSON

@IBOutlet var zipLabel: UILabel!
@IBOutlet var zipInput: UITextField!
@IBOutlet var jsondataLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    getJSON()
}

@IBAction func btnAction() {
    zipLabel.text = zipInput.text
}

func getJSON(){
    let url = NSURL(string :"https://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/10001/JSON")
    let request = URLRequest(url: url as! URL )
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    let task = session.dataTask(with: request){(data, response, error ) -> Void in
        if error == nil{
            DispatchQueue.main.async(execute: {
                let jsondata = JSON(data : data!)

                print(jsondata)
                print("-----")
                print(jsondata[0]["UV_INDEX"])

                let result =  jsondata[0]["UV_INDEX"].stringValue

                self.jsondataLabel.text = result
            })
        }else{
            print("There was an error")
        }
    }
    task.resume()
}

Body:
If your API gives you the response on GET Request you can use the following code -

@IBOutlet var zipLabel: UILabel!
@IBOutlet var zipInput: UITextField!
@IBOutlet var jsondataLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

}

@IBAction func btnAction() {
    zipLabel.text = zipInput.text
    getJSON(zipcode: zipInput.text)
}

func getJSON(zipcode: String){
    let url = NSURL(string :"https://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/10001/JSON&zipcode="+zipcode)
    let request = URLRequest(url: url as! URL )
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    let task = session.dataTask(with: request){(data, response, error ) -> Void in
        if error == nil{
            DispatchQueue.main.async(execute: {
                let jsondata = JSON(data : data!)

                print(jsondata)
                print("-----")
                print(jsondata[0]["UV_INDEX"])

                let result =  jsondata[0]["UV_INDEX"].stringValue

                self.jsondataLabel.text = result
            })
        }else{
            print("There was an error")
        }
    }
    task.resume()
}

But Please note that this code won't work if your API gives you the response on POST request.


问:
When is it ever appropriate to place Javascript inside the body of a document?
The client has a bunch of Javascript that calls Microsoft Ajax etc. Aside from web page analytics which make sense to load at the same time static resources are loaded, wouldn't it make sense to load any AJAX scripts in the head instead of the body?

Ultimately the result is a bloated load time for the page since all the Javascript is being loaded at time of render.

What is your ideal placement of certain Javascript in a web page?

答: Best practice is to put your scripts at the bottom of the document. Yahoo covers it on their Best Practices.</p>


问:
C# Json to custom class
I have json:

```<code>[
     {
        "Name" : "SHA of timestamp",
        "ProjectURL" : "URL to Proj",
        "AccountIdentifier" : "Account Identifier",
        "Repositories":
        {
            "GitLink1":
            {
                "Login" : "login1",
                "Password"  : "pas1"
            },
            "GitLink2":
            {
                "Login" : "login2",
                "Password"  : "pas2"
            },

            ...

            "GitLink999":
            {
                "Login" : "login999",
                "Password" : "pass999"
            }
        }
    },

    ...

    {
        Same entry
    }
]
</code>```

I need to fill it in IEnumerable of my created classes

```<code>public class Git
{
    public string Login { get; set; }
    public string Password { get; set; }
}

public class Repositories
{
    public Git git { get; set; }
}

public class ConfigEntry
{
    public string Name { get; set; }
    public string ProjectURL { get; set; }
    public string AccountIdentifier { get; set; }
    public Repositories Repositories { get; set; }
}
</code>```

Using

```<code>IEnumerable<ConfigurationEntry> config = JsonConvert.DeserializeObject<IEnumerable<ConfigurationEntry>>(CONFIGJSON);
</code>```

Where CONFIGJSON contains frst json file.

Gives me this data of ConfigEntry class :

Name : "filled with some data"

ProjectURL : same

AccountIdentifier : same

Repositories : NULL

How i can fill Repositories field with all data i have in config JSON?

Is there any ideas.

答:
It looks like you probably shouldn't have a Repositories class - instead, change your ConfigEntry.Repositories property to:

```<code>public Dictionary<string, Git> Repositories { get; set; }
</code>```

Then you'll get a dictionary where the key of "GetLink1" has a value with Login of "login1" etc.

ContentLicense: CC BY-SA 4.0

Title: C# Json to custom class

Body:
I have json:

[
     {
        "Name" : "SHA of timestamp",
        "ProjectURL" : "URL to Proj",
        "AccountIdentifier" : "Account Identifier",
        "Repositories":
        {
            "GitLink1":
            {
                "Login" : "login1",
                "Password"  : "pas1"
            },
            "GitLink2":
            {
                "Login" : "login2",
                "Password"  : "pas2"
            },

            ...

            "GitLink999":
            {
                "Login" : "login999",
                "Password" : "pass999"
            }
        }
    },

    ...

    {
        Same entry
    }
]

I need to fill it in IEnumerable of my created classes

public class Git
{
    public string Login { get; set; }
    public string Password { get; set; }
}

public class Repositories
{
    public Git git { get; set; }
}

public class ConfigEntry
{
    public string Name { get; set; }
    public string ProjectURL { get; set; }
    public string AccountIdentifier { get; set; }
    public Repositories Repositories { get; set; }
}

Using

IEnumerable<ConfigurationEntry> config = JsonConvert.DeserializeObject<IEnumerable<ConfigurationEntry>>(CONFIGJSON);

Where CONFIGJSON contains frst json file.

Gives me this data of ConfigEntry class :

Name : "filled with some data"

ProjectURL : same

AccountIdentifier : same

Repositories : NULL

How i can fill Repositories field with all data i have in config JSON?

Is there any ideas.

Body:
It looks like you probably shouldn't have a Repositories class - instead, change your ConfigEntry.Repositories property to:

public Dictionary<string, Git> Repositories { get; set; }

Then you'll get a dictionary where the key of "GetLink1" has a value with Login of "login1" etc.


问:
How can I add a *.hx file support in opengrok?
I have a legacy C project which is using *.hx as a customized header file suffix. I'm trying to using opengrok to read the code. But it doesn't support this file extension.

I tried to modify the SUFFIX in
OpenGrok-0.12-stable\src\org\opensolaris\opengrok\analysis\c\CAnalyzerFactory.java

and compile to get the opengrok.jar
but it doesn't help.

答: Check the CLI options to opengrok.jar, especially the -A option.


问:
Country state concept in codeigniter
This is My View Page

```<code> <select name="category" value="c_id" onChange="getsubcategorydetails(this.value)" style="display:">
                                                   <option value="" selected="selected" >Select Categories</option>
            <?php if(isset($categories)) : foreach($categories as $row) :?>
                <option value=<?php echo $row->c_id; ?>><?php echo $row->c_name; ?></option>
                <?php endforeach;?>
                <?php else :
                endif;
                ?>
          </select>
                 </div>
               </div>
                 </div>
                </div>
                                <div class="row">
                                   <div class="input-field col s12">
                                   <tr>

                                            <td>

    <select name=" select id="subcategory">
 <option value="" selected="selected" >Select Sub Category</option>
 <?php foreach($sub_categories as $stt): ?>
  <option value="<?php echo $stt->s_c_id; ?>"><?php echo $stt->s_c_name; ?></option>
 <?php endforeach; ?>
 </select>
                                                </select></td>
                                                </tr>
</code>```

This is My Controller

```<code>    public function getsubcategorydetails($c_id)
    {

      $c_id = $this->uri->segment(3);
      //  echo  $c_id;
        $data['sub_categories'] = $this->m_category->getsubcategorydetails($c_id);
        //print_r($data['sub_category']);
       $this->load->view('my_admin/newpost_1',$data);
    }
</code>```

This is My Model

```<code>    function getsubcategorydetails($c_id='')
 {
    $this -> db -> select('*');
    $this -> db -> where('c_id', $c_id);
    $query = $this -> db -> get('subcategories');
    return $query->result();
 }
</code>```

When i Click Category Select Box The Values returned from Controller ... But It Not Displayed On View ... What's Wrong With That .... Thanks In Advance

答:
I suggest you to use JQuery AJAX to fetch the subcategory details.

Currently you are following wrong coding methods like calling a codeigniter controller function on an "OnChange" event with getsubcategorydetails($c_id) which is not right and makes it a wrong practice. OnChange event is used to call only Javascript functions.

To manipulate DOM, use Javascript/JQuery for it. Use the controller as a relay for getting appropriate formatted data into your JQuery.

Title: Country state concept in codeigniter

Body:
This is My View Page

 <select name="category" value="c_id" onChange="getsubcategorydetails(this.value)" style="display:">
                                                   <option value="" selected="selected" >Select Categories</option>
            <?php if(isset($categories)) : foreach($categories as $row) :?>
                <option value=<?php echo $row->c_id; ?>><?php echo $row->c_name; ?></option>
                <?php endforeach;?>
                <?php else :
                endif;
                ?>
          </select>

    <select name=" select id="subcategory">
 <option value="" selected="selected" >Select Sub Category</option>
 <?php foreach($sub_categories as $stt): ?>
  <option value="<?php echo $stt->s_c_id; ?>"><?php echo $stt->s_c_name; ?></option>
 <?php endforeach; ?>
 </select>
                                                </select>

This is My Controller

    public function getsubcategorydetails($c_id)
    {

      $c_id = $this->uri->segment(3);
      //  echo  $c_id;
        $data['sub_categories'] = $this->m_category->getsubcategorydetails($c_id);
        //print_r($data['sub_category']);
       $this->load->view('my_admin/newpost_1',$data);
    }

This is My Model

    function getsubcategorydetails($c_id='')
 {
    $this -> db -> select('*');
    $this -> db -> where('c_id', $c_id);
    $query = $this -> db -> get('subcategories');
    return $query->result();
 }

When i Click Category Select Box The Values returned from Controller ... But It Not Displayed On View ... What's Wrong With That .... Thanks In Advance


问:
amazon EMR hive execution error
I am trying to run a simple hive job using amazon EMR console. Every time I get an error stating "Error missing argument base-path" and the hive job fails. Can any one suggest me how to resolve it.

I have inserted the input file into the s3://bucket/inputs location, the script in s3:// bucket / script, and my hive query is as follows:

```<code>create external table table_name(
 string var 1,
 string var 2....)
Row format delimited
fields terminated by '/t'
location 's3://bucket/outputs'
load data inpath 's3://bucket/inputs/data.txt' into table table_name )
</code>```

In the amazon EMR job flow I have followed all the instructions provided by the amazon documentation. I am a beginner in this field. Is there any need to pass any argument in the arguments lists section in the hive job creation.

Thanks in advance

答:
The ASF docs explicitly state that on EMR, you must use s3, not any of the others.  Amazon ship with their own S3 client libraries. If Hive requires S3n, it means something is wrong with its classpath, and it isn't picking up the AWS proprietary client —which is not only confusing, potentially trouble.

For the curious, here is the history of Hadoop S3 support

Title: amazon EMR hive execution error

Body:
I am trying to run a simple hive job using amazon EMR console. Every time I get an error stating "Error missing argument base-path" and the hive job fails. Can any one suggest me how to resolve it.

I have inserted the input file into the s3://bucket/inputs location, the script in s3:// bucket / script, and my hive query is as follows:

create external table table_name(
 string var 1,
 string var 2....)
Row format delimited
fields terminated by '/t'
location 's3://bucket/outputs'
load data inpath 's3://bucket/inputs/data.txt' into table table_name )

In the amazon EMR job flow I have followed all the instructions provided by the amazon documentation. I am a beginner in this field. Is there any need to pass any argument in the arguments lists section in the hive job creation.

Thanks in advance


问:
Why does is_array() return false?
I have this SimpleXML object:

```<code>object(SimpleXMLElement)#176 (1) {
 ["record"]=>
 array(2) {
  [0]=>
  object(SimpleXMLElement)#39 (2) {
     ["f"]=>
     array(2) {
       [0]=>
       string(13) "stuff"
       [1]=>
       string(1) "1"
     }
  }
  [1]=>
  object(SimpleXMLElement)#37 (2) {
    ["f"]=>
    array(2) {
      [0]=>
      string(13) "more stuff"
      [1]=>
      string(3) "90"
    }
  }
}
</code>```

Why does is_array($object->record) return false? It clearly says it's an array. Why can't I detect it using is_array?

Also, I am unable to cast it as an array using (array) $object->record. I get this error:

Warning:  It is not yet possible to
  assign complex types to properties

答: SimpleXML nodes are objects that can contain other SimpleXML nodes. Use iterator_to_array().

Title: Why does is_array() return false?

Body:
I have this SimpleXML object:

object(SimpleXMLElement)#176 (1) {
 ["record"]=>
 array(2) {
  [0]=>
  object(SimpleXMLElement)#39 (2) {
     ["f"]=>
     array(2) {
       [0]=>
       string(13) "stuff"
       [1]=>
       string(1) "1"
     }
  }
  [1]=>
  object(SimpleXMLElement)#37 (2) {
    ["f"]=>
    array(2) {
      [0]=>
      string(13) "more stuff"
      [1]=>
      string(3) "90"
    }
  }
}

Why does is_array($object->record) return false? It clearly says it's an array. Why can't I detect it using is_array?

Also, I am unable to cast it as an array using (array) $object->record. I get this error:

Warning:  It is not yet possible to
  assign complex types to properties