问:
Not able to perform segue
hi the session block works fine but when I am trying to move to next Viewcontroller I get thread1:Signal SIGABRT ..Actually I am trying to get request from server and use the reply to perform the following codes

```<code>    - (IBAction)submitb:(id)sender{
    if(_otptf.text==self.otpStr && _otptf.text>0){
    NSString *post = [NSString stringWithFormat:@"phone=%@",self.stri1];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    //Next up, we read the postData's length, so we can pass it along in the request.
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    // Now that we have what we'd like to post, we can create an NSMutableURLRequest, and include our postData
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://test.kre8tives.com/barebon/customer_checkapi.php"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];
    NSLog(@"the data Details is %@", post);
          //   And finally, we can send our request, and read the reply by creating a new NSURLSession:
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    static NSURLSession* sharedSessionMainQueue = nil;
    if(!sharedSessionMainQueue){
        sharedSessionMainQueue = [NSURLSession sessionWithConfiguration:nil delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
    }

    [[sharedSessionMainQueue dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
    //  NSError *error;
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // you need to convert to dictionary object
        NSLog(@"Req cust:%@",requestReply);
        NSLog(@"requestReply cust: %@", jsonDict);
        self.tmpv1=[jsonDict valueForKey:@"success"] ;
        self.strv1=self.tmpv1;
        NSLog(@"tmp storage inside block:%@",self.tmpv1);
        if (!error) {
            if([self.tmpv1 isEqualToString:@"%@"],"0"){
                          [self performSegueWithIdentifier:@"x2" sender:self];
                //[self performSegueWithIdentifier:@"x2" sender:self];
                }
            if([self.tmpv1 isEqualToString:@"%@"],"1"){
                    [self performSegueWithIdentifier:@"b2" sender:self];
                }
        }
    }] resume];
   // [self navi];

}
else{
/* what ever */
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Inputs Found or Incorrect Otp!!"
                                                message:@"Please check your input!!."
                                               delegate:self
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles:nil];
[alert show];
    }
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable      id)sender{
    if ([[segue identifier] isEqualToString:@"x2"])
   {
    ProfileViewController *loadCtr = (ProfileViewController *)segue.destinationViewController;
    //loadCtr.mobilestrp = self.stri1;
}

else if ([[segue identifier] isEqualToString:@"b2"])
{

}

}
</code>```

this is my log

```<code>2017-06-05 12:14:32.884 MenuBar[1496:103465] the data Details is phone=9047038606
2017-06-05 12:14:33.726 MenuBar[1496:103531] requestReply: {
    otp = 828712;
    success = 1;
}
2017-06-05 12:14:33.727 MenuBar[1496:103531] tmp storage inside block:828712
2017-06-05 12:14:33.728 MenuBar[1496:103531]  storage:828712
2017-06-05 12:14:33.729 MenuBar[1496:103531] tmp storage:828712
2017-06-05 12:14:33.738 MenuBar[1496:103465] 9047038606
2017-06-05 12:14:45.069 MenuBar[1496:103465] the data Details is phone=9047038606
2017-06-05 12:14:49.919 MenuBar[1496:103465] Req cust:{"success":0}
2017-06-05 12:14:52.373 MenuBar[1496:103465] requestReply cust: {
    success = 0;
}
2017-06-05 12:14:52.715 MenuBar[1496:103465] tmp storage inside block:0
2017-06-05 12:28:08.486 MenuBar[1520:108818] -[WelcomeViewController setCustid:]: unrecognized selector sent to instance 0x7ff98f908790
2017-06-05 12:28:08.491 MenuBar[1520:108818] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-   [WelcomeViewController setCustid:]: unrecognized selector sent to instance   0x7ff98f908790'
    *** First throw call stack:
   (
    0   CoreFoundation                      0x000000010ba31b0b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010b126141 objc_exception_throw + 48
    2   CoreFoundation
</code>```

thanks in advance for the suggestions!!

答: Check your IBActions and variables in profileViewController whether it has link to your file or not. That is your reference outlet.

Title: Not able to perform segue

Body:
hi the session block works fine but when I am trying to move to next Viewcontroller I get thread1:Signal SIGABRT ..Actually I am trying to get request from server and use the reply to perform the following codes

    - (IBAction)submitb:(id)sender{
    if(_otptf.text==self.otpStr && _otptf.text>0){
    NSString *post = [NSString stringWithFormat:@"phone=%@",self.stri1];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    //Next up, we read the postData's length, so we can pass it along in the request.
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    // Now that we have what we'd like to post, we can create an NSMutableURLRequest, and include our postData
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://test.kre8tives.com/barebon/customer_checkapi.php"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];
    NSLog(@"the data Details is %@", post);
          //   And finally, we can send our request, and read the reply by creating a new NSURLSession:
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    static NSURLSession* sharedSessionMainQueue = nil;
    if(!sharedSessionMainQueue){
        sharedSessionMainQueue = [NSURLSession sessionWithConfiguration:nil delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
    }

    [[sharedSessionMainQueue dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
    //  NSError *error;
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // you need to convert to dictionary object
        NSLog(@"Req cust:%@",requestReply);
        NSLog(@"requestReply cust: %@", jsonDict);
        self.tmpv1=[jsonDict valueForKey:@"success"] ;
        self.strv1=self.tmpv1;
        NSLog(@"tmp storage inside block:%@",self.tmpv1);
        if (!error) {
            if([self.tmpv1 isEqualToString:@"%@"],"0"){
                          [self performSegueWithIdentifier:@"x2" sender:self];
                //[self performSegueWithIdentifier:@"x2" sender:self];
                }
            if([self.tmpv1 isEqualToString:@"%@"],"1"){
                    [self performSegueWithIdentifier:@"b2" sender:self];
                }
        }
    }] resume];
   // [self navi];

}
else{
/* what ever */
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Inputs Found or Incorrect Otp!!"
                                                message:@"Please check your input!!."
                                               delegate:self
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles:nil];
[alert show];
    }
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable      id)sender{
    if ([[segue identifier] isEqualToString:@"x2"])
   {
    ProfileViewController *loadCtr = (ProfileViewController *)segue.destinationViewController;
    //loadCtr.mobilestrp = self.stri1;
}

else if ([[segue identifier] isEqualToString:@"b2"])
{

}

}

this is my log

2017-06-05 12:14:32.884 MenuBar[1496:103465] the data Details is phone=9047038606
2017-06-05 12:14:33.726 MenuBar[1496:103531] requestReply: {
    otp = 828712;
    success = 1;
}
2017-06-05 12:14:33.727 MenuBar[1496:103531] tmp storage inside block:828712
2017-06-05 12:14:33.728 MenuBar[1496:103531]  storage:828712
2017-06-05 12:14:33.729 MenuBar[1496:103531] tmp storage:828712
2017-06-05 12:14:33.738 MenuBar[1496:103465] 9047038606
2017-06-05 12:14:45.069 MenuBar[1496:103465] the data Details is phone=9047038606
2017-06-05 12:14:49.919 MenuBar[1496:103465] Req cust:{"success":0}
2017-06-05 12:14:52.373 MenuBar[1496:103465] requestReply cust: {
    success = 0;
}
2017-06-05 12:14:52.715 MenuBar[1496:103465] tmp storage inside block:0
2017-06-05 12:28:08.486 MenuBar[1520:108818] -[WelcomeViewController setCustid:]: unrecognized selector sent to instance 0x7ff98f908790
2017-06-05 12:28:08.491 MenuBar[1520:108818] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-   [WelcomeViewController setCustid:]: unrecognized selector sent to instance   0x7ff98f908790'
    *** First throw call stack:
   (
    0   CoreFoundation                      0x000000010ba31b0b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010b126141 objc_exception_throw + 48
    2   CoreFoundation

thanks in advance for the suggestions!!


来源: stackexchange

问:
How to get List<String> from JSON list using Retrofit 2?
I am new to Android. I need to get a list of strings from a JSON list. It will be added to a Spinner list. I have the list on server like

```<code>[{"bgroup":"A+"},{"bgroup":"A1+"},{"bgroup":"A1-"}].
</code>```

tried with Retrofit Scalars.
Response  as

```<code>[{"bgroup":"A+"},{"bgroup":"A1+"},{"bgroup":"A1-"}]
</code>```

but error detecting as:

Expected a string but was BEGIN_OBJECT at line 1 column 3 path $[0]*

Any better way to retrieve the list of strings from the JSON?

答:
Make the following model class (parcelable)

```<code>package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example implements Parcelable {

@SerializedName("bgroup")
@Expose
private String bgroup;

public String getBgroup() {
return bgroup;
}

public void setBgroup(String bgroup) {
this.bgroup = bgroup;
}

    protected Example(Parcel in) {
        bgroup = in.readString();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(bgroup);
    }

    @SuppressWarnings("unused")
    public static final Parcelable.Creator<Example> CREATOR = new Parcelable.Creator<Example>() {
        @Override
        public Example createFromParcel(Parcel in) {
            return new Example(in);
        }

        @Override
        public Example[] newArray(int size) {
            return new Example[size];
        }
    };
}
</code>```

Than create interface class like this

```<code>public interface ApiService {

@GET("<URL>")
Call<List<Example>> getBloodGroups();
}
</code>```

And finally call retrofit like following :

```<code>Call<List<Example>> call = new RestClient(this).getApiService()
                .getBloodGroups();
        call.enqueue(new Callback<List<Example>>() {
            @Override
            public void onResponse(Call<List<Example>> call, Response<List<Example>> response) {

            }

            @Override
            public void onFailure(Call<List<Example>> call, Throwable throwable) {

            }
        });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new to Android. I need to get a list of strings from a JSON list. It will be added to a Spinner list. I have the list on server like

[{"bgroup":"A+"},{"bgroup":"A1+"},{"bgroup":"A1-"}].

tried with Retrofit Scalars.
Response  as

[{"bgroup":"A+"},{"bgroup":"A1+"},{"bgroup":"A1-"}]

but error detecting as:

Expected a string but was BEGIN_OBJECT at line 1 column 3 path $[0]*

Any better way to retrieve the list of strings from the JSON?

Body:
Make the following model class (parcelable)

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example implements Parcelable {

@SerializedName("bgroup")
@Expose
private String bgroup;

public String getBgroup() {
return bgroup;
}

public void setBgroup(String bgroup) {
this.bgroup = bgroup;
}

    protected Example(Parcel in) {
        bgroup = in.readString();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(bgroup);
    }

    @SuppressWarnings("unused")
    public static final Parcelable.Creator<Example> CREATOR = new Parcelable.Creator<Example>() {
        @Override
        public Example createFromParcel(Parcel in) {
            return new Example(in);
        }

        @Override
        public Example[] newArray(int size) {
            return new Example[size];
        }
    };
}

Than create interface class like this

public interface ApiService {

@GET("<URL>")
Call<List<Example>> getBloodGroups();
}

And finally call retrofit like following :

Call<List<Example>> call = new RestClient(this).getApiService()
                .getBloodGroups();
        call.enqueue(new Callback<List<Example>>() {
            @Override
            public void onResponse(Call<List<Example>> call, Response<List<Example>> response) {

            }

            @Override
            public void onFailure(Call<List<Example>> call, Throwable throwable) {

            }
        });


问:
How to aggregate several columns into a JSON file for each group in HIVE
I want to convert the following table into a new table with two rows. In the new table, each user_id has one JSON file to summarize all other columns in the first table.

user_id reservation_id  nights  price
AAA     10001             1     100
AAA     10002             1     120
BBB     20003             7     350

to

user_id    reservation_details
AAA        {10001:{'nights':1, 'price':100}, 10002:{'nights':1, 'price':120}}
BBB        {20003:{'nights':7, 'price':350}}

Body:
select      user_id
           ,concat("{",concat_ws(',',collect_list(concat(string(reservation_id),":{'nights':",string(nights),",'price':",string(price),"}"))),"}")  as reservation_details

from        mytable

group by    user_id

+---------+-----------------------------------------------------------------+
| user_id |                       reservation_details                       |
+---------+-----------------------------------------------------------------+
| AAA     | {10001:{'nights':1,'price':100},10002:{'nights':1,'price':120}} |
| BBB     | {20003:{'nights':7,'price':350}}                                |
+---------+-----------------------------------------------------------------+


问:
How to read huge CSV file with 29 million rows of data using .net
I have a huge .csv file, to be specific a .TAB file with 29 million rows and the file size is around 600 MB. I would need to read this into an IEnumerable collection.

I have tried CsvHelper, GenericParser, and few other solutions but always ending up with an Out of Memory exception

Please suggest a way to do this

I have tried

```<code>var deliveryPoints = new List<Point>();

using (TextReader csvreader1 = File.OpenText(@"C:\testfile\Prod\PCDP1705.TAB")) //StreamReader csvreader1 = new StreamReader(@"C:\testfile\Prod\PCDP1705.TAB"))
using (var csvR1 = new CsvReader(csvreader1, csvconfig))
{
     csvR1.Configuration.RegisterClassMap<DeliveryMap>();
     deliveryPoints = csvR1.GetRecords<Point>().ToList();
}

using (GenericParser parser = new GenericParser())
{
     parser.SetDataSource(@"C:\testfile\Prod\PCDP1705.TAB");

     parser.ColumnDelimiter = '\t';
     parser.FirstRowHasHeader = false;
     //parser.SkipStartingDataRows = 10;
     //parser.MaxBufferSize = 4096;
     //parser.MaxRows = 500;
     parser.TextQualifier = '\"';

     while (parser.Read())
     {
         var address = new Point();
         address.PostCodeID = int.Parse(parser[0]);
         address.DPS = parser[1];
         address.OrganisationFlag = parser[2];
         deliveryPoints.Add(address);
     }
}
</code>```

and

```<code>var deliveryPoints = new List<Point>();
csvreader = new StreamReader(@"C:\testfile\Prod\PCDP1705.TAB");
csv = new CsvReader(csvreader, csvconfig);

while (csv.Read())
{
     var address = new Point();
     address.PostCodeID = int.Parse(csv.GetField(0));
     address.DPS = csv.GetField(1);
     deliveryPoints.Add(address);
}
</code>```

答:
No need to use 3rd party software.  Use Net Library methods</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader csvreader = new StreamReader(@"C:\testfile\Prod\PCDP1705.TAB");
            string inputLine = "";
            while ((inputLine = csvreader.ReadLine()) != null)
            {
                var address = new Point();
                string[] csvArray = inputLine.Split(new char[] { ',' });
                address.postCodeID = int.Parse(csvArray[0]);
                address.DPS = csvArray[1];
                Point.deliveryPoints.Add(address);
            }

            //add data to datatable
            DataTable dt = new DataTable();
            dt.Columns.Add("Post Code", typeof(int));
            dt.Columns.Add("DPS", typeof(string));

            foreach (Point point in Point.deliveryPoints)
            {
                dt.Rows.Add(new object[] { point.postCodeID, point.DPS });
            }

        }
    }
    public class Point
    {
        public static List<Point> deliveryPoints = new List<Point>();
        public int postCodeID { get; set; }
        public string DPS { get; set; }

    }
}
</code>```

Body:
I have a huge .csv file, to be specific a .TAB file with 29 million rows and the file size is around 600 MB. I would need to read this into an IEnumerable collection.

I have tried CsvHelper, GenericParser, and few other solutions but always ending up with an Out of Memory exception

Please suggest a way to do this

I have tried

var deliveryPoints = new List<Point>();

using (TextReader csvreader1 = File.OpenText(@"C:\testfile\Prod\PCDP1705.TAB")) //StreamReader csvreader1 = new StreamReader(@"C:\testfile\Prod\PCDP1705.TAB"))
using (var csvR1 = new CsvReader(csvreader1, csvconfig))
{
     csvR1.Configuration.RegisterClassMap<DeliveryMap>();
     deliveryPoints = csvR1.GetRecords<Point>().ToList();
}

using (GenericParser parser = new GenericParser())
{
     parser.SetDataSource(@"C:\testfile\Prod\PCDP1705.TAB");

     parser.ColumnDelimiter = '\t';
     parser.FirstRowHasHeader = false;
     //parser.SkipStartingDataRows = 10;
     //parser.MaxBufferSize = 4096;
     //parser.MaxRows = 500;
     parser.TextQualifier = '\"';

     while (parser.Read())
     {
         var address = new Point();
         address.PostCodeID = int.Parse(parser[0]);
         address.DPS = parser[1];
         address.OrganisationFlag = parser[2];
         deliveryPoints.Add(address);
     }
}

and

var deliveryPoints = new List<Point>();
csvreader = new StreamReader(@"C:\testfile\Prod\PCDP1705.TAB");
csv = new CsvReader(csvreader, csvconfig);

while (csv.Read())
{
     var address = new Point();
     address.PostCodeID = int.Parse(csv.GetField(0));
     address.DPS = csv.GetField(1);
     deliveryPoints.Add(address);
}

Body:
No need to use 3rd party software.  Use Net Library methods

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader csvreader = new StreamReader(@"C:\testfile\Prod\PCDP1705.TAB");
            string inputLine = "";
            while ((inputLine = csvreader.ReadLine()) != null)
            {
                var address = new Point();
                string[] csvArray = inputLine.Split(new char[] { ',' });
                address.postCodeID = int.Parse(csvArray[0]);
                address.DPS = csvArray[1];
                Point.deliveryPoints.Add(address);
            }

            //add data to datatable
            DataTable dt = new DataTable();
            dt.Columns.Add("Post Code", typeof(int));
            dt.Columns.Add("DPS", typeof(string));

            foreach (Point point in Point.deliveryPoints)
            {
                dt.Rows.Add(new object[] { point.postCodeID, point.DPS });
            }

        }
    }
    public class Point
    {
        public static List<Point> deliveryPoints = new List<Point>();
        public int postCodeID { get; set; }
        public string DPS { get; set; }

    }
}


问:
Run multiple UI Threads
Skip to the bottom for the question; this is just some extra info

I am using a component (GeckoFX) to render some websites, well fine, yet it can only be used in a Windows Form; as it has to bind to a WinForms object that can be drawn. Because all the WinForms are running in the same thread, I can only use one GeckoFX instance at a time; so I decided to create a 'worker class' in the form of a WinForm, and add all the logic in there. The form doesn't require to communicate with the main form.

Now I can fire up 10 windows, and they will eventually work, but every new form will wait before all the other forms have handled all their GeckoFX events, as you cannot use multiple instances on one thread. Furthermore, the browser has to be on a UIThread. So:

Is it possible to create multiple UI Threads (one for each form)?

I have seen someone doing it ([edit: removed 'bad' link]), yet no one ever got his code samples working. The guy who got it working originally used some form of custom message pumping to do this kind of things, but I have no clue how to achieve something like that.

答:
GeckoFx doesn't require a form.</p>

```<code>GeckoWebBrowser wb = new GeckoWebBrowser();
wb.CreateControl(); //<-- the magic lays here!
wb.DocumentCompleted += delegate{ MessageBox.Show(wb.DocumentTitle); };
wb.Navigate("http://mysite.com");
</code>```

ContentLicense: CC BY-SA 4.0

Title: Run multiple UI Threads

Body:
GeckoFx doesn't require a form.

GeckoWebBrowser wb = new GeckoWebBrowser();
wb.CreateControl(); //<-- the magic lays here!
wb.DocumentCompleted += delegate{ MessageBox.Show(wb.DocumentTitle); };
wb.Navigate("http://mysite.com");

ContentLicense: CC BY-SA 2.5


问:
How to use values of generator objects?
I have a Nx6 for the dataset, where N is the number of samples.

And when I run this line of code:

```<code>segments, labels = segment_signal(dataset)
</code>```

It gives the error:

TypeError: cannot do slice indexing on <class 'pandas.core.indexes.range.RangeIndex'> with these indexers [45.0] of <class 'float'>

The definition of the function segment signal is the following:

```<code>def segment_signal(data,window_size = 90):
    segments = np.empty((0,window_size,3))
    labels = np.empty((0))
    for (start, end) in windows(data['timestamp'], window_size):
        x = data["x-axis"][start:end]
        y = data["y-axis"][start:end]
        z = data["z-axis"][start:end]
        if(len(dataset['timestamp'][start:end]) == window_size):
            segments = np.vstack([segments,np.dstack([x,y,z])])
            labels = np.append(labels,stats.mode(data["activity"][start:end])[0][0])
    return segments, labels
</code>```

And the helper function:

```<code>def windows(data, size):
    start = 0
    while start < data.count():
        yield start, start + size
        start += (size / 2)
</code>```

I troubleshooted it and it appears that this line is causing the error:

x = dataset["x-axis"][start:end]

I analyzed it further and it seems that windows() is a generator function. Hence, the (start, end) in segment_signal are generator objects. But error occurs in the x = dataset["x-axis"][start:end] for some reason that I could not understand.

The problem is that I can print the values of start and end, but I can't use their values. Say, use them as index for the x.

Turns iut that start and end are floats.

I just did int(start) and int(end). But when I did x = dataset["x-axis"][start:end] and get the shape x.shape, the answer is (24,), when it should be 90 (because the window size is 90. But when I computed end - start the answer is still 90. And when I printed x, it only has 26 elements when it should have been 90. Why is this?

答:
I think JAV is right about the variables' type. Try this simple (not sure if it's the best) solution

```<code>for (start, end) in windows(data['timestamp'], window_size):
    start = int(start)
    end = int(end)
    print("check start and end",start,end)
</code>```

I hope this helps

Title: How to use values of generator objects?

Body:
I have a Nx6 for the dataset, where N is the number of samples.

And when I run this line of code:

segments, labels = segment_signal(dataset)

It gives the error:

TypeError: cannot do slice indexing on <class 'pandas.core.indexes.range.RangeIndex'> with these indexers [45.0] of <class 'float'>

The definition of the function segment signal is the following:

def segment_signal(data,window_size = 90):
    segments = np.empty((0,window_size,3))
    labels = np.empty((0))
    for (start, end) in windows(data['timestamp'], window_size):
        x = data["x-axis"][start:end]
        y = data["y-axis"][start:end]
        z = data["z-axis"][start:end]
        if(len(dataset['timestamp'][start:end]) == window_size):
            segments = np.vstack([segments,np.dstack([x,y,z])])
            labels = np.append(labels,stats.mode(data["activity"][start:end])[0][0])
    return segments, labels

And the helper function:

def windows(data, size):
    start = 0
    while start < data.count():
        yield start, start + size
        start += (size / 2)

I troubleshooted it and it appears that this line is causing the error:

x = dataset["x-axis"][start:end]

I analyzed it further and it seems that windows() is a generator function. Hence, the (start, end) in segment_signal are generator objects. But error occurs in the x = dataset["x-axis"][start:end] for some reason that I could not understand.

The problem is that I can print the values of start and end, but I can't use their values. Say, use them as index for the x.

Turns iut that start and end are floats.

I just did int(start) and int(end). But when I did x = dataset["x-axis"][start:end] and get the shape x.shape, the answer is (24,), when it should be 90 (because the window size is 90. But when I computed end - start the answer is still 90. And when I printed x, it only has 26 elements when it should have been 90. Why is this?

Body:
I think JAV is right about the variables' type. Try this simple (not sure if it's the best) solution

for (start, end) in windows(data['timestamp'], window_size):
    start = int(start)
    end = int(end)
    print("check start and end",start,end)

I hope this helps


问:
Union 3 tables with specific column
I have 3 tables and I want to union all but only two columns are able to show data.

```<code>SELECT Vehicle_ID, Total_Weight, date, bilty_No FROM harvesting
UNION
SELECT Vehicle_ID, Total_Weight, date, Bilty_No FROM Blade_Harvesting
</code>```

I want to add another table like below but its giving error

```<code>SELECT Vehicle_ID, Total_Weight, date, bilty_No FROM harvesting
UNION
SELECT Vehicle_ID, Total_Weight, date, Bilty_No FROM Blade_Harvesting
UNION
SELECT Vehicle_ID, Vehicle_Name FROM Vehicle
</code>```

It's giving this error:

All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists

答:
Please user :

SELECT Vehicle_ID, Total_Weight,     date,   Bilty_No, '' AS Vehicle_Name   FROM harvesting

UNION
SELECT Vehicle_ID, Total_Weight,      date,  Bilty_No, '' AS Vehicle_Name  FROM Blade_Harvesting

UNION
SELECT Vehicle_ID, '0' AS Total_Weight, NULL AS date, '0' AS Bilty_No,  Vehicle_Name FROM Vehicle

Title: Union 3 tables with specific column

Body:
I have 3 tables and I want to union all but only two columns are able to show data.

SELECT Vehicle_ID, Total_Weight, date, bilty_No FROM harvesting
UNION
SELECT Vehicle_ID, Total_Weight, date, Bilty_No FROM Blade_Harvesting

I want to add another table like below but its giving error

SELECT Vehicle_ID, Total_Weight, date, bilty_No FROM harvesting
UNION
SELECT Vehicle_ID, Total_Weight, date, Bilty_No FROM Blade_Harvesting
UNION
SELECT Vehicle_ID, Vehicle_Name FROM Vehicle

It's giving this error:

All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists


问:
iOS - Iteration in some folders
I need to get some files in definite folders. For this purpose I use this answer and it works fine. However, my folder structure is like:

```<code>Documents/
  idOfFolder1/
    images/
      image1.jpg
      image2.png
    sounds/
      sound1.mp3
    files/
      file1.pdf
  idOfFolder2/
    images/
      ...
</code>```

I need to iterate through all folders having a specific id and get images. Since the answer written iterates through all folders it takes much more time than normal (we have many files). To optimize process, I want to skip "sounds" and "files" folders. Is there a way to handle this?

Thank you!

答:
I think you can implement it in a such different way using a NSPredicate onto the NSDirectoryEnumerator array as in this answer Iterating through files in nested folders or Filter NSFileManager with NSPredicate but the syntax can be awkward: take a look at NSPredicate syntax documentation NSPredicate Format String

In your case I would either:
1. use fast enumeration with a for loop
2. if possible redesign the folder structures
3. use core data or another caching system to speed up the loading process (this involves to sync time to time with the real files)

Title: iOS - Iteration in some folders

Body:
I need to get some files in definite folders. For this purpose I use this answer and it works fine. However, my folder structure is like:

Documents/
  idOfFolder1/
    images/
      image1.jpg
      image2.png
    sounds/
      sound1.mp3
    files/
      file1.pdf
  idOfFolder2/
    images/
      ...

I need to iterate through all folders having a specific id and get images. Since the answer written iterates through all folders it takes much more time than normal (we have many files). To optimize process, I want to skip "sounds" and "files" folders. Is there a way to handle this?

Thank you!


问:
React Native 'hello world' quick start: "could not connect to development server"
I'm trying to do the react native 'hello world', and I'm using usb debugging on my android.

I ran react-native run-android, then react-native start.

I can view the js file in localhost, but get 'could not connect to development server' message on my phone.

I followed the instructions to run adb reverse tcp:8081 tcp:8081, then realized that command doesn't exist, so I ran adb forward tcp:8081 tcp:8081 instead.

Still no luck. Using react-native@0.22.0, ubuntu 14.04. My phone is nexus 5 on android 6.0.1.

How can I allow my phone to access my localhost?

By the way, it is working over wifi, but I'd like to get it working over usb.

答:
I had a similar problem. I would get this error when trying to get it to run on device. It was working fine on my simulators on my computer.

The problem was when I would do adb devices or react-native run-android I would get "ADB is Not Recognized as an internal or external command".

So my fix was to add the path to adb.exe's parent directory to my Environment Variables and then restart my command prompts. After I did that, adb devices would not throw the "unrecognized internal external blah" and it listed my device. I then ran react-native run-android and on startup no more red screen showing the completely useless error message Error calling AppRegistry.runApplication! :)

So I found ADB was located in my folder:

C:\Users\dell\AppData\Local\Android\sdk\platform-tools\adb.exe
I am on a Windows 10 system. dell is my user name of the computer.

So I went to System Environemnt Variables then found "Path" then clicked "Edit", then clicked "New" and added in "C:\Users\dell\AppData\Local\Android\sdk\platform-tools".


问:
increase max count azure mobile services android
I am doing android-azure mobile app offline sync. and currently use this code to pull table

```<code>table.pull(query).get();
</code>```

however with this the max top is always 50 which causes many calls.

now to set top i read, you have to do ,

```<code>QueryOperations().fields().top()
</code>```

but if i do not have any conditions then query variable will be null, and hence I am not sure how i set "top" parameter.

I am very much new in android. so if question is not good, feel free to edit. :)

答:
According to the Azure offical tutorial How to use the Azure Mobile Apps SDK for Android, it said as below in the subsection Return data in pages.

Return data in pages

Data is ALWAYS returned in pages. The maximum number of records returned is set by the server. If the client requests more records, then the server returns the maximum number of records. By default, the maximum page size on the server is 50 records.

And a tip shows.

Tip

Choosing the right page size is a balance between memory usage while the request is happening, bandwidth usage and delay in receiving the data completely. The default (50 records) is suitable for all devices. If you exclusively operate on larger memory devices, increase up to 500. We have found that increasing the page size beyond 500 records results in unacceptable delays and large memory issues.

So if you want to change the maxmium page size, you need to set it on the backend of Azure Mobile Apps via NodeJs/C# code. The client SDK could not do it.

There was an existing SO thread Azure Mobile App node.js backend Android client - 50 row limit which has a similar question with yours, you can refer to its answer to resolve yours if you were using NodeJS in your backend.

Hope it helps.

Body:
I am doing android-azure mobile app offline sync. and currently use this code to pull table

table.pull(query).get();

however with this the max top is always 50 which causes many calls.

now to set top i read, you have to do ,

QueryOperations().fields().top()

but if i do not have any conditions then query variable will be null, and hence I am not sure how i set "top" parameter.

I am very much new in android. so if question is not good, feel free to edit. :)


问:
run queries periodically (ala crontab) from a postgresql database
I am trying to replicate (a mininimal) crontab functionality in a postgresql database table with crontab-like semantics as follows below (indices not shown, for simiplicity):

```<code>create table schedule (
id int not null primary key,
command text
);

create table schedule_detail(
schedule_id int not null references schedule(id),
sd_minute smallint not null,
sd_hour smallint not null,
sd_day smallint not null,
sd_month smallint not null,
sd_year smallint not null,
sd_dayofweek smallint not null
);
</code>```

I have only got as far as the schema design. I would like some ideas on how I can implement this. In particular, how to implement:

The 'periodic polling' of the schedule table

How to determine which schedule to be run

Does postgresql have any native (inbuilt) functionality that I can build upon to achieve this behaviour?

答: pgAgent will do the job. A complete setup can be found at Postgresonline.com.</p>

Body:
I am trying to replicate (a mininimal) crontab functionality in a postgresql database table with crontab-like semantics as follows below (indices not shown, for simiplicity):

create table schedule (
id int not null primary key,
command text
);

create table schedule_detail(
schedule_id int not null references schedule(id),
sd_minute smallint not null,
sd_hour smallint not null,
sd_day smallint not null,
sd_month smallint not null,
sd_year smallint not null,
sd_dayofweek smallint not null
);

I have only got as far as the schema design. I would like some ideas on how I can implement this. In particular, how to implement:

The 'periodic polling' of the schedule table

How to determine which schedule to be run

Does postgresql have any native (inbuilt) functionality that I can build upon to achieve this behaviour?


问:
How to disable/remove specific OpenSSL crypto algorithms from OpenSSL source code?
How can I add/create a c/c++ OpenSSL static library with specific crypto algorithms? Let's say I don't want md5 implementation. how do I create a library without md5?

答:
In configure script you can specify no-<cipher> option, it will build openssl without the cipher that you specified, you can refer to INSTALL file from openssl package

```<code>  no-<cipher>   Build without the specified cipher (bf, cast, des, dh, dsa,
                hmac, md2, md5, mdc2, rc2, rc4, rc5, rsa, sha).
                The crypto/<cipher> directory can be removed after running
                "make depend".
</code>```

Body:
In configure script you can specify no-<cipher> option, it will build openssl without the cipher that you specified, you can refer to INSTALL file from openssl package

  no-<cipher>   Build without the specified cipher (bf, cast, des, dh, dsa,
                hmac, md2, md5, mdc2, rc2, rc4, rc5, rsa, sha).
                The crypto/<cipher> directory can be removed after running
                "make depend".


问:
Create delay between two message reads of a Queue?
I am using Azure Queues to perform a bulk import.
I am using WebJobs to perform the process in the background.
The queue dequeues very frequently. How do I create a delay between 2 message
reads?

This is how I am adding a message to the Queue

```<code>public async Task<bool> Handle(CreateFileUploadCommand message)
{
    var queueClient = _queueService.GetQueueClient(Constants.Queues.ImportQueue);

    var brokeredMessage = new BrokeredMessage(JsonConvert.SerializeObject(new ProcessFileUploadMessage
    {
        TenantId = message.TenantId,
        FileExtension = message.FileExtension,
        FileName = message.Name,
        DeviceId = message.DeviceId,
        SessionId = message.SessionId,
        UserId = message.UserId,
        OutletId = message.OutletId,
        CorrelationId = message.CorrelationId,

    }))
    {
        ContentType = "application/json",
    };

    await queueClient.SendAsync(brokeredMessage);

    return true;
}
</code>```

And Below is the WebJobs Function.

```<code>public class Functions
{
    private readonly IValueProvider _valueProvider;
    public Functions(IValueProvider valueProvider)
    {
        _valueProvider = valueProvider;
    }

    public async Task ProcessQueueMessage([ServiceBusTrigger(Constants.Constants.Queues.ImportQueue)] BrokeredMessage message,
    TextWriter logger)
    {

        var queueMessage = message.GetBody<string>();

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(_valueProvider.Get("ServiceBaseUri"));

            var stringContent = new StringContent(queueMessage, Encoding.UTF8, "application/json");

            var result = await client.PostAsync(RestfulUrls.ImportMenu.ProcessUrl, stringContent);

            if (result.IsSuccessStatusCode)
            {
                await message.CompleteAsync();
            }
            else
            {
                await message.AbandonAsync();
            }
        }
    }
}
</code>```

答:
As far as I know, azure webjobs sdk enable concurrent processing on a single instance(the default is 16).

If you run your webjobs, it will read 16 queue messages(peeklock and calls Complete on the message if the function finishes successfully, or calls Abandon)  and create 16 processes to execute the trigger function at same time. So you feel the queue dequeues very frequently.

If you want to disable concurrent processing on a single instance.

I suggest you could set ServiceBusConfiguration's MessageOptions.MaxConcurrentCalls to 1.

More details, you could refer to below codes:

In the program.cs:

```<code>JobHostConfiguration config = new JobHostConfiguration();
ServiceBusConfiguration serviceBusConfig = new ServiceBusConfiguration();
serviceBusConfig.MessageOptions.MaxConcurrentCalls = 1;
config.UseServiceBus(serviceBusConfig);

JobHost host = new JobHost(config);
host.RunAndBlock();
</code>```

If you want to create a delay between 2 message reads, I suggest you could create a custom ServiceBusConfiguration.MessagingProvider.

It contains CompleteProcessingMessageAsync method, this method completes processing of the specified message, after the job function has been invoked.

I suggest you could add thread.sleep method in CompleteProcessingMessageAsync to achieve delay read.

More detail, you could refer to below code sample:

CustomMessagingProvider.cs:

Notice: I override the CompleteProcessingMessageAsync method codes.

```<code> public class CustomMessagingProvider : MessagingProvider
    {
        private readonly ServiceBusConfiguration _config;

        public CustomMessagingProvider(ServiceBusConfiguration config)
            : base(config)
        {
            _config = config;
        }

        public override NamespaceManager CreateNamespaceManager(string connectionStringName = null)
        {
            // you could return your own NamespaceManager here, which would be used
            // globally
            return base.CreateNamespaceManager(connectionStringName);
        }

        public override MessagingFactory CreateMessagingFactory(string entityPath, string connectionStringName = null)
        {
            // you could return a customized (or new) MessagingFactory here per entity
            return base.CreateMessagingFactory(entityPath, connectionStringName);
        }

        public override MessageProcessor CreateMessageProcessor(string entityPath)
        {
            // demonstrates how to plug in a custom MessageProcessor
            // you could use the global MessageOptions, or use different
            // options per entity
            return new CustomMessageProcessor(_config.MessageOptions);
        }

        private class CustomMessageProcessor : MessageProcessor
        {
            public CustomMessageProcessor(OnMessageOptions messageOptions)
                : base(messageOptions)
            {
            }

            public override Task<bool> BeginProcessingMessageAsync(BrokeredMessage message, CancellationToken cancellationToken)
            {
                // intercept messages before the job function is invoked
                return base.BeginProcessingMessageAsync(message, cancellationToken);
            }

            public override async Task CompleteProcessingMessageAsync(BrokeredMessage message, FunctionResult result, CancellationToken cancellationToken)
            {
                if (result.Succeeded)
                {
                    if (!MessageOptions.AutoComplete)
                    {
                        // AutoComplete is true by default, but if set to false
                        // we need to complete the message
                        cancellationToken.ThrowIfCancellationRequested();

                        await message.CompleteAsync();

                        Console.WriteLine("Begin sleep");
                        //Sleep 5 seconds
                        Thread.Sleep(5000);
                        Console.WriteLine("Sleep 5 seconds");

                    }
                }
                else
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    await message.AbandonAsync();
                }
            }
        }
    }
</code>```

Program.cs main method:

```<code> static void Main()
        {
            var config = new JobHostConfiguration();

            if (config.IsDevelopment)
            {
                config.UseDevelopmentSettings();
            }

            var sbConfig = new ServiceBusConfiguration
            {
                MessageOptions = new OnMessageOptions
                {
                    AutoComplete = false,
                    MaxConcurrentCalls = 1
                }
            };
            sbConfig.MessagingProvider = new CustomMessagingProvider(sbConfig);
            config.UseServiceBus(sbConfig);
            var host = new JobHost(config);

            // The following code ensures that the WebJob will be running continuously
            host.RunAndBlock();
        }
</code>```

Result:

Body:
I am using Azure Queues to perform a bulk import.
I am using WebJobs to perform the process in the background.
The queue dequeues very frequently. How do I create a delay between 2 message
reads?

This is how I am adding a message to the Queue

public async Task<bool> Handle(CreateFileUploadCommand message)
{
    var queueClient = _queueService.GetQueueClient(Constants.Queues.ImportQueue);

    var brokeredMessage = new BrokeredMessage(JsonConvert.SerializeObject(new ProcessFileUploadMessage
    {
        TenantId = message.TenantId,
        FileExtension = message.FileExtension,
        FileName = message.Name,
        DeviceId = message.DeviceId,
        SessionId = message.SessionId,
        UserId = message.UserId,
        OutletId = message.OutletId,
        CorrelationId = message.CorrelationId,

    }))
    {
        ContentType = "application/json",
    };

    await queueClient.SendAsync(brokeredMessage);

    return true;
}

And Below is the WebJobs Function.

public class Functions
{
    private readonly IValueProvider _valueProvider;
    public Functions(IValueProvider valueProvider)
    {
        _valueProvider = valueProvider;
    }

    public async Task ProcessQueueMessage([ServiceBusTrigger(Constants.Constants.Queues.ImportQueue)] BrokeredMessage message,
    TextWriter logger)
    {

        var queueMessage = message.GetBody<string>();

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(_valueProvider.Get("ServiceBaseUri"));

            var stringContent = new StringContent(queueMessage, Encoding.UTF8, "application/json");

            var result = await client.PostAsync(RestfulUrls.ImportMenu.ProcessUrl, stringContent);

            if (result.IsSuccessStatusCode)
            {
                await message.CompleteAsync();
            }
            else
            {
                await message.AbandonAsync();
            }
        }
    }
}

Body:
As far as I know, azure webjobs sdk enable concurrent processing on a single instance(the default is 16).

If you run your webjobs, it will read 16 queue messages(peeklock and calls Complete on the message if the function finishes successfully, or calls Abandon)  and create 16 processes to execute the trigger function at same time. So you feel the queue dequeues very frequently.

If you want to disable concurrent processing on a single instance.

I suggest you could set ServiceBusConfiguration's MessageOptions.MaxConcurrentCalls to 1.

More details, you could refer to below codes:

In the program.cs:

JobHostConfiguration config = new JobHostConfiguration();
ServiceBusConfiguration serviceBusConfig = new ServiceBusConfiguration();
serviceBusConfig.MessageOptions.MaxConcurrentCalls = 1;
config.UseServiceBus(serviceBusConfig);

JobHost host = new JobHost(config);
host.RunAndBlock();

If you want to create a delay between 2 message reads, I suggest you could create a custom ServiceBusConfiguration.MessagingProvider.

It contains CompleteProcessingMessageAsync method, this method completes processing of the specified message, after the job function has been invoked.

I suggest you could add thread.sleep method in CompleteProcessingMessageAsync to achieve delay read.

More detail, you could refer to below code sample:

CustomMessagingProvider.cs:

Notice: I override the CompleteProcessingMessageAsync method codes.

 public class CustomMessagingProvider : MessagingProvider
    {
        private readonly ServiceBusConfiguration _config;

        public CustomMessagingProvider(ServiceBusConfiguration config)
            : base(config)
        {
            _config = config;
        }

        public override NamespaceManager CreateNamespaceManager(string connectionStringName = null)
        {
            // you could return your own NamespaceManager here, which would be used
            // globally
            return base.CreateNamespaceManager(connectionStringName);
        }

        public override MessagingFactory CreateMessagingFactory(string entityPath, string connectionStringName = null)
        {
            // you could return a customized (or new) MessagingFactory here per entity
            return base.CreateMessagingFactory(entityPath, connectionStringName);
        }

        public override MessageProcessor CreateMessageProcessor(string entityPath)
        {
            // demonstrates how to plug in a custom MessageProcessor
            // you could use the global MessageOptions, or use different
            // options per entity
            return new CustomMessageProcessor(_config.MessageOptions);
        }

        private class CustomMessageProcessor : MessageProcessor
        {
            public CustomMessageProcessor(OnMessageOptions messageOptions)
                : base(messageOptions)
            {
            }

            public override Task<bool> BeginProcessingMessageAsync(BrokeredMessage message, CancellationToken cancellationToken)
            {
                // intercept messages before the job function is invoked
                return base.BeginProcessingMessageAsync(message, cancellationToken);
            }

            public override async Task CompleteProcessingMessageAsync(BrokeredMessage message, FunctionResult result, CancellationToken cancellationToken)
            {
                if (result.Succeeded)
                {
                    if (!MessageOptions.AutoComplete)
                    {
                        // AutoComplete is true by default, but if set to false
                        // we need to complete the message
                        cancellationToken.ThrowIfCancellationRequested();

                        await message.CompleteAsync();

                        Console.WriteLine("Begin sleep");
                        //Sleep 5 seconds
                        Thread.Sleep(5000);
                        Console.WriteLine("Sleep 5 seconds");

                    }
                }
                else
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    await message.AbandonAsync();
                }
            }
        }
    }

Program.cs main method:

 static void Main()
        {
            var config = new JobHostConfiguration();

            if (config.IsDevelopment)
            {
                config.UseDevelopmentSettings();
            }

            var sbConfig = new ServiceBusConfiguration
            {
                MessageOptions = new OnMessageOptions
                {
                    AutoComplete = false,
                    MaxConcurrentCalls = 1
                }
            };
            sbConfig.MessagingProvider = new CustomMessagingProvider(sbConfig);
            config.UseServiceBus(sbConfig);
            var host = new JobHost(config);

            // The following code ensures that the WebJob will be running continuously
            host.RunAndBlock();
        }

Result:


问:
vb.net display oldest date
Book Collection as a coding project for an intro class and need to display the oldest print year. It is showing up initially but won't write to file because I'm trying to convert from string to integer. Code that's being used:</p>

```<code>Private Sub findOldest()
    Dim oldest As Integer = 4000
    Dim printDate As Integer
    For index As Integer = 2 To count * 4 - 1 Step 4
        printDate = CInt(bookData(index))
        If oldest > printDate Then
            oldest = printDate
        End If
    Next
    lblOldestBook.Text = CStr(oldest)
End Sub
</code>```

答:
You could use Linq to return the earliest date. As for writing to the .Text property, you can use .ToString() to represent in object as a string.

```<code>Dim MinDate = (From d In bookData).Min() 'untested!

lblOldestBook.Text = oldest.ToString()
</code>```

Title: vb.net display oldest date

Body:
Book Collection as a coding project for an intro class and need to display the oldest print year. It is showing up initially but won't write to file because I'm trying to convert from string to integer. Code that's being used:

Private Sub findOldest()
    Dim oldest As Integer = 4000
    Dim printDate As Integer
    For index As Integer = 2 To count * 4 - 1 Step 4
        printDate = CInt(bookData(index))
        If oldest > printDate Then
            oldest = printDate
        End If
    Next
    lblOldestBook.Text = CStr(oldest)
End Sub

Body:
You could use Linq to return the earliest date. As for writing to the .Text property, you can use .ToString() to represent in object as a string.

Dim MinDate = (From d In bookData).Min() 'untested!

lblOldestBook.Text = oldest.ToString()


问:
How to set global variable in Main method c#
I have two variables in foreach for username and password and I want to set to global variables but I don't know how ?
I try with this code but, when I try to replace strings with username and password with this variable I receive message:

```<code>Use of unsigned local variable 'username'.
Use of unsigned local variable 'password'.
</code>```

The code:

```<code>            public static void Main()
        {
            string[] lineOfContents = File.ReadAllLines(@"C:\\M\send.txt");

            string username;
            string password;

            foreach (var line in lineOfContents)
            {
                string[] tokens = line.Split(',');
                string user = tokens[0];
                string pass = tokens[1];
                username = user;
                password = pass;
            }

            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://199.199.199.199/Plovdiv.txt");
                request.Method = WebRequestMethods.Ftp.UploadFile;

                // This example assumes the FTP site uses anonymous logon.
                request.Credentials = new NetworkCredential(username, password);
</code>```

答:
The compiler doesn't know whether the loop will execute or not that's why it shows such warnings, ie., The loop may or may not execute, if it skips the iteration(lineOfContents is null or it has no values) then your local variables username and password will not get initialized and that leads to Exceptions, to avoid that you have to initialized them with some default values, so the declaration would be like the following:

```<code>string username = ""; // String.Empty or some default values
string password = "";
// rest of code here
</code>```

Body:
I have two variables in foreach for username and password and I want to set to global variables but I don't know how ?
I try with this code but, when I try to replace strings with username and password with this variable I receive message:

Use of unsigned local variable 'username'.
Use of unsigned local variable 'password'.

The code:

            public static void Main()
        {
            string[] lineOfContents = File.ReadAllLines(@"C:\\M\send.txt");

            string username;
            string password;

            foreach (var line in lineOfContents)
            {
                string[] tokens = line.Split(',');
                string user = tokens[0];
                string pass = tokens[1];
                username = user;
                password = pass;
            }

            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://199.199.199.199/Plovdiv.txt");
                request.Method = WebRequestMethods.Ftp.UploadFile;

                // This example assumes the FTP site uses anonymous logon.
                request.Credentials = new NetworkCredential(username, password);

Body:
The compiler doesn't know whether the loop will execute or not that's why it shows such warnings, ie., The loop may or may not execute, if it skips the iteration(lineOfContents is null or it has no values) then your local variables username and password will not get initialized and that leads to Exceptions, to avoid that you have to initialized them with some default values, so the declaration would be like the following:

string username = ""; // String.Empty or some default values
string password = "";
// rest of code here


问:
Excel VBA: Insert N number of Sheets based on cell value
I'm new in Excel VBA. I want to insert number of cells based on a cell value.

I have sheet1, i want to use b4 as a reference as to the number of sheets (which is a template) to be inserted.

Example, if value of b4 = 4, I'd like to copy the template sheet 4 times.

How do i do that in vba?

THANKS. :)

答:
Something like this should work:</p>

```<code>Sub copySheets()

Dim i As integer

Dim n As integer 'the amount of sheets

n = Cells(4, 2).Value 'b4

For i = 2 To n
    If ActiveWorkbooks.Worksheets.Count < n Then 'Makes sure the sheets exists
        Dim ws As Worksheet
        Set ws = ThisWorkbook.Sheets.Add(After:= _
             ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
    End If
    ws1.Copy ThisWorkbook.Sheets(Sheets.Count) 'copy data

Next i

End Sub
</code>```

Body:
Something like this should work:

Sub copySheets()

Dim i As integer

Dim n As integer 'the amount of sheets

n = Cells(4, 2).Value 'b4

For i = 2 To n
    If ActiveWorkbooks.Worksheets.Count < n Then 'Makes sure the sheets exists
        Dim ws As Worksheet
        Set ws = ThisWorkbook.Sheets.Add(After:= _
             ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
    End If
    ws1.Copy ThisWorkbook.Sheets(Sheets.Count) 'copy data

Next i

End Sub


问:
How to display array in array on Highcharts? [JS]
I get data like this from the server:

```<code>data":[[1496640705,1583360,1583360,1583370,1583360],[1496640720,1583360,1583350,1583360,1583345],[1496640735,1583350,1583320,1583400,1583320]]
</code>```

My question is, how can I display this data on Highcharts? Every array first element is the Date for X axis, and only want the last data every array for the Y axis. How can I select these 2 elements for Highcharts?

答:
Your data from server should contains Date in millisecond format(for highcharts).So your data must be like

```<code>  var data = [
    [1496640705000, 1583360, 1583360, 1583370, 1583360],
    [1496640720000, 1583360, 1583350, 1583360, 1583345],
    [1496640735000, 1583350, 1583320, 1583400, 1583320]
  ],
//For highcharts data should be formatted as [[x,y],[x,y],...]
seresData=[]
data.forEach(function(item) {
seresData.push([item[0],item[item.length - 1]])
})
console.log(seresData)
</code>```

Demo Code

var data = [
    [1496640705000, 1583360, 1583360, 1583370, 1583360],
    [1496640720000, 1583360, 1583350, 1583360, 1583345],
    [1496640735000, 1583350, 1583320, 1583400, 1583320]
  ],

  seresData = []
data.forEach(function(item) {
  seresData.push([item[0], item[item.length - 1]])
})
//console.log(seresData)

Highcharts.chart('container', {
  chart: {
    type: 'spline'
  },
  title: {
    text: 'Snow depth at Vikjafjellet, Norway'
  },
  subtitle: {
    text: 'Irregular time data in Highcharts JS'
  },
  xAxis: {
    type: 'datetime',
    dateTimeLabelFormats: { // don't display the dummy year
      month: '%e. %b',
      year: '%b'
    },
    title: {
      text: 'Date'
    }
  },
  yAxis: {
    title: {
      text: 'Snow depth (m)'
    },
    min: 0
  },
  tooltip: {
    headerFormat: '{series.name}
',
    pointFormat: '{point.x:%e. %b}: {point.y:.2f} m'
  },

  plotOptions: {
    spline: {
      marker: {
        enabled: true
      }
    }
  },

  series: [{
    name: 'Winter 2012-2013',
    // Define the data points. All series have a dummy year
    // of 1970/71 in order to be compared on the same x axis. Note
    // that in JavaScript, months start at 0 for January, 1 for February etc.
    data: seresData
  }]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div></code>```

Body:
I get data like this from the server:

data":[[1496640705,1583360,1583360,1583370,1583360],[1496640720,1583360,1583350,1583360,1583345],[1496640735,1583350,1583320,1583400,1583320]]

My question is, how can I display this data on Highcharts? Every array first element is the Date for X axis, and only want the last data every array for the Y axis. How can I select these 2 elements for Highcharts?

Body:
Your data from server should contains Date in millisecond format(for highcharts).So your data must be like

  var data = [
    [1496640705000, 1583360, 1583360, 1583370, 1583360],
    [1496640720000, 1583360, 1583350, 1583360, 1583345],
    [1496640735000, 1583350, 1583320, 1583400, 1583320]
  ],
//For highcharts data should be formatted as [[x,y],[x,y],...]
seresData=[]
data.forEach(function(item) {
seresData.push([item[0],item[item.length - 1]])
})
console.log(seresData)

Demo Code

var data = [
    [1496640705000, 1583360, 1583360, 1583370, 1583360],
    [1496640720000, 1583360, 1583350, 1583360, 1583345],
    [1496640735000, 1583350, 1583320, 1583400, 1583320]
  ],

  seresData = []
data.forEach(function(item) {
  seresData.push([item[0], item[item.length - 1]])
})
//console.log(seresData)

Highcharts.chart('container', {
  chart: {
    type: 'spline'
  },
  title: {
    text: 'Snow depth at Vikjafjellet, Norway'
  },
  subtitle: {
    text: 'Irregular time data in Highcharts JS'
  },
  xAxis: {
    type: 'datetime',
    dateTimeLabelFormats: { // don't display the dummy year
      month: '%e. %b',
      year: '%b'
    },
    title: {
      text: 'Date'
    }
  },
  yAxis: {
    title: {
      text: 'Snow depth (m)'
    },
    min: 0
  },
  tooltip: {
    headerFormat: '<b>{series.name}</b><br>',
    pointFormat: '{point.x:%e. %b}: {point.y:.2f} m'
  },

  plotOptions: {
    spline: {
      marker: {
        enabled: true
      }
    }
  },

  series: [{
    name: 'Winter 2012-2013',
    // Define the data points. All series have a dummy year
    // of 1970/71 in order to be compared on the same x axis. Note
    // that in JavaScript, months start at 0 for January, 1 for February etc.
    data: seresData
  }]
});

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>


问:
How should we get cumulative columns for different types of variables?
my data is something like this:

```<code>structure(c("Manufacturing Excell", "NPI Efficiencies", "NPI Efficiencies",
"Manufacturing Excell", "Manufacturing Excell", "Material Efficiencie",
"NPI Efficiencies", "Manufacturing Excell", "NPI Efficiencies",
"NPI Efficiencies", "NPI Efficiencies", "Material Efficiencie",
"NPI Efficiencies", "NPI Efficiencies", "Manufacturing Excell",
"Manufacturing Excell", "NPI Efficiencies", "NPI Efficiencies",
"NPI Efficiencies", "NPI Efficiencies", "Material Efficiencie",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "Manufacturing Excell",
"NPI Efficiencies", "NPI Efficiencies", "Manufacturing Excell",
"Manufacturing Excell", "Manufacturing Excell", "Manufacturing Excell",
"NPI Efficiencies", "Manufacturing Excell", "Material Efficiencie",
"Manufacturing Excell", "Manufacturing Excell", "NPI Efficiencies",
"Manufacturing Excell", "Manufacturing Excell", "Manufacturing Excell",
"NPI Efficiencies", "NPI Efficiencies", "Material Efficiencie",
"NPI Efficiencies", "Manufacturing Excell", "NPI Efficiencies",
"Manufacturing Excell", "NPI Efficiencies", "Manufacturing Excell",
"Manufacturing Excell", "Manufacturing Excell", "NPI Efficiencies",
"NPI Efficiencies", "Manufacturing Excell", "NPI Efficiencies",
"NPI Efficiencies", "Manufacturing Excell", "Manufacturing Excell",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "Material Efficiencie",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies",
"Manufacturing Excell", "Manufacturing Excell", "Material Efficiencie",
"NPI Efficiencies", "NPI Efficiencies", "Material Efficiencie",
"Material Efficiencie", "NPI Efficiencies", "NPI Efficiencies",
"Manufacturing Excell", "NPI Efficiencies", "NPI Efficiencies",
"NPI Efficiencies", "Material Efficiencie", "NPI Efficiencies",
"Material Efficiencie", "Manufacturing Excell", "Material Efficiencie",
"NPI Efficiencies", "Manufacturing Excell", "Material Efficiencie",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "Manufacturing Excell",
"Manufacturing Excell", "NPI Efficiencies", "Manufacturing Excell",
"Material Efficiencie", "NPI Efficiencies", "Material Efficiencie",
"NPI Efficiencies", "NPI Efficiencies", "Manufacturing Excell",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies",
"Manufacturing Excell", "Material Efficiencie", "Material Efficiencie",
"Manufacturing Excell", "Material Efficiencie", "Manufacturing Excell",
"Manufacturing Excell", "NPI Efficiencies", "NPI Efficiencies",
"NPI Efficiencies", "Manufacturing Excell", "Material Efficiencie",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "Manufacturing Excell",
"Manufacturing Excell", "NPI Efficiencies", "NPI Efficiencies",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "Manufacturing Excell",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies",
"Manufacturing Excell", "NPI Efficiencies", "Manufacturing Excell",
"NPI Efficiencies", "Material Efficiencie", "NPI Efficiencies",
"NPI Efficiencies", "Manufacturing Excell", "Manufacturing Excell",
"Manufacturing Excell", "NPI Efficiencies", "NPI Efficiencies",
"Material Efficiencie", "Material Efficiencie", "Material Efficiencie",
"Material Efficiencie", "NPI Efficiencies", "NPI Efficiencies",
"Manufacturing Excell", "Manufacturing Excell", "Manufacturing Excell",
"Manufacturing Excell", "Manufacturing Excell", "Manufacturing Excell",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "Manufacturing Excell",
"Manufacturing Excell", "Material Efficiencie", "NPI Efficiencies",
"NPI Efficiencies", "28859", "15134", "29429", "14214", "37988",
"15328", "42679", "46206", "43311", "8158", "29937", "6021",
"5581", "44627", "36779", "15888", "20088", "42170", "11560",
"16401", "30293", "27682", "44574", "20240", "10176", "45920",
"40615", "28510", "23527", "35717", "12608", "30585", "1344",
"30179", "38589", "18135", "32662", "577", "47836", "36944",
"8946", "36730", "6499", "47177", "31564", "17612", "19799",
"43469", "780", "29003", "729", "39209", "8237", "12442", "40877",
"45338", "44977", "2081", "47886", "19948", "38960", "27127",
"33186", "36972", "29774", "24197", "47513", "21171", "10992",
"2630", "39740", "38639", "8373", "7932", "44641", "8877", "4256",
"47425", "4972", "11793", "48437", "15102", "30181", "23058",
"27086", "11750", "32797", "33320", "42980", "2712", "3360",
"18773", "34625", "48207", "18044", "16727", "36327", "38051",
"39081", "35858", "11747", "32221", "45342", "25444", "27538",
"3725", "29636", "37667", "24387", "43088", "49972", "39308",
"17497", "26198", "42199", "20640", "26455", "42792", "36511",
"16867", "34142", "10629", "15415", "38989", "24381", "45988",
"19603", "40886", "16616", "13004", "8370", "34725", "17915",
"29838", "38500", "10620", "45602", "11911", "38119", "308",
"37473", "17560", "14887", "30872", "7622", "20169", "38494",
"12728", "14816", "37183", "18602", "157", "49615", "12902",
"31344", "15606", "30386", "49746", "26466", "19784", "9326",
"33639", "25323", "31404", "20045", "45788", "49454", "13271",
"44675", "44926", "33041"), .Dim = c(171L, 2L))
</code>```

Now what i want to do is get a separate cumulative sum table for different savings type. That is i want a separate cumulative sum table for NPI Efficiencie, for Manufacturing Excel, and for Material Efficiencies. is there anyways i can do this with the help of R. Please help!

答:
Like this?</p>

```<code>library(dplyr)
library(data.table)
dt <- data.frame(dt) %>% setDT
dt[, X2 := as.character(X2) %>% as.numeric]
dt[, cumsum_by_group := cumsum(X2), by = X1]
</code>```

Body:
my data is something like this:

structure(c("Manufacturing Excell", "NPI Efficiencies", "NPI Efficiencies",
"Manufacturing Excell", "Manufacturing Excell", "Material Efficiencie",
"NPI Efficiencies", "Manufacturing Excell", "NPI Efficiencies",
"NPI Efficiencies", "NPI Efficiencies", "Material Efficiencie",
"NPI Efficiencies", "NPI Efficiencies", "Manufacturing Excell",
"Manufacturing Excell", "NPI Efficiencies", "NPI Efficiencies",
"NPI Efficiencies", "NPI Efficiencies", "Material Efficiencie",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "Manufacturing Excell",
"NPI Efficiencies", "NPI Efficiencies", "Manufacturing Excell",
"Manufacturing Excell", "Manufacturing Excell", "Manufacturing Excell",
"NPI Efficiencies", "Manufacturing Excell", "Material Efficiencie",
"Manufacturing Excell", "Manufacturing Excell", "NPI Efficiencies",
"Manufacturing Excell", "Manufacturing Excell", "Manufacturing Excell",
"NPI Efficiencies", "NPI Efficiencies", "Material Efficiencie",
"NPI Efficiencies", "Manufacturing Excell", "NPI Efficiencies",
"Manufacturing Excell", "NPI Efficiencies", "Manufacturing Excell",
"Manufacturing Excell", "Manufacturing Excell", "NPI Efficiencies",
"NPI Efficiencies", "Manufacturing Excell", "NPI Efficiencies",
"NPI Efficiencies", "Manufacturing Excell", "Manufacturing Excell",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "Material Efficiencie",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies",
"Manufacturing Excell", "Manufacturing Excell", "Material Efficiencie",
"NPI Efficiencies", "NPI Efficiencies", "Material Efficiencie",
"Material Efficiencie", "NPI Efficiencies", "NPI Efficiencies",
"Manufacturing Excell", "NPI Efficiencies", "NPI Efficiencies",
"NPI Efficiencies", "Material Efficiencie", "NPI Efficiencies",
"Material Efficiencie", "Manufacturing Excell", "Material Efficiencie",
"NPI Efficiencies", "Manufacturing Excell", "Material Efficiencie",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "Manufacturing Excell",
"Manufacturing Excell", "NPI Efficiencies", "Manufacturing Excell",
"Material Efficiencie", "NPI Efficiencies", "Material Efficiencie",
"NPI Efficiencies", "NPI Efficiencies", "Manufacturing Excell",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies",
"Manufacturing Excell", "Material Efficiencie", "Material Efficiencie",
"Manufacturing Excell", "Material Efficiencie", "Manufacturing Excell",
"Manufacturing Excell", "NPI Efficiencies", "NPI Efficiencies",
"NPI Efficiencies", "Manufacturing Excell", "Material Efficiencie",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "Manufacturing Excell",
"Manufacturing Excell", "NPI Efficiencies", "NPI Efficiencies",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "Manufacturing Excell",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies",
"Manufacturing Excell", "NPI Efficiencies", "Manufacturing Excell",
"NPI Efficiencies", "Material Efficiencie", "NPI Efficiencies",
"NPI Efficiencies", "Manufacturing Excell", "Manufacturing Excell",
"Manufacturing Excell", "NPI Efficiencies", "NPI Efficiencies",
"Material Efficiencie", "Material Efficiencie", "Material Efficiencie",
"Material Efficiencie", "NPI Efficiencies", "NPI Efficiencies",
"Manufacturing Excell", "Manufacturing Excell", "Manufacturing Excell",
"Manufacturing Excell", "Manufacturing Excell", "Manufacturing Excell",
"NPI Efficiencies", "NPI Efficiencies", "NPI Efficiencies", "Manufacturing Excell",
"Manufacturing Excell", "Material Efficiencie", "NPI Efficiencies",
"NPI Efficiencies", "28859", "15134", "29429", "14214", "37988",
"15328", "42679", "46206", "43311", "8158", "29937", "6021",
"5581", "44627", "36779", "15888", "20088", "42170", "11560",
"16401", "30293", "27682", "44574", "20240", "10176", "45920",
"40615", "28510", "23527", "35717", "12608", "30585", "1344",
"30179", "38589", "18135", "32662", "577", "47836", "36944",
"8946", "36730", "6499", "47177", "31564", "17612", "19799",
"43469", "780", "29003", "729", "39209", "8237", "12442", "40877",
"45338", "44977", "2081", "47886", "19948", "38960", "27127",
"33186", "36972", "29774", "24197", "47513", "21171", "10992",
"2630", "39740", "38639", "8373", "7932", "44641", "8877", "4256",
"47425", "4972", "11793", "48437", "15102", "30181", "23058",
"27086", "11750", "32797", "33320", "42980", "2712", "3360",
"18773", "34625", "48207", "18044", "16727", "36327", "38051",
"39081", "35858", "11747", "32221", "45342", "25444", "27538",
"3725", "29636", "37667", "24387", "43088", "49972", "39308",
"17497", "26198", "42199", "20640", "26455", "42792", "36511",
"16867", "34142", "10629", "15415", "38989", "24381", "45988",
"19603", "40886", "16616", "13004", "8370", "34725", "17915",
"29838", "38500", "10620", "45602", "11911", "38119", "308",
"37473", "17560", "14887", "30872", "7622", "20169", "38494",
"12728", "14816", "37183", "18602", "157", "49615", "12902",
"31344", "15606", "30386", "49746", "26466", "19784", "9326",
"33639", "25323", "31404", "20045", "45788", "49454", "13271",
"44675", "44926", "33041"), .Dim = c(171L, 2L))

Now what i want to do is get a separate cumulative sum table for different savings type. That is i want a separate cumulative sum table for NPI Efficiencie, for Manufacturing Excel, and for Material Efficiencies. is there anyways i can do this with the help of R. Please help!

Body:
Like this?

library(dplyr)
library(data.table)
dt <- data.frame(dt) %>% setDT
dt[, X2 := as.character(X2) %>% as.numeric]
dt[, cumsum_by_group := cumsum(X2), by = X1]


问:
CSS Font Images
another quick question. I've seen this multiple times now in different code sets. Someone calls for an image from the css

HTML:

```<code>    <a href="#"><i class="icon-map-marker2"></i></a>
</code>```

CSS

```<code>.icon-map-marker2:before {
    content: "\e6f9";
}
</code>```

Which gives the output of this:

As you can see the picture isn't transparent background. I was looking to edit it to give it transparency, but can't seem to find out how. I've also tried things with the CSS like:

```<code>style="background-color:rgba(0, 0, 0, 0.5);"
// Changing the last value's number though and stuff like that
opacity: 1;
// etc
</code>```

I want to keep the gold color, but have a transparent background! Thanks for the assistance!

An example is on Canvas' live preview - Hover Home -> One Page: http://preview.themeforest.net/item/canvas-the-multipurpose-html5-template/full_screen_preview/9228123?_ga=2.252490057.1116575863.1496646725-686174233.1494200798

答:
Try adding css for a tag for background color:

```<code>a{
  background:transparent;
}
</code>```

Background coming form .fbox-icon this div.. just add css for that

```<code>.feature-box.fbox-bg.fbox-center .fbox-icon {
   background-color:transparent;
}
</code>```

Title: CSS Font Images

Body:
another quick question. I've seen this multiple times now in different code sets. Someone calls for an image from the css

HTML:

CSS

.icon-map-marker2:before {
    content: "\e6f9";
}

Which gives the output of this:

As you can see the picture isn't transparent background. I was looking to edit it to give it transparency, but can't seem to find out how. I've also tried things with the CSS like:

style="background-color:rgba(0, 0, 0, 0.5);"
// Changing the last value's number though and stuff like that
opacity: 1;
// etc

I want to keep the gold color, but have a transparent background! Thanks for the assistance!

An example is on Canvas' live preview - Hover Home -> One Page: http://preview.themeforest.net/item/canvas-the-multipurpose-html5-template/full_screen_preview/9228123?_ga=2.252490057.1116575863.1496646725-686174233.1494200798

Body:
Try adding css for a tag for background color:

a{
  background:transparent;
}

Background coming form .fbox-icon this div.. just add css for that

.feature-box.fbox-bg.fbox-center .fbox-icon {
   background-color:transparent;
}


答:
You assign values to username and password inside the foreach loop, however the compiler doesn't know if lineOfContents is not empty, and when you reach to request.Credentials = new NetworkCredential(username, password); the variables will have any value. You need to initialize them

```<code>string username = string.Empty;
string password = string.Empty;
</code>```

Title: How to set global variable in Main method c#

Body:
You assign values to username and password inside the foreach loop, however the compiler doesn't know if lineOfContents is not empty, and when you reach to request.Credentials = new NetworkCredential(username, password); the variables will have any value. You need to initialize them

string username = string.Empty;
string password = string.Empty;


问:
Why does open() create my file with the wrong permissions?
I am trying to read some text from a file and write it to another using open(), read() and write().

This is my open() for the file-to-write-to (I want to create a new file and write into it):

```<code>fOut = open ("test-1", O_RDWR | O_CREAT | O_SYNC);
</code>```

This is setting file-permissions to something I don't understand at all. This is the output of ls -l:

```<code>---------T 1 chaitanya chaitanya 0 2010-02-11 09:38 test-1
</code>```

Even the read permission is locked. I tried searching for this, but could not find ANYTHING.
Strangely, write() still successfully writes data to the file.

Also, if I do a 'chmod 777 test-1', things start working properly again.

Could someone please let me know where I am going wrong in my open call?

Thanks!

For your reference, I have pasted the complete program below:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

int main () {

    char buffer[512], ch;

    int fIn, fOut, i;
    ssize_t bytes;
    FILE *fp = NULL;

    //open a file
    fIn = open ("test", O_RDONLY);
    if (fIn == -1) {
        printf("\nfailed to open file.");
        return 1;
    }

    //read from file
    bytes =  read (fIn, buffer, sizeof(buffer));
    //and close it
    close (fIn);

    printf("\nSuccessfully read %d bytes.\n", bytes);

    //Create a new file
    fOut = open ("test-1", O_RDWR | O_CREAT | O_SYNC);

    printf("\nThese are the permissions for test-1\n");
    fflush(stdout);
    system("ls -l test-1");

    //write to it and close it.
    write (fOut, buffer, bytes);
    close (fOut);

    //write is somehow locking even the read permission to the file. Change it.
    system("chmod 777 test-1");

    fp = fopen ("test-1", "r");
    if (fp == NULL) {
        printf("\nCan't open test-1");
        return 1;
    }

    while (1)
    {
        ch = fgetc(fp);
        if (ch == EOF)
            break;
        printf("\n%c", ch);
    }

    fclose (fp);

    return 0;
}
</code>```

答:
This is kind of an old thread, but I think people should be aware of the "sys/stat.h" library. This includes a bunch of symbolic constants for setting permission bits.

For example: To open a file with Read/Write permissions enabled for the user

```<code>#include <fcntl.h>
#include <sys/stat.h>

open("Your/File/Path", O_RDWR | O_CREAT, S_IWUSR | S_IRUSR);
</code>```

where:

```<code>S_IWUSR // Sets the Users Write bit
S_IRUSR // Sets the Users Read bit
</code>```

This library includes a bunch of others, I won't list them all here but you can read up on it all here.

Of course you can put in the octal values to set these bits, however some may argue that it is poor coding practice.

Body:
I am trying to read some text from a file and write it to another using open(), read() and write().

This is my open() for the file-to-write-to (I want to create a new file and write into it):

fOut = open ("test-1", O_RDWR | O_CREAT | O_SYNC);

This is setting file-permissions to something I don't understand at all. This is the output of ls -l:

---------T 1 chaitanya chaitanya 0 2010-02-11 09:38 test-1

Even the read permission is locked. I tried searching for this, but could not find ANYTHING.
Strangely, write() still successfully writes data to the file.

Also, if I do a 'chmod 777 test-1', things start working properly again.

Could someone please let me know where I am going wrong in my open call?

Thanks!

For your reference, I have pasted the complete program below:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

int main () {

    char buffer[512], ch;

    int fIn, fOut, i;
    ssize_t bytes;
    FILE *fp = NULL;

    //open a file
    fIn = open ("test", O_RDONLY);
    if (fIn == -1) {
        printf("\nfailed to open file.");
        return 1;
    }

    //read from file
    bytes =  read (fIn, buffer, sizeof(buffer));
    //and close it
    close (fIn);

    printf("\nSuccessfully read %d bytes.\n", bytes);

    //Create a new file
    fOut = open ("test-1", O_RDWR | O_CREAT | O_SYNC);

    printf("\nThese are the permissions for test-1\n");
    fflush(stdout);
    system("ls -l test-1");

    //write to it and close it.
    write (fOut, buffer, bytes);
    close (fOut);

    //write is somehow locking even the read permission to the file. Change it.
    system("chmod 777 test-1");

    fp = fopen ("test-1", "r");
    if (fp == NULL) {
        printf("\nCan't open test-1");
        return 1;
    }

    while (1)
    {
        ch = fgetc(fp);
        if (ch == EOF)
            break;
        printf("\n%c", ch);
    }

    fclose (fp);

    return 0;
}

Body:
This is kind of an old thread, but I think people should be aware of the "sys/stat.h" library. This includes a bunch of symbolic constants for setting permission bits.

For example: To open a file with Read/Write permissions enabled for the user

#include <fcntl.h>
#include <sys/stat.h>

open("Your/File/Path", O_RDWR | O_CREAT, S_IWUSR | S_IRUSR);

where:

S_IWUSR // Sets the Users Write bit
S_IRUSR // Sets the Users Read bit

This library includes a bunch of others, I won't list them all here but you can read up on it all here.

Of course you can put in the octal values to set these bits, however some may argue that it is poor coding practice.


问:
Kendo Ui grid: Popup window Add trigger from outside grid
I have the grid and button below. What i am trying to achieve is to trigger Kendoui popup window when is the btnAdd clicked. I am aware that this can be achieve if you put button in kendo ui grid toolbar.

Please advise, thank you

```<code>    <script>
        $('#btnAdd').click(function () {

        });
     </script>

     <input type="button" id="btnAdd"/>

    @(Html.Kendo().Grid<PWeb_App.ViewModels.ResultModel>()
            .Name("Result")
            .HtmlAttributes(new { @Style = "align:center; font-size:10px; width:985px" })
            .Columns(columns =>
            {
                columns.Bound(p => p.GivenName).Width(90);
                columns.Bound(p => p.FamilyName).Width(90);
            })
            .ToolBar(toolbar => toolbar.Save())
            .Editable(editable => editable.Mode(GridEditMode.PopUp))
            .Sortable()
            .Pageable(paging => paging
                .Input(false)
                .Numeric(true)
                .PreviousNext(true)
                .PageSizes(new int[] { 5, 10, 25, 50 })
                .Refresh(false)
            )
            .Selectable()
            .Scrollable()
            .ColumnMenu(c => c.Columns(false))
            .DataSource(dataSource => dataSource
                .Ajax()//bind with Ajax instead server bind
                .PageSize(10)
                .ServerOperation(true)
                .Model(model =>
                    {
                        model.Id(p => p.Pid);
                        model.Field(p => p.FamilyName).Editable(false);
                        model.Field(p => p.GivenName).Editable(false);
                    })
                   .Read(read => read.Action("GetData", "Details").Type(HttpVerbs.Get))
                            .Update("Edit", "Details")

                )

        )
</code>```

答: maybe adding the    editable : "popup" will solve your problem?</p>

Body:
I have the grid and button below. What i am trying to achieve is to trigger Kendoui popup window when is the btnAdd clicked. I am aware that this can be achieve if you put button in kendo ui grid toolbar.

Please advise, thank you

     <input type="button" id="btnAdd"/>

    @(Html.Kendo().Grid<PWeb_App.ViewModels.ResultModel>()
            .Name("Result")
            .HtmlAttributes(new { @Style = "align:center; font-size:10px; width:985px" })
            .Columns(columns =>
            {
                columns.Bound(p => p.GivenName).Width(90);
                columns.Bound(p => p.FamilyName).Width(90);
            })
            .ToolBar(toolbar => toolbar.Save())
            .Editable(editable => editable.Mode(GridEditMode.PopUp))
            .Sortable()
            .Pageable(paging => paging
                .Input(false)
                .Numeric(true)
                .PreviousNext(true)
                .PageSizes(new int[] { 5, 10, 25, 50 })
                .Refresh(false)
            )
            .Selectable()
            .Scrollable()
            .ColumnMenu(c => c.Columns(false))
            .DataSource(dataSource => dataSource
                .Ajax()//bind with Ajax instead server bind
                .PageSize(10)
                .ServerOperation(true)
                .Model(model =>
                    {
                        model.Id(p => p.Pid);
                        model.Field(p => p.FamilyName).Editable(false);
                        model.Field(p => p.GivenName).Editable(false);
                    })
                   .Read(read => read.Action("GetData", "Details").Type(HttpVerbs.Get))
                            .Update("Edit", "Details")

                )

        )


问:
How to check jenkins node connection status using jenkins-cli
I'm trying to check specific Jenkins node is connected using Jenkins CLI
. To get the node details I can use get-node command and it returns details as this xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<slave>
<name>20170602_jenkins_slave_002</name>
<description>10.49.82.46</description>
<remoteFS>c:\\jenkins_root</remoteFS>
<numExecutors>1</numExecutors>
<mode>EXCLUSIVE</mode>
<retentionStrategy class="hudson.slaves.RetentionStrategy$Always"/>
<launcher class="hudson.slaves.JNLPLauncher"/>
<label>20170602_jenkins_slave_002</label>
<nodeProperties/>
<userId>admin</userId>
</slave>
</code>```

But it does not includes the node status. Anyone has idea how to check the node status by Jenkins cli

答:
As I'm not aware of a method using jenkins-cli, my suggestion is to use the REST API:

```<code>http://jenkins.example.com/computer/:name/api/json
</code>```

returns JSON data including an offline field.

You can get an overview over all agents (called computer here) on the following URL:

```<code>http://jenkins.example.com/computer/api/json?pretty=true
</code>```

Body:
I'm trying to check specific Jenkins node is connected using Jenkins CLI
. To get the node details I can use get-node command and it returns details as this xml

<?xml version="1.0" encoding="UTF-8"?>
<slave>
<name>20170602_jenkins_slave_002</name>
<description>10.49.82.46</description>
<remoteFS>c:\\jenkins_root</remoteFS>
<numExecutors>1</numExecutors>
<mode>EXCLUSIVE</mode>
<retentionStrategy class="hudson.slaves.RetentionStrategy$Always"/>
<launcher class="hudson.slaves.JNLPLauncher"/>
20170602_jenkins_slave_002
<nodeProperties/>
<userId>admin</userId>
</slave>

But it does not includes the node status. Anyone has idea how to check the node status by Jenkins cli

Body:
As I'm not aware of a method using jenkins-cli, my suggestion is to use the REST API:

http://jenkins.example.com/computer/:name/api/json

returns JSON data including an offline field.

You can get an overview over all agents (called computer here) on the following URL:

http://jenkins.example.com/computer/api/json?pretty=true


问:
An ExtJS panel/tree/something else that polls
All I want is to display a list of records from a database table that are always up-to-date.

My initial thought was to have a constant ajax call every x seconds checking for updates, but wasnt sure if that was the best way to approach it. I have googled around, and such things as COMET, Ext.Direct, polling, pushing (comet?) have all come up.

What would be the best way to do this?

答: I find auto-updating information distracting at any rate of refresh. I would supply a link or button to refresh.</p>


问:
show json data from foreach in view using core php
this is json data :

```<code>{"activities":[{"id":"23442","title":"coldplay","author":"ekkk@abc.com","modified":"due","action":"updated","date":"2017-05-31 12:59:27","message":"Updated the due date to 2017-07-12 10:30:00"},{"id":"23650","title":"Task For Timesheet viewer ","author":"tkkl@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-31 09:51:35","message":"Accepted task"},{"id":"23650","title":"Task For Timesheet viewer ","author":"ekkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-31 09:50:55","message":"Accepted task"},{"id":"23607","title":"project 3","author":"ekkk@abc.com","modified":"status","action":"updated","date":"2017-05-30 15:40:11","message":"Deleted task"},{"id":"23645","title":"naiman bug 2","author":"ekkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-29 11:58:38","message":"Accepted task"},{"id":"23645","title":"naiman bug 2","author":"nkkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-29 11:58:07","message":"Accepted task"}]}
</code>```

To view this data in a table, i have used foreach loop in the view file. but it is not working showing, Warning: Invalid argument supplied for foreach(). This is how i did

```<code><tbody>
            <tr>
            <?php foreach($notifications as $key => $value) {     ?>
                        <td><?php echo $value ?></td>
                    <?php } ?>
            </tr>
        </tbody>
</code>```

答:
you have to convert your json to array using json_deode after you can use foreach to print data

```<code>   $notification = json_decode('{"activities":[{"id":"23442","title":"coldplay","author":"ekkk@abc.com","modified":"due","action":"updated","date":"2017-05-31 12:59:27","message":"Updated the due date to 2017-07-12 10:30:00"},{"id":"23650","title":"Task For Timesheet viewer ","author":"tkkl@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-31 09:51:35","message":"Accepted task"},{"id":"23650","title":"Task For Timesheet viewer ","author":"ekkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-31 09:50:55","message":"Accepted task"},{"id":"23607","title":"project 3","author":"ekkk@abc.com","modified":"status","action":"updated","date":"2017-05-30 15:40:11","message":"Deleted task"},{"id":"23645","title":"naiman bug 2","author":"ekkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-29 11:58:38","message":"Accepted task"},{"id":"23645","title":"naiman bug 2","author":"nkkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-29 11:58:07","message":"Accepted task"}]}');

foreach ($notification->activities as $key => $value)
{
    echo $value->id."<br>";
    echo $value->title."<br>";
}
</code>```

or just add true as second parameter to json decode then it will convert json to associate array so you can use it like your foreach

```<code>eg $notification = json_deocde('your_json',true);
</code>```

now you can use it as your foreach

Body:
this is json data :

{"activities":[{"id":"23442","title":"coldplay","author":"ekkk@abc.com","modified":"due","action":"updated","date":"2017-05-31 12:59:27","message":"Updated the due date to 2017-07-12 10:30:00"},{"id":"23650","title":"Task For Timesheet viewer ","author":"tkkl@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-31 09:51:35","message":"Accepted task"},{"id":"23650","title":"Task For Timesheet viewer ","author":"ekkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-31 09:50:55","message":"Accepted task"},{"id":"23607","title":"project 3","author":"ekkk@abc.com","modified":"status","action":"updated","date":"2017-05-30 15:40:11","message":"Deleted task"},{"id":"23645","title":"naiman bug 2","author":"ekkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-29 11:58:38","message":"Accepted task"},{"id":"23645","title":"naiman bug 2","author":"nkkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-29 11:58:07","message":"Accepted task"}]}

To view this data in a table, i have used foreach loop in the view file. but it is not working showing, Warning: Invalid argument supplied for foreach(). This is how i did

            <?php foreach($notifications as $key => $value) {     ?>
                        <?php echo $value ?>
                    <?php } ?>

Body:
you have to convert your json to array using json_deode after you can use foreach to print data

   $notification = json_decode('{"activities":[{"id":"23442","title":"coldplay","author":"ekkk@abc.com","modified":"due","action":"updated","date":"2017-05-31 12:59:27","message":"Updated the due date to 2017-07-12 10:30:00"},{"id":"23650","title":"Task For Timesheet viewer ","author":"tkkl@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-31 09:51:35","message":"Accepted task"},{"id":"23650","title":"Task For Timesheet viewer ","author":"ekkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-31 09:50:55","message":"Accepted task"},{"id":"23607","title":"project 3","author":"ekkk@abc.com","modified":"status","action":"updated","date":"2017-05-30 15:40:11","message":"Deleted task"},{"id":"23645","title":"naiman bug 2","author":"ekkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-29 11:58:38","message":"Accepted task"},{"id":"23645","title":"naiman bug 2","author":"nkkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-29 11:58:07","message":"Accepted task"}]}');

foreach ($notification->activities as $key => $value)
{
    echo $value->id."<br>";
    echo $value->title."<br>";
}

or just add true as second parameter to json decode then it will convert json to associate array so you can use it like your foreach

eg $notification = json_deocde('your_json',true);

now you can use it as your foreach


问:
Connect to Firebase failed with assistant in android studio
I want to connect my app to firebase and for that I am doing it by Firebase Assistant in android studio.

When I click on connect to firebase the following error is shown:

Firebase: Connect to Firebase failed. Please check your internet connection and try again. If errors persist, you can connect manually at https://console.firebase.google.com
  SocketTimeoutException: Could not obtain an OAuth2 access token.: connect timed out

Note: I am properly connected with internet and my android studio is updated.

How to solve this problem?

答: Check ur firebase console once, It happens that the  project gets created in firebase console but still it shows the error, If it is so, then go to project settings of that project and add the package name of the project in it, and then download the google-services.json file,add the json file in root project directory. Add the necessary dependencies for the feature u want to use from firebase assistant. U are all set to use firebase now!!..Hope it helps..</p>