问:
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!!

答:
You are not checking the segue identifier in prepareForSegue method.

Check it like this:

```<code>-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable    id)sender{
  if([segue.identifier isEqulaToString: @"x2"]){
    //x2 view controller settings
  }
  else if([segue.identifier isEqulaToString: @"b2"]){
    //b2 view controller settings
  }
}
</code>```

With this, you can have specific view controller and it's properties to set.

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!!

Body:
You are not checking the segue identifier in prepareForSegue method.

Check it like this:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable    id)sender{
  if([segue.identifier isEqulaToString: @"x2"]){
    //x2 view controller settings
  }
  else if([segue.identifier isEqulaToString: @"b2"]){
    //b2 view controller settings
  }
}

With this, you can have specific view controller and it's properties to set.


来源: stackexchange

问:
build database for a huge web portal
If I want to build a movie website similar to IMDB.
I can have the website up and running.
from the day I launch I can maintain the data upto date,
but my question, in my mind is How can i think of making the old data available say from 1900 to 2010

This is the challenge that I am facing, can any one share the knowledge how to go about this ?
Which Strategy I can follow to make a any website to make it to have old and as well as the on going News

Say the technology I can think to develop this website would be java, mysql, php

 How can i think of making the old data available say from 1900 to 2010 *
Means :  I would like to upload the All the movie data which is very old

答:
I don't see the problem here.  Just store the data for all movies in the database, and provide a way for the user to:

qualify his/her searches with a date range, and

order the results in date order.

I would like to upload the All the movie data which is very old

And is there any reason that you can't do this?  (Apart from the obvious one of not having the data in the first place ...)

FOLLOWUP

It sounds like the problem you are worrying about is one of incomplete or bad data.  There is no simple solution to that.  You probably need to devise a strategy for dealing with it; e.g.

upload everything, and then do batch validation / cleanup runs on the live database

as above, but hide records until have passed validation

validate each record as you attempt to upload, and put those that fail validation on one side.

You also need to be able to:

identify common validation problems, and perform bulk corrections,

change (e.g. tighten) the validation rules on the fly and revalidate.

But this is all standard stuff for a large data-oriented application.  (And there were easy solutions, everyone and their granny would be scraping the internet and building databases.  TANSTAAFL. )

ContentLicense: CC BY-SA 3.0

Title: build database for a huge web portal

ContentLicense: CC BY-SA 2.5


问:
loading data to Azure DW using Azure Data Factory
I am populating azure data warehouse with ADF and I need to prepare an incremental insert/update operation. My source can contain data that is already loaded to DW so I need to perform a check if data is loaded and perform an operation. Basically the idea is to fetch data everyday for past 7 days in case someone did update historical data.

At first I tried using copy activity with custom query on source and then on destination using stored procedure that will check by business key if record already exists or not and perform insert or update. But I cannot find how to process results of source query row per row and pass it to SP.

What would be best approach that will fit my case? Basically I am looking for SSIS inside azure cloud

答:
You need to land the loaded data into something like SQL DB first (if you aren't already). Then use a stored procedure on that to produce the merge style behaviour and deal with the 7 day window. Eg:

```<code>{
"name": "SprocActivitySamplePipeline",
"properties": {
    "activities": [
    {
    "type": "SqlServerStoredProcedure",
    "typeProperties": {
        "storedProcedureName": "sp_sample",
        "storedProcedureParameters": {
            "DateTime": "$$Text.Format('{0:yyyy-MM-dd HH:mm:ss}', SliceStart)"
        }
    }
</code>```

Source: https://learn.microsoft.com/en-us/azure/data-factory/data-factory-stored-proc-activity

In this case the ADF input and output datasets can be relational tables in the database.

ADF is not SSIS, sadly. But if you want to compare it think of it more like the SSIS control flow, rather than the data flow and ETL engine.

You'll therefore need a chain of activities to do what you require. In your screen shot above you have SQL DB already as the source so I'm a little confused as to what the actually problem is.

Maybe run the proc over the data in SQL DB first to a staged area. Then to the copy to SQL DW.

Hope this helps.

Body:
You need to land the loaded data into something like SQL DB first (if you aren't already). Then use a stored procedure on that to produce the merge style behaviour and deal with the 7 day window. Eg:

{
"name": "SprocActivitySamplePipeline",
"properties": {
    "activities": [
    {
    "type": "SqlServerStoredProcedure",
    "typeProperties": {
        "storedProcedureName": "sp_sample",
        "storedProcedureParameters": {
            "DateTime": "$$Text.Format('{0:yyyy-MM-dd HH:mm:ss}', SliceStart)"
        }
    }

Source: https://learn.microsoft.com/en-us/azure/data-factory/data-factory-stored-proc-activity

In this case the ADF input and output datasets can be relational tables in the database.

ADF is not SSIS, sadly. But if you want to compare it think of it more like the SSIS control flow, rather than the data flow and ETL engine.

You'll therefore need a chain of activities to do what you require. In your screen shot above you have SQL DB already as the source so I'm a little confused as to what the actually problem is.

Maybe run the proc over the data in SQL DB first to a staged area. Then to the copy to SQL DW.

Hope this helps.


问:
Awk Command not working as it should, output is wrong, sed command?
I tried this little script on my dataset and for some reason I am not getting the desired output? can someone have a look ? Maybe you can figure it out? Also if you could offer a SED command solution.

Script

```<code>awk -v RS= -F '<connection name="|<hostPort>' '
{
sub(/".*/, "", $2)
split($3, tokens, /[:<]/)
printf "%-6s %s %s\n", $2, tokens[1], tokens[2]
}
'
</code>```

input

```<code><hostPort>srv1:33333</hostPort>
<hostPort>srv2:33333</hostPort>
<connection name="boing_ny__Primary__" transport="tcp">
<hostPort>srv1:33333</hostPort>
<connection name="boing_ny__Backup__" transport="tcp">
<hostPort>srv2:33333</hostPort>
<connection name="boy_ny__Primary__" transport="tcp">
<hostPort>srv1:6666</hostPort>
<connection name="boy_ny__Backup__" transport="tcp">
<hostPort>srv2:6666</hostPort>
<connection name="song_ny__Primary__" transport="tcp">
<hostPort>srv1:55555</hostPort>
<connection name="song_ny__Backup__" transport="tcp">
<hostPort>srv2:55555</hostPort>
<connection name="bob_ny__Primary__" transport="tcp">
<hostPort>srv3:33333</hostPort>
<connection name="bob_ny__Backup__" transport="tcp">
<hostPort>srv4:33333</hostPort>
<hostPort>srv1:4444</hostPort>
<hostPort>srv2:4444</hostPort>
<hostPort>srv1:4444</hostPort>
</code>```

Current output

```<code>srv1:33333</hostPort>
srv2 33333
</code>```

desired output

```<code>boing_ny__Primary__  srv1 33333
boing_ny__Backup__   srv2 33333
boy_ny__Primary__     srv1 6666
boy_ny__Backup__   srv2 6666
song_ny__Primary__ srv1 55555
song_ny__Backup__ srv2 55555
bob_ny__Primary__ srv3 33333
bob_ny__Backup__ srv4 33333
</code>```

答:
As comments refer the right way to do the job is to use an appropriate parser.

As for experimenting, this GNU awk seems to do the job with your input data provided, but can not guarantee a robust solution since XML data can vary in your files.

```<code>awk '/connection name=/{a=$0;getline; \
print gensub(/(.*connection name=["])(.[^"]*)(["].*)/,"\\2","g",a), \
gensub(/(<.*>)(.[^:]*)([:])(.[^<]*)(<[/].*>)/,"\\2 \\4","g",$0)}' file1

#Output:
boing_ny__Primary__ srv1 33333
boing_ny__Backup__ srv2 33333
boy_ny__Primary__ srv1 6666
boy_ny__Backup__ srv2 6666
song_ny__Primary__ srv1 55555
song_ny__Backup__ srv2 55555
bob_ny__Primary__ srv3 33333
bob_ny__Backup__ srv4 33333
</code>```

How this works:

When we find a record containing /connection name=/ we store this record $0 to a variable a, we get next line with getline, and then we use and print two sed like substitutions using gensub:

```<code>gensub(/(.*connection name=["])(.[^"]*)(["].*)/,"\\2","g",a)
#all chars up to first " --|       |      |       |    |  |
#after " and up to the next "------|      |       |    |  |
#after last " up to the end of $0 --------|       |    |  |
#replace with group 2 ----------------------------|    |  |
#global replacement------------------------------------|  |
#target = a = previous record-----------------------------|

#With a = <connection name="boing_ny__Primary__" transport="tcp">
#Above gensub will return group2 = boing_ny__Primary__

gensub              (/(<.*>)(.[^:]*)([:])(.[^<]*)(<[/].*>)/,"\\2 \\4","g",$0)
#all chars between < >--|       |     |     |        |          |      |  |
#all chars up to : -------------|     |     |        |          |      |  |
#literal : ---------------------------|     |        |          |      |  |
#the part after : and before < -------------|        |          |      |  |
#the last < > part ----------------------------------|          |      |  |
#use group 2 and 4 ---------------------------------------------|      |  |
#global replacement ---------------------------------------------------|  |
#target = $0 current record ----------------------------------------------|

#With $0 = <hostPort>srv2:33333</hostPort>
#Above gensub will return group 2 = srv2 and group 4 = 33333 --> srv2 33333
</code>```

The general awk gensub synthax is gensub(regexp, replacement, how [, target]) and the substituted part is returned/applied on gensub function - see man page of gensub.

Body:
I tried this little script on my dataset and for some reason I am not getting the desired output? can someone have a look ? Maybe you can figure it out? Also if you could offer a SED command solution.

Script

awk -v RS= -F '<connection name="|<hostPort>' '
{
sub(/".*/, "", $2)
split($3, tokens, /[:<]/)
printf "%-6s %s %s\n", $2, tokens[1], tokens[2]
}
'

input

<hostPort>srv1:33333</hostPort>
<hostPort>srv2:33333</hostPort>
<connection name="boing_ny__Primary__" transport="tcp">
<hostPort>srv1:33333</hostPort>
<connection name="boing_ny__Backup__" transport="tcp">
<hostPort>srv2:33333</hostPort>
<connection name="boy_ny__Primary__" transport="tcp">
<hostPort>srv1:6666</hostPort>
<connection name="boy_ny__Backup__" transport="tcp">
<hostPort>srv2:6666</hostPort>
<connection name="song_ny__Primary__" transport="tcp">
<hostPort>srv1:55555</hostPort>
<connection name="song_ny__Backup__" transport="tcp">
<hostPort>srv2:55555</hostPort>
<connection name="bob_ny__Primary__" transport="tcp">
<hostPort>srv3:33333</hostPort>
<connection name="bob_ny__Backup__" transport="tcp">
<hostPort>srv4:33333</hostPort>
<hostPort>srv1:4444</hostPort>
<hostPort>srv2:4444</hostPort>
<hostPort>srv1:4444</hostPort>

Current output

srv1:33333</hostPort>
srv2 33333

desired output

boing_ny__Primary__  srv1 33333
boing_ny__Backup__   srv2 33333
boy_ny__Primary__     srv1 6666
boy_ny__Backup__   srv2 6666
song_ny__Primary__ srv1 55555
song_ny__Backup__ srv2 55555
bob_ny__Primary__ srv3 33333
bob_ny__Backup__ srv4 33333

Body:
As comments refer the right way to do the job is to use an appropriate parser.

As for experimenting, this GNU awk seems to do the job with your input data provided, but can not guarantee a robust solution since XML data can vary in your files.

awk '/connection name=/{a=$0;getline; \
print gensub(/(.*connection name=["])(.[^"]*)(["].*)/,"\\2","g",a), \
gensub(/(<.*>)(.[^:]*)([:])(.[^<]*)(<[/].*>)/,"\\2 \\4","g",$0)}' file1

#Output:
boing_ny__Primary__ srv1 33333
boing_ny__Backup__ srv2 33333
boy_ny__Primary__ srv1 6666
boy_ny__Backup__ srv2 6666
song_ny__Primary__ srv1 55555
song_ny__Backup__ srv2 55555
bob_ny__Primary__ srv3 33333
bob_ny__Backup__ srv4 33333

How this works:

When we find a record containing /connection name=/ we store this record $0 to a variable a, we get next line with getline, and then we use and print two sed like substitutions using gensub:

gensub(/(.*connection name=["])(.[^"]*)(["].*)/,"\\2","g",a)
#all chars up to first " --|       |      |       |    |  |
#after " and up to the next "------|      |       |    |  |
#after last " up to the end of $0 --------|       |    |  |
#replace with group 2 ----------------------------|    |  |
#global replacement------------------------------------|  |
#target = a = previous record-----------------------------|

#With a = <connection name="boing_ny__Primary__" transport="tcp">
#Above gensub will return group2 = boing_ny__Primary__

gensub              (/(<.*>)(.[^:]*)([:])(.[^<]*)(<[/].*>)/,"\\2 \\4","g",$0)
#all chars between < >--|       |     |     |        |          |      |  |
#all chars up to : -------------|     |     |        |          |      |  |
#literal : ---------------------------|     |        |          |      |  |
#the part after : and before < -------------|        |          |      |  |
#the last < > part ----------------------------------|          |      |  |
#use group 2 and 4 ---------------------------------------------|      |  |
#global replacement ---------------------------------------------------|  |
#target = $0 current record ----------------------------------------------|

#With $0 = <hostPort>srv2:33333</hostPort>
#Above gensub will return group 2 = srv2 and group 4 = 33333 --> srv2 33333

The general awk gensub synthax is gensub(regexp, replacement, how [, target]) and the substituted part is returned/applied on gensub function - see man page of gensub.


答:
try:

```<code>awk '/connection/{match($0,/"[^"]*/);VAL=substr($0,RSTART+1,RLENGTH-1);next} /hostPort/ && VAL{match($0,/>.*</);print VAL FS substr($0,RSTART+1,RLENGTH-2)}'   Input_file
</code>```

Will add explanation shortly.

EDIT2: Following is the explanation for same.

```<code>awk '/connection/{                                                    #### Looking for a line which has string connection in it.
                        match($0,/"[^"]*/);                           #### Using match function here to match a regex where it starts from " and looks for first occurrence of ".
                        VAL=substr($0,RSTART+1,RLENGTH-1);            #### Now creating a variable named VAL whose value is substring of RSTART and LENGTH, where RLENGTH and RSTART are the default keywords of awk and they will be SET when a REGEX match is found. RSTART will give the index of starting point of match and RLENGTH will give the length of that regex match.
                        next                                          #### Using next keyword to skip all further statements.
                 }
    /hostPort/ && VAL{                                                #### Checking here 2 conditions, it checks for a line which has hostport string and value of variable VAL is NOT NULL, if these conditions are TRUE then perform following actions.
                        match($0,/>.*</);                             #### using match function of awk to get the srv values so putting here regex so match from >.*< get everything between > to <.
                        print VAL FS substr($0,RSTART+1,RLENGTH-2)    #### printing value of VAL(which got created in previous condition) then printing the substring of RSTART and RLENGTH values here.
                     }
    '  Input_file                                                     #### Mentioning the Input_file here.
</code>```

Title: Awk Command not working as it should, output is wrong, sed command?

Body:
try:

awk '/connection/{match($0,/"[^"]*/);VAL=substr($0,RSTART+1,RLENGTH-1);next} /hostPort/ && VAL{match($0,/>.*</);print VAL FS substr($0,RSTART+1,RLENGTH-2)}'   Input_file

Will add explanation shortly.

EDIT2: Following is the explanation for same.

awk '/connection/{                                                    #### Looking for a line which has string connection in it.
                        match($0,/"[^"]*/);                           #### Using match function here to match a regex where it starts from " and looks for first occurrence of ".
                        VAL=substr($0,RSTART+1,RLENGTH-1);            #### Now creating a variable named VAL whose value is substring of RSTART and LENGTH, where RLENGTH and RSTART are the default keywords of awk and they will be SET when a REGEX match is found. RSTART will give the index of starting point of match and RLENGTH will give the length of that regex match.
                        next                                          #### Using next keyword to skip all further statements.
                 }
    /hostPort/ && VAL{                                                #### Checking here 2 conditions, it checks for a line which has hostport string and value of variable VAL is NOT NULL, if these conditions are TRUE then perform following actions.
                        match($0,/>.*</);                             #### using match function of awk to get the srv values so putting here regex so match from >.*< get everything between > to <.
                        print VAL FS substr($0,RSTART+1,RLENGTH-2)    #### printing value of VAL(which got created in previous condition) then printing the substring of RSTART and RLENGTH values here.
                     }
    '  Input_file                                                     #### Mentioning the Input_file here.


问:
Global search box extension - how to make browser to start when suggestion picked
I'm implementing global search box extension (sth like SearchableDictionary sample in android sdk). Everything works fine - suggestions are displayed properly. Problem is that I want browser to start when user picks a suggestion. (each suggestion is a link)

Columns of my cursor contain SearchManager.SUGGEST_COLUMN_INTENT_DATA, and I use that to pass http link. My searchable xml contains default intent action set to: android:searchSuggestIntentAction="android.intent.action.VIEW". But when user hits the suggestion, my application is started instead of browser. What am I missing?

Regards!

答:
Try to use this code. Rewrote the showResults function in the Searchable Dictionary sample code.</p>

```<code>private void showResults(String query) {
    Intent myIntent;

    myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(query));

    startActivity(myIntent);
    finish();
}
</code>```

Body:
Try to use this code. Rewrote the showResults function in the Searchable Dictionary sample code.

private void showResults(String query) {
    Intent myIntent;

    myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(query));

    startActivity(myIntent);
    finish();
}


问:
Using when and done and settimeout show hide div

function closecustomBox() {
  $('#dialog').hide();
}
$('#dialog').hide();
$('#anotherdialog').hide();
$("#show").click(function() {
  $('#dialog').show();
  $.when(
    setTimeout(function() {
      closecustomBox();
    }, 3000)
  ).done(function(x) {
    $('#anotherdialog').show();
  });
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#dialog {
  width: 101px;
  height: 101px;
  background-color: red;
}

#anotherdialog {
  width: 100px;
  height: 100px;
  background-color: blue;
}</code>```

show
```

What I want to happened is after clicking show will show the red box after 3 seconds the red box will hide then the blue box should show.

I want to achieve here is to not make the 2 div appear together

答:
Small change to your code..

function closecustomBox() {
  $('#dialog').hide();
}
$('#dialog').hide();
$('#anotherdialog').hide();
$("#show").click(function() {
  $('#dialog').show();
  //$.when(
    setTimeout(function() {
      closecustomBox();
      $('#anotherdialog').show();
    }, 3000)
  /*).done(function(x) {
    $('#anotherdialog').show();
  });*/
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#dialog {
  width: 101px;
  height: 101px;
  background-color: red;
}

#anotherdialog {
  width: 100px;
  height: 100px;
  background-color: blue;
}</code>```

show
```

Body:
function closecustomBox() {
  $('#dialog').hide();
}
$('#dialog').hide();
$('#anotherdialog').hide();
$("#show").click(function() {
  $('#dialog').show();
  $.when(
    setTimeout(function() {
      closecustomBox();
    }, 3000)
  ).done(function(x) {
    $('#anotherdialog').show();
  });
})

#dialog {
  width: 101px;
  height: 101px;
  background-color: red;
}

#anotherdialog {
  width: 100px;
  height: 100px;
  background-color: blue;
}

show

What I want to happened is after clicking show will show the red box after 3 seconds the red box will hide then the blue box should show.

I want to achieve here is to not make the 2 div appear together

Body:
Small change to your code..

function closecustomBox() {
  $('#dialog').hide();
}
$('#dialog').hide();
$('#anotherdialog').hide();
$("#show").click(function() {
  $('#dialog').show();
  //$.when(
    setTimeout(function() {
      closecustomBox();
      $('#anotherdialog').show();
    }, 3000)
  /*).done(function(x) {
    $('#anotherdialog').show();
  });*/
})

#dialog {
  width: 101px;
  height: 101px;
  background-color: red;
}

#anotherdialog {
  width: 100px;
  height: 100px;
  background-color: blue;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dialog"></div>

<div id="anotherdialog"></div>

<div id="show">show</div>


问:
Do I have to use a Git software or it's ok to use just the command line?
I always like the Command Line Environment because you feel like you have control on every thing. But is it necessary to use a software for using Git? How do companies handle this? Do they use CLI or do they use softwares?</p>

答:
It's ok to know the tool you chose.

I've seen companies that only works with CLI and others that also works with tools. Often, ... who only uses the tool, at some point do not know how to solve exceptions, conflicts, or something like that.

My suggestion is to learn the main tool (git). After that, just use the tool tailored on you. The purpose in your daily work is not to use a tool or another. The purpose is to create value and good software.


问:
C# Coding a Tie in Tic Tac Toe
I've developed a game of tic tac toe in C# and set a function for the win conditions, but I can't seem to figure out how to set the condition for a tie when the grid is full. When I tried to input, the tie would occur randomly. I wonder if it's how I set the or and and operators.Here's what I tried. </p>

```<code>public bool Ended()
{
    if (grid[0, 0] == 'X' && grid[0, 1] == 'X' && grid[0, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[1, 0] == 'X' && grid[1, 1] == 'X' && grid[1, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[2, 0] == 'X' && grid[2, 1] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'X' && grid[1, 0] == 'X' && grid[2, 0] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 1] == 'X' && grid[1, 1] == 'X' && grid[2, 1] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 2] == 'X' && grid[1, 2] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'X' && grid[1, 1] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 2] == 'X' && grid[1, 1] == 'X' && grid[2, 0] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[0, 1] == 'O' && grid[0, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[1, 0] == 'O' && grid[1, 1] == 'O' && grid[1, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[2, 0] == 'O' && grid[2, 1] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[1, 0] == 'O' && grid[2, 0] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 1] == 'O' && grid[1, 1] == 'O' && grid[2, 1] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 2] == 'O' && grid[1, 2] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[1, 1] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 2] == 'O' && grid[1, 1] == 'O' && grid[2, 0] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    else if (grid[0, 0] == 'X' || grid[0, 0] == 'O' &&
        grid[0, 1] == 'X' || grid[0, 1] == 'O' &&
        grid[0, 2] == 'X' || grid[0, 2] == 'O' &&
        grid[1, 0] == 'X' || grid[1, 0] == 'O' &&
        grid[1, 1] == 'X' || grid[1, 1] == 'O' &&
        grid[1, 2] == 'X' || grid[1, 2] == 'O' &&
        grid[2, 0] == 'X' || grid[2, 0] == 'O' &&
        grid[2, 1] == 'X' || grid[2, 1] == 'O' &&
        grid[2, 2] == 'X' || grid[2, 2] == 'O')
    { Console.WriteLine("It's a Tie"); return true; }
    return false;
}
</code>```

答:
Here's a way to check. First create all 8 slices of the grid:

```<code>var slices =
    Enumerable
        .Range(0, 3)
        .SelectMany(i => new []
        {
            Enumerable.Range(0, 3).Select(j => grid[i, j]),
            Enumerable.Range(0, 3).Select(j => grid[j, i])
        })
        .Concat(new [] { Enumerable.Range(0, 3).SelectMany(i => new [] { grid[i, i] }) })
        .Concat(new [] { Enumerable.Range(0, 3).SelectMany(i => new [] { grid[i, 2 - i] }) })
        .Select(z => String.Join("", z))
        .ToArray();
</code>```

Starting with this input:

```<code>char[,] grid = new char[3, 3]
{
    { 'X', 'O', 'X' },
    { 'O', 'X', 'X' },
    { 'X', 'X', 'O' },
};
</code>```

That'll give you:

Now it's easy to see who wins:

```<code>bool xWins = slices.Any(z => z == "XXX") && slices.All(z => z != "OOO");
bool oWins = slices.Any(z => z == "OOO") && slices.All(z => z != "XXX");
</code>```

And to see if the board is a draw check that both are false and if there are any empty spots (assuming that _ is empty):

```<code>bool draw = !xWins && !oWins && slices.All(z => !z.Contains("_"));
</code>```

Title: C# Coding a Tie in Tic Tac Toe

Body:
I've developed a game of tic tac toe in C# and set a function for the win conditions, but I can't seem to figure out how to set the condition for a tie when the grid is full. When I tried to input, the tie would occur randomly. I wonder if it's how I set the or and and operators.Here's what I tried.

public bool Ended()
{
    if (grid[0, 0] == 'X' && grid[0, 1] == 'X' && grid[0, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[1, 0] == 'X' && grid[1, 1] == 'X' && grid[1, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[2, 0] == 'X' && grid[2, 1] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'X' && grid[1, 0] == 'X' && grid[2, 0] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 1] == 'X' && grid[1, 1] == 'X' && grid[2, 1] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 2] == 'X' && grid[1, 2] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'X' && grid[1, 1] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 2] == 'X' && grid[1, 1] == 'X' && grid[2, 0] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[0, 1] == 'O' && grid[0, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[1, 0] == 'O' && grid[1, 1] == 'O' && grid[1, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[2, 0] == 'O' && grid[2, 1] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[1, 0] == 'O' && grid[2, 0] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 1] == 'O' && grid[1, 1] == 'O' && grid[2, 1] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 2] == 'O' && grid[1, 2] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[1, 1] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 2] == 'O' && grid[1, 1] == 'O' && grid[2, 0] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    else if (grid[0, 0] == 'X' || grid[0, 0] == 'O' &&
        grid[0, 1] == 'X' || grid[0, 1] == 'O' &&
        grid[0, 2] == 'X' || grid[0, 2] == 'O' &&
        grid[1, 0] == 'X' || grid[1, 0] == 'O' &&
        grid[1, 1] == 'X' || grid[1, 1] == 'O' &&
        grid[1, 2] == 'X' || grid[1, 2] == 'O' &&
        grid[2, 0] == 'X' || grid[2, 0] == 'O' &&
        grid[2, 1] == 'X' || grid[2, 1] == 'O' &&
        grid[2, 2] == 'X' || grid[2, 2] == 'O')
    { Console.WriteLine("It's a Tie"); return true; }
    return false;
}

Body:
Here's a way to check. First create all 8 slices of the grid:

var slices =
    Enumerable
        .Range(0, 3)
        .SelectMany(i => new []
        {
            Enumerable.Range(0, 3).Select(j => grid[i, j]),
            Enumerable.Range(0, 3).Select(j => grid[j, i])
        })
        .Concat(new [] { Enumerable.Range(0, 3).SelectMany(i => new [] { grid[i, i] }) })
        .Concat(new [] { Enumerable.Range(0, 3).SelectMany(i => new [] { grid[i, 2 - i] }) })
        .Select(z => String.Join("", z))
        .ToArray();

Starting with this input:

char[,] grid = new char[3, 3]
{
    { 'X', 'O', 'X' },
    { 'O', 'X', 'X' },
    { 'X', 'X', 'O' },
};

That'll give you:

Now it's easy to see who wins:

bool xWins = slices.Any(z => z == "XXX") && slices.All(z => z != "OOO");
bool oWins = slices.Any(z => z == "OOO") && slices.All(z => z != "XXX");

And to see if the board is a draw check that both are false and if there are any empty spots (assuming that _ is empty):

bool draw = !xWins && !oWins && slices.All(z => !z.Contains("_"));


问:
React: What is the naming convention to inform the return type of the function is jsx in the comments?
I believe most of the developers follow guidelines rolled out by JSDocs for commenting in JavaScript. So, this is how I usually provide comments for the function I create to help other developers who might work on the same file:

```<code>  /**
   * Renders the translated section in sidebar.
   *
   * @param {array} langList - List of languages to be rendered
   * @param {boolean} isTranslated - If true render translations
   * @return {JSX} - Returns JSX
   */
  _renderLangSection (langList, isTranslated) {
    return (
      <div>{isTranslated ? langlist : null}</div>
    );
  }
</code>```

As you can see the return type of this function is JSX. Is this the right return type? Or is React element a better name? Does anyone know what the React community prefers?

答:
It doesn't matter if you call the return type to be JSX as after this function gets compiled with Babel, the JSX code gets transformed to pure javascript as

```<code>function _renderLangSection (langList, isTranslated) {
  return React.createElement("div", null, isTranslated ? langlist : null);
}
</code>```

which ultimately returns a React element.

Body:
I believe most of the developers follow guidelines rolled out by JSDocs for commenting in JavaScript. So, this is how I usually provide comments for the function I create to help other developers who might work on the same file:

  /**
   * Renders the translated section in sidebar.
   *
   * @param {array} langList - List of languages to be rendered
   * @param {boolean} isTranslated - If true render translations
   * @return {JSX} - Returns JSX
   */
  _renderLangSection (langList, isTranslated) {
    return (

{isTranslated ? langlist : null}

    );
  }

As you can see the return type of this function is JSX. Is this the right return type? Or is React element a better name? Does anyone know what the React community prefers?

Body:
It doesn't matter if you call the return type to be JSX as after this function gets compiled with Babel, the JSX code gets transformed to pure javascript as

function _renderLangSection (langList, isTranslated) {
  return React.createElement("div", null, isTranslated ? langlist : null);
}

which ultimately returns a React element.


答:
No, it's not necessary for obvious reasons. It's just a personal preference and you might find using a nice and tidy UI to be a lot more convenient, especially if you're new to the whole concept.

Behind the scenes pretty much any graphical user interface I know will just execute the actual command line tools so they don't have to reimplement everything in their own code.

So in the end, everyone runs the command line tools, even if they don't know it.

Personal opinion: If you're new and are just getting started, there's nothing wrong in using a graphical version to help you get along.

But once you know the basics, it won't hurt knowing the basics and how to do them on the command line:

Initialize a new repository

Clone an existing repository

Push and pull changes

Stage changes and commit them

Create, switch, and delete branches

Add, modify, and remove remotes

Once you know these, you should be able to handle your way around using command line only for pretty much all common tasks. You'll be a lot faster that way and it's a lot easier to automate things compared to a GUI client.

Title: Do I have to use a Git software or it's ok to use just the command line?

Body: I always like the Command Line Environment because you feel like you have control on every thing. But is it necessary to use a software for using Git? How do companies handle this? Do they use CLI or do they use softwares?


问:
How to add different constraints depend on iPhone screen size?
This is my xib file viewed as iPhone6/iPhone7,it looks good.

but if i turn it into iPhoneSE,it becomes abnormal.

Becasue the space blank doesn't change when the device changes,and i can not change the space constraint adapting to device without code.

答:
Try following constraints:

Output: iPhone 6/7

Output: iPhone SE

Specify your requirements more clearly, so that I can help you more.


问:
Move ImageView from one layout to another layout within same activity using animation
I want to translate this imageview from relative_bottom to relative_top layout through animation. I want to put that image in center of relative_top layout. this is my splashscreen so i want this to transit automatically.

here is hiiii as imageview.I want to animate this automatically:

I want to place this image here with animation

I dont know how to set exact position.

What should I add to get such output? I have tried many ways but couldn't get a solution.

Sample xml file:

```<code><LinearLayout android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       android:background="@drawable/background"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/bg"
            android:layout_weight="2"
            android:layout_gravity="center"
            android:id="@+id/relative_top"
            android:orientation="vertical">

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:paddingLeft="50dp"
            android:paddingRight="50dp"
            android:id="@+id/bottom"
            android:layout_gravity="center_horizontal"
            android:gravity="top">
            <ProgressBar>
               ....
               </Progressbar>
            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/relative_bottom"
                android:layout_alignTop="@id/progressBar"
                android:layout_centerInParent="true"
                >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/imageview"
                    android:src="@drawable/logo"
                    android:scaleType="fitCenter"
                    />

            </RelativeLayout>

        </RelativeLayout>

</LinearLayout>
</code>```

答:
First create an xml for the animation:

fab_show.xml

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><!--Move-->
<translate
    android:duration="650"
    android:fromXDelta="650%"
    android:fromYDelta="350%"
    android:interpolator="@android:anim/linear_interpolator"
    android:toXDelta="0%"
    android:toYDelta="0%">

</translate>
</code>```

fromXDelta and fromYDelta is the starting position of the imageView (a FAB in my case) which you can adjust according to your requirement and toXDelta, toYDelta is the position where you want the item to be after the completion of animation.

Here is how you use this animation:

```<code> private ImageView img;

Animation fab_show = AnimationUtils.loadAnimation(getApplication(), R.anim.hsfab1_show);
</code>```

To trigger the animation:

```<code>img = (ImageView) findViewById(R.id.your_imageview);
img.startAnimation(fab_show);
</code>```

Body:
I want to translate this imageview from relative_bottom to relative_top layout through animation. I want to put that image in center of relative_top layout. this is my splashscreen so i want this to transit automatically.

here is hiiii as imageview.I want to animate this automatically:

I want to place this image here with animation

I dont know how to set exact position.

What should I add to get such output? I have tried many ways but couldn't get a solution.

Sample xml file:

<LinearLayout android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       android:background="@drawable/background"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/bg"
            android:layout_weight="2"
            android:layout_gravity="center"
            android:id="@+id/relative_top"
            android:orientation="vertical">

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:paddingLeft="50dp"
            android:paddingRight="50dp"
            android:id="@+id/bottom"
            android:layout_gravity="center_horizontal"
            android:gravity="top">
            <ProgressBar>
               ....
               </Progressbar>
            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/relative_bottom"
                android:layout_alignTop="@id/progressBar"
                android:layout_centerInParent="true"
                >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/imageview"
                    android:src="@drawable/logo"
                    android:scaleType="fitCenter"
                    />

            </RelativeLayout>

        </RelativeLayout>

</LinearLayout>

Body:
First create an xml for the animation:

fab_show.xml

<?xml version="1.0" encoding="utf-8"?>

<!--Move-->
<translate
    android:duration="650"
    android:fromXDelta="650%"
    android:fromYDelta="350%"
    android:interpolator="@android:anim/linear_interpolator"
    android:toXDelta="0%"
    android:toYDelta="0%">

</translate>

fromXDelta and fromYDelta is the starting position of the imageView (a FAB in my case) which you can adjust according to your requirement and toXDelta, toYDelta is the position where you want the item to be after the completion of animation.

Here is how you use this animation:

 private ImageView img;

Animation fab_show = AnimationUtils.loadAnimation(getApplication(), R.anim.hsfab1_show);

To trigger the animation:

img = (ImageView) findViewById(R.id.your_imageview);
img.startAnimation(fab_show);


问:
adding multiplied numbers using javascript

function multiplyBy()
{
        num1 = document.getElementById("firstNumber").value;
        num2 = document.getElementById("secondNumber").value;
       num3= document.getElementById("result").value = num1 * num2;
       document.getElementById("total").value = +num3 ;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" value="" onchange="multiplyBy()" /><br>
<p>The Result is : <br>
<input type="text" name="result" id = "result" value=""/>
</p>
<p>Total :<br>
<input type="text" name="total" id="total" value=""/>
</p></code>```

function multiplyBy()
{
        num1 = document.getElementById("firstNumber").value;
        num2 = document.getElementById("secondNumber").value;
       num3= document.getElementById("result").value = num1 * num2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" value=""
onchange="multiplyBy()" /><br>
<p>The Result is : <br>
<input type="text" name="result" id = "result" value=""/>
</p></code>```

I am multiplying two numbers here.how to add those multiplied numbers in another text box.suppose 2&5 are multiplied later 4&6 multiplied how to add those numbers.

答:
Try this. You need to parse the input value using parseFloat. This will convert the string to a number. The existing result value is added to the newly calculating value. |0 is used for the false value of input getting 0

Updated

prev, present and total result box were added

Append each additional input with new result.

var last=0;
function multiplyBy() {
  var num1 = document.getElementById("firstNumber");
  var num2 = document.getElementById("secondNumber");
  var prev = document.getElementById("prev");
  var present = document.getElementById("present");
  var total = document.getElementById("result");
  prev.value=last;
  present.value=(parseFloat(num1.value) * parseFloat(num2.value))
  last = last+(parseFloat(num1.value) * parseFloat(num2.value))
  total.value=last;
  num1.value = "";
  num2.value = "";

  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>1st Number : <input type="text" id="firstNumber" value="" /><br> 2nd Number: <input type="text" id="secondNumber" value="" onchange="multiplyBy()" /><br>
<p >
Prev result:<br>
<input type="text" name="result"  id="prev" ><br>
Present:<br>
<input type="text" name="result"  id="present" ><br>
The total Result is : <br>
<input type="text" name="result"  id="result"><br>
</p></code>```

Body:
function multiplyBy()
{
        num1 = document.getElementById("firstNumber").value;
        num2 = document.getElementById("secondNumber").value;
       num3= document.getElementById("result").value = num1 * num2;
       document.getElementById("total").value = +num3 ;
}

1st Number : <input type="text" id="firstNumber" value="" />

2nd Number: <input type="text" id="secondNumber" value="" onchange="multiplyBy()" />

The Result is :

<input type="text" name="result" id = "result" value=""/>

Total :

<input type="text" name="total" id="total" value=""/>

function multiplyBy()
{
        num1 = document.getElementById("firstNumber").value;
        num2 = document.getElementById("secondNumber").value;
       num3= document.getElementById("result").value = num1 * num2;
}

1st Number : <input type="text" id="firstNumber" value="" />

2nd Number: <input type="text" id="secondNumber" value=""
onchange="multiplyBy()" />

The Result is :

<input type="text" name="result" id = "result" value=""/>

I am multiplying two numbers here.how to add those multiplied numbers in another text box.suppose 2&5 are multiplied later 4&6 multiplied how to add those numbers.

Body:
Try this. You need to parse the input value using parseFloat. This will convert the string to a number. The existing result value is added to the newly calculating value. |0 is used for the false value of input getting 0

Updated

prev, present and total result box were added

Append each additional input with new result.

var last=0;
function multiplyBy() {
  var num1 = document.getElementById("firstNumber");
  var num2 = document.getElementById("secondNumber");
  var prev = document.getElementById("prev");
  var present = document.getElementById("present");
  var total = document.getElementById("result");
  prev.value=last;
  present.value=(parseFloat(num1.value) * parseFloat(num2.value))
  last = last+(parseFloat(num1.value) * parseFloat(num2.value))
  total.value=last;
  num1.value = "";
  num2.value = "";

  }

1st Number : <input type="text" id="firstNumber" value="" /><br> 2nd Number: <input type="text" id="secondNumber" value="" onchange="multiplyBy()" /><br>
<p >
Prev result:<br>
<input type="text" name="result"  id="prev" ><br>
Present:<br>
<input type="text" name="result"  id="present" ><br>
The total Result is : <br>
<input type="text" name="result"  id="result"><br>
</p>


问:
jQuery: Why do hidden table cells get (sort of) shown again when I measure their height in FF3 and Chrome
I can successfully hide some table cells using jQuery. When I then measure the height of a hidden cell, the space that the cell would occupy if not hidden appears as blank space, pushing all the remaining cells in that row across by one column. It's as if the the cell is reinserted in the table flow, but its content is hidden. The example below demonstrates the problem. Click "hide column 2" followed by "measure row 1 column 2" to see it happen. The example code is standalone - just save it as an HTML file.

This affects FF3 and Chrome, but not IE7.

```<code><html>
<head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("a.clickToHide").click(function() {
                $(".col2").hide();
            });
            $("a.clickToMeasure").click(function() {
                $("span.result").text($("tr.row1 td.col2").height());
            });
        });
    </script>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th class="col1"> Column 1 </th>
                <th class="col2"> Column 2 </th>
                <th class="col3"> Column 3 </th>
            </tr>
        </thead>
        <tbody>
            <tr class="row1">
                <td class="col1"> Column 1 </th>
                <td class="col2"> Column 2 </th>
                <td class="col3"> Column 3 </th>
            </tr>
            <tr class="row2">
                <td class="col1"> Column 1 </th>
                <td class="col2"> Column 2 </th>
                <td class="col3"> Column 3 </th>
            </tr>
        </tbody>
    </table>
    <a class="clickToHide" href="#">Click to hide column 2</a> <br />
    <a class="clickToMeasure" href="#">Click to measure row 1 column 2</a> <br />
    <span class="result"></span>
</body>
</code>```

答:
Interesting results while looking into this.  First, you can accomplish what you want by refining your selector.

Second, I decided to dig into the jquery source to understand why your selector causes the issue.  What I found was that the table cell is being made visible "display: block;" in the "swap" function.  It appears to do so do get correct calculations (comments).  After it is made visible and calculations are performed correctly the function attempts to revert the visible status back.  But the reversing doesn't take affect.  I think it's definitely a browser issue because the object values are accurate.

OwnerDisplayName: Alex Scordellis

Body:
I can successfully hide some table cells using jQuery. When I then measure the height of a hidden cell, the space that the cell would occupy if not hidden appears as blank space, pushing all the remaining cells in that row across by one column. It's as if the the cell is reinserted in the table flow, but its content is hidden. The example below demonstrates the problem. Click "hide column 2" followed by "measure row 1 column 2" to see it happen. The example code is standalone - just save it as an HTML file.

This affects FF3 and Chrome, but not IE7.

                 Column 1
                 Column 2
                 Column 3

                 Column 1
                 Column 2
                 Column 3

                 Column 1
                 Column 2
                 Column 3

    Click to hide column 2

    Click to measure row 1 column 2


问:
How to get the previous value of int[] to be added by two int values using java 5
I want to get the sum of the stored int values of int[] array. the code still have errors. are there any codes that would make this line of codes look simplified? I want to make the 52 weeks money challenge app without database.

I have this formula: iA + sum = total[] + aA = tA;

I am having an error of the previous value not being added by preceding value.

PS. weeks, iA (Initial Amount), aA (Adding Amount), sum, sT are int. the tA's are now being added to the total[].

PSS: For everyone who flagged this question which have duplicate question, I already saw that question and it doesn't answer what my question is. The post have its own values created by the programmer/coder, I am asking for how to add the previous element to the values of two added integer values. I already tried the solution given in that question, and it's not working for my code. It gives different value (the unwanted value).

```<code>int[] total = new int[weeks + 1];
        int sum = 0;
        int tA = 0;
        int ai = 0;

        for(int sT = 1 ; sT <= weeks; sT++){ // error
            sum += iA;
            System.out.println("The payable for the week " + sT + " is: " + sum);
            total[sT] = sum;
            tA = total[sT];
            if(sT == 1){
                System.out.println("if: " + tA);
            }
            else if(sT == 2){
                tA += iA;
                System.out.println("else if: " + tA);
            }
            else{
                tA += aA;
                System.out.println("else: " + tA);
            }
        }
    System.out.println(Arrays.toString(total)); //print stored values of array
</code>```

答:
If you are on Java 8, you can use

```<code>int sum = Arrays.stream(total).sum();
</code>```

Otherwise the old fashioned way

```<code>for( int i : total) {
    sum += i;
}
</code>```

Body:
I want to get the sum of the stored int values of int[] array. the code still have errors. are there any codes that would make this line of codes look simplified? I want to make the 52 weeks money challenge app without database.

I have this formula: iA + sum = total[] + aA = tA;

I am having an error of the previous value not being added by preceding value.

PS. weeks, iA (Initial Amount), aA (Adding Amount), sum, sT are int. the tA's are now being added to the total[].

PSS: For everyone who flagged this question which have duplicate question, I already saw that question and it doesn't answer what my question is. The post have its own values created by the programmer/coder, I am asking for how to add the previous element to the values of two added integer values. I already tried the solution given in that question, and it's not working for my code. It gives different value (the unwanted value).

int[] total = new int[weeks + 1];
        int sum = 0;
        int tA = 0;
        int ai = 0;

        for(int sT = 1 ; sT <= weeks; sT++){ // error
            sum += iA;
            System.out.println("The payable for the week " + sT + " is: " + sum);
            total[sT] = sum;
            tA = total[sT];
            if(sT == 1){
                System.out.println("if: " + tA);
            }
            else if(sT == 2){
                tA += iA;
                System.out.println("else if: " + tA);
            }
            else{
                tA += aA;
                System.out.println("else: " + tA);
            }
        }
    System.out.println(Arrays.toString(total)); //print stored values of array

Body:
If you are on Java 8, you can use

int sum = Arrays.stream(total).sum();

Otherwise the old fashioned way

for( int i : total) {
    sum += i;
}


答:
I have added the multiplyBy() to both the input fields and changed the type to number to restrict the user to enter number only.

Please check the code snippet below.

document.getElementById("firstNumber").addEventListener("change",multiplyBy);
document.getElementById("secondNumber").addEventListener("change",multiplyBy);

function multiplyBy()
    {
    actualResult = document.getElementById("actualResult").value ? document.getElementById("actualResult").value : 0; // Return zero if there is no value in actualResult input field
            num1 = document.getElementById("firstNumber").value;
            num2 = document.getElementById("secondNumber").value;
           num3= document.getElementById("result").value = num1 * num2;
 document.getElementById("actualResult").value = Number(actualResult) + num3;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> 1st Number : <input type="number" id="firstNumber" value=""/><br>
    2nd Number: <input type="number" id="secondNumber" value=""/><br>
    <p>The Current Result is : <br>
    <input type="number" name="result" id = "result" value=""/>
 </p>
   <p>Previous Result + Current Result : <br>
    <input type="number" name="actualResult" id = "actualResult" value=""/>
    </p></code>```

Title: adding multiplied numbers using javascript

Body:
I have added the multiplyBy() to both the input fields and changed the type to number to restrict the user to enter number only.

Please check the code snippet below.

document.getElementById("firstNumber").addEventListener("change",multiplyBy);
document.getElementById("secondNumber").addEventListener("change",multiplyBy);

function multiplyBy()
    {
    actualResult = document.getElementById("actualResult").value ? document.getElementById("actualResult").value : 0; // Return zero if there is no value in actualResult input field
            num1 = document.getElementById("firstNumber").value;
            num2 = document.getElementById("secondNumber").value;
           num3= document.getElementById("result").value = num1 * num2;
 document.getElementById("actualResult").value = Number(actualResult) + num3;
    }

 1st Number : <input type="number" id="firstNumber" value=""/><br>
    2nd Number: <input type="number" id="secondNumber" value=""/><br>
    <p>The Current Result is : <br>
    <input type="number" name="result" id = "result" value=""/>
 </p>
   <p>Previous Result + Current Result : <br>
    <input type="number" name="actualResult" id = "actualResult" value=""/>
    </p>


问:
Navigation drawer item icon not showing original colour
I'm trying to show an icon next to an item within my menu for my navigation drawer, but for some reason the icon always appears in grey rather than the original colour (brown). Is there any way of preventing this from happening in order to show the icon's original colour?

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        if (navigationView != null) {
            setupDrawerContent(navigationView);
        }
    }

    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                mDrawerLayout.closeDrawers();

                return true;
            }
        });
    }
}
</code>```

drawer_view.xml

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:title="Section">
        <menu>
            <item
                android:id="@+id/navigation_item_1"
                android:icon="@drawable/ic_browncircle"
                android:title="Sub item 1" />
        </menu>
    </item>
</menu>
</code>```

答:
Just add one line in xml

app:itemIconTint="@color/white"

Body:
I'm trying to show an icon next to an item within my menu for my navigation drawer, but for some reason the icon always appears in grey rather than the original colour (brown). Is there any way of preventing this from happening in order to show the icon's original colour?

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        if (navigationView != null) {
            setupDrawerContent(navigationView);
        }
    }

    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                mDrawerLayout.closeDrawers();

                return true;
            }
        });
    }
}

drawer_view.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:title="Section">
        <menu>
            <item
                android:id="@+id/navigation_item_1"
                android:icon="@drawable/ic_browncircle"
                android:title="Sub item 1" />
        </menu>
    </item>
</menu>


答: From what I saw, it's a matter of taste to some companies. I've worked with 3 different companies with 3 different version controls: svn, git and tfvc and we did not use the CLI almost at all. It depends a lot on the company culture but from what I saw, the emphasis should be on knowing your tolling and being able to be productive with it. </p>


问:
Android ViewPager does not show content after first time
I am working on a drawer app with fragments. One of the options in the drawers calls a fragment in which I set up a tabbed view (with fragments) that show graphs.

When I run the app for the first time, my tabs work perfectly fine, contents, graph and everything looks great.

As soon as I click away from that fragment and go to any other fragment, and come back, the tabs show up with correct titles, but no contents, no graph nothing.

Here is my main fragment that sets up the viewpager:

```<code>import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

public class StatsMain extends Fragment {
    private ViewPagerAdapter adapter = null;
    private TabLayout tabLayout = null;
    private ViewPager viewPager = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    return inflater.inflate(R.layout.stats_main, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    viewPager = (ViewPager) view.findViewById(R.id.viewpager);
    tabLayout = (TabLayout) view.findViewById(R.id.tabs);

    setupViewPager(viewPager);
    tabLayout.setupWithViewPager(viewPager);

}

private void setupViewPager(ViewPager viewPager) {
    adapter = new ViewPagerAdapter(getFragmentManager());
    adapter.addFragment(new Stats1(), "Stats 1");
    adapter.addFragment(new Stats2(), "Stats 2");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}
}
</code>```

And here is my layout for it:

```<code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"  />

</android.support.design.widget.CoordinatorLayout>
</code>```

This is one of my Stats() fragments. The second one looks very similar:

```<code>public class Stats1 extends Fragment {
GraphView graph;
public Stats1 () {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    return inflater.inflate(R.layout.stats1, container, false);

}

@Override
public void onViewCreated(View view, Bundle savedInstanceState){
    Calendar calendar = Calendar.getInstance();
    Date d1 = calendar.getTime();
    calendar.add(Calendar.DATE, 1);
    Date d2 = calendar.getTime();
    calendar.add(Calendar.DATE, 1);
    Date d3 = calendar.getTime();
    calendar.add(Calendar.DATE, 1);
    Date d4 = calendar.getTime();
    calendar.add(Calendar.DATE, 1);
    Date d5 = calendar.getTime();

    graph = (GraphView) view.findViewById(R.id.graph);
    StaticLabelsFormatter staticLabelsFormatter = new
StaticLabelsFormatter(graph);

    staticLabelsFormatter.setHorizontalLabels(new String[] {"old", "middle", "new"});

    graph.setTitle("Data History");
    LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(new DataPoint[] {
            new DataPoint(d1, 145.4),
            new DataPoint(d2, 145.9),
            new DataPoint(d3, 147.2),
            new DataPoint(d4, 146.5),
            new DataPoint(d5, 147.1)
    });

    graph.getViewport().setScalable(true);

    graph.addSeries(series);
// set date label formatter
    //graph.getGridLabelRenderer().setLabelFormatter(new
DateAsXAxisLabelFormatter(this));
    graph.getGridLabelRenderer().setLabelFormatter(staticLabelsFormatter);

    //graph.getGridLabelRenderer().setNumHorizontalLabels(6); // only 4 because of the space
    series.setDrawDataPoints(true);

// set manual x bounds to have nice steps
    graph.getViewport().setMinX(d1.getTime());
    graph.getViewport().setMaxX(d5.getTime());
    graph.getViewport().setXAxisBoundsManual(true);

// as we use dates as labels, the human rounding to nice readable numbers
// is not necessary
    graph.getGridLabelRenderer().setHumanRounding(false);
}
</code>```

I use appsthatmatter/GraphView for graphing purposes.

I tried debugging it and I found out that after I navigate away from the tabs and come back, the function:

```<code>    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }
</code>```

won't get called anymore. It does twice the first time around but it never will  until i properly close the app and restart.

Can anybody help me figure out what I'm not doing right, please?

Thanks

答:
I actually fixed it. I had to change: </p>

```<code>adapter = new ViewPagerAdapter(getFragmentManager());
</code>```

<p>to </p>

```<code>adapter = new ViewPagerAdapter(getChildFragmentManager());
</code>```

Body:
I am working on a drawer app with fragments. One of the options in the drawers calls a fragment in which I set up a tabbed view (with fragments) that show graphs.

When I run the app for the first time, my tabs work perfectly fine, contents, graph and everything looks great.

As soon as I click away from that fragment and go to any other fragment, and come back, the tabs show up with correct titles, but no contents, no graph nothing.

Here is my main fragment that sets up the viewpager:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

public class StatsMain extends Fragment {
    private ViewPagerAdapter adapter = null;
    private TabLayout tabLayout = null;
    private ViewPager viewPager = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    return inflater.inflate(R.layout.stats_main, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    viewPager = (ViewPager) view.findViewById(R.id.viewpager);
    tabLayout = (TabLayout) view.findViewById(R.id.tabs);

    setupViewPager(viewPager);
    tabLayout.setupWithViewPager(viewPager);

}

private void setupViewPager(ViewPager viewPager) {
    adapter = new ViewPagerAdapter(getFragmentManager());
    adapter.addFragment(new Stats1(), "Stats 1");
    adapter.addFragment(new Stats2(), "Stats 2");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}
}

And here is my layout for it:

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"  />

</android.support.design.widget.CoordinatorLayout>

This is one of my Stats() fragments. The second one looks very similar:

public class Stats1 extends Fragment {
GraphView graph;
public Stats1 () {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    return inflater.inflate(R.layout.stats1, container, false);

}

@Override
public void onViewCreated(View view, Bundle savedInstanceState){
    Calendar calendar = Calendar.getInstance();
    Date d1 = calendar.getTime();
    calendar.add(Calendar.DATE, 1);
    Date d2 = calendar.getTime();
    calendar.add(Calendar.DATE, 1);
    Date d3 = calendar.getTime();
    calendar.add(Calendar.DATE, 1);
    Date d4 = calendar.getTime();
    calendar.add(Calendar.DATE, 1);
    Date d5 = calendar.getTime();

    graph = (GraphView) view.findViewById(R.id.graph);
    StaticLabelsFormatter staticLabelsFormatter = new
StaticLabelsFormatter(graph);

    staticLabelsFormatter.setHorizontalLabels(new String[] {"old", "middle", "new"});

    graph.setTitle("Data History");
    LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(new DataPoint[] {
            new DataPoint(d1, 145.4),
            new DataPoint(d2, 145.9),
            new DataPoint(d3, 147.2),
            new DataPoint(d4, 146.5),
            new DataPoint(d5, 147.1)
    });

    graph.getViewport().setScalable(true);

    graph.addSeries(series);
// set date label formatter
    //graph.getGridLabelRenderer().setLabelFormatter(new
DateAsXAxisLabelFormatter(this));
    graph.getGridLabelRenderer().setLabelFormatter(staticLabelsFormatter);

    //graph.getGridLabelRenderer().setNumHorizontalLabels(6); // only 4 because of the space
    series.setDrawDataPoints(true);

// set manual x bounds to have nice steps
    graph.getViewport().setMinX(d1.getTime());
    graph.getViewport().setMaxX(d5.getTime());
    graph.getViewport().setXAxisBoundsManual(true);

// as we use dates as labels, the human rounding to nice readable numbers
// is not necessary
    graph.getGridLabelRenderer().setHumanRounding(false);
}

I use appsthatmatter/GraphView for graphing purposes.

I tried debugging it and I found out that after I navigate away from the tabs and come back, the function:

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

won't get called anymore. It does twice the first time around but it never will  until i properly close the app and restart.

Can anybody help me figure out what I'm not doing right, please?

Thanks

Body:
I actually fixed it. I had to change:

adapter = new ViewPagerAdapter(getFragmentManager());

to

adapter = new ViewPagerAdapter(getChildFragmentManager());


答:
Try this

Solution 1

```<code>-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"ProfileViewController's identifier"])
    {
         ProfileViewController *loadCtr = (ProfileViewController *)segue.destinationViewController;
             loadCtr.custid =self.tmpv1;
             loadCtr.mobilestrp = self.stri1;
    }

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

    }
}
</code>```

Solution 2

Check both viewcontroller's assigned segue identifier and if both are same then assign different identifier .

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!!

Body:
Try this

Solution 1

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

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

    }
}

Solution 2

Check both viewcontroller's assigned segue identifier and if both are same then assign different identifier .


问:
Build tuple from heterogeneous initializer list at function call
Consider the following function

```<code>template <class... T, class... U>
void f(std::tuple<T...> t, std::tuple<U...> u)
{
    std::cout << sizeof...(T) << " " << sizeof...(U) << std::endl;
}

int main(int argc, char* argv[])
{
    f({3, 3.5, "Hello World!"}, {'a', std::string("b")}); // Fails
    return 0;
}
</code>```

Would there be any way in C++17 to modify the function signature so that the line marked "Fails" would work? (keeping that line the same).

答:
In C++17, you might write:

```<code>f(std::tuple{3, 3.5, "Hello World!"}, std::tuple{'a', std::string("b")});
</code>```

Prior, you may use std::make_tuple:

```<code>f(std::make_tuple(3, 3.5, "Hello World!"), std::make_tuple('a', std::string("b")));
</code>```

but nothing to let the line unmodified and keeping the function template.

Body:
Consider the following function

template <class... T, class... U>
void f(std::tuple<T...> t, std::tuple u)
{
    std::cout << sizeof...(T) << " " << sizeof...(U) << std::endl;
}

int main(int argc, char* argv[])
{
    f({3, 3.5, "Hello World!"}, {'a', std::string("b")}); // Fails
    return 0;
}

Would there be any way in C++17 to modify the function signature so that the line marked "Fails" would work? (keeping that line the same).

Body:
In C++17, you might write:

f(std::tuple{3, 3.5, "Hello World!"}, std::tuple{'a', std::string("b")});

Prior, you may use std::make_tuple:

f(std::make_tuple(3, 3.5, "Hello World!"), std::make_tuple('a', std::string("b")));

but nothing to let the line unmodified and keeping the function template.


问:
CRUD using MVC Architecture using PHP and MYSQL
I am in need to develop a site using MVC architecture without using any frameworks.

Is there any CRUD example for PHP using MVC architecture so that i can able to proceed further. I search a lot. But i can't find a best example which looks cool and powerful.

Kindly suggest me any good examples which implements full power of MVC architecture.

Thanks in advance...

答: Codeigniter From Scratch: Day 5</p>

Body: Codeigniter From Scratch: Day 5


问:
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>```

答:
Your current code has wrong logic:

What if C:\M\send.txt file is empty: foreach doesn't loop at all and username, password will contain garbage

Why do you loop over the entire file? It's the last line of the file which will be finally assigned to the username, password.

In case you want to preserve the existing logic (parse and assign the last line of the file):

```<code>    public static void Main()
    {
        var line = File
          .ReadLines(@"C:\\M\send.txt") // We don't want All lines to be in memory
          .LastOrDefault();

        string username = ""; // or null
        string password = ""; // or null

        if (line != null)
        {
            string[] tokens = line.Split(',');
            string user = tokens[0];
            string pass = tokens[1];
            username = user;
            password = pass;
        }
        //TODO: you may want to add "else" here (i.e. the file is empty case)
</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:
Your current code has wrong logic:

What if C:\M\send.txt file is empty: foreach doesn't loop at all and username, password will contain garbage

Why do you loop over the entire file? It's the last line of the file which will be finally assigned to the username, password.

In case you want to preserve the existing logic (parse and assign the last line of the file):

    public static void Main()
    {
        var line = File
          .ReadLines(@"C:\\M\send.txt") // We don't want All lines to be in memory
          .LastOrDefault();

        string username = ""; // or null
        string password = ""; // or null

        if (line != null)
        {
            string[] tokens = line.Split(',');
            string user = tokens[0];
            string pass = tokens[1];
            username = user;
            password = pass;
        }
        //TODO: you may want to add "else" here (i.e. the file is empty case)


问:
Genymotion stuck after reboot
When I try to reboot genymotion from Program Files\Genymotion\tools with command adb reboot it gets stucked. I tried to update genymotion but it does not help. Genymotion version Version 2.9.0
I'm using native genymotion android tools

答: Try to increase the RAM size for your genymotion device and restart again..!!

Title: Genymotion stuck after reboot


问:
How can i secure my application and also protect my Sqlite database in application
How can i secure my application and also protect my database in application. Which means data is not accessed by other application or by reverse engineering. Like in banking application login data and other information is stored in app but we can not accessed. How to achieve this type of security in application.
Encryption is way to achieve security but there are many types of encryption. I am not getting to figured out that which encryption type is better for security in application.</p>

答:
You can use sqlcipher to protect your sqlite database
click here</p>


问:
Changing picture inside img on hover with css
I need to change  source URL on hover.

I have tried this but won't work :

This is my Css:

```<code>.nav > li > div {
    position: absolute;
    display: block;
    width: 100%;
    top: 38px;
    left: 0;
    opacity: 0;
    visibility: hidden;
    overflow: hidden;
    background: #ffffff;
    border-top-color: #5f7ec7;
    border-top-style: solid;
    border-top-width: 1px;
    border-bottom-color: #5f7ec7;
    border-bottom-style: solid;
    border-bottom-width: 1px;
    -webkit-transition: all .3s ease .15s;
    -moz-transition: all .3s ease .15s;
    -o-transition: all .3s ease .15s;
    -ms-transition: all .3s ease .15s;
    transition: all .3s ease .15s;
}
.nav > li:hover > div {
    opacity: 1;
    visibility: visible;
    overflow: visible;
}
</code>```

And This is my html:

```<code><ul class="nav" style="width: 100%">
    <li>
        Something
        <a title="D" itemprop="url" href="/Default.aspx"><span itemprop="name">Something</span><img src="/images/Top-Menu-Layer/arrow_122b87.gif" style="vertical-align:middle; padding-left:5px; height:4px; width:7px" /></a>
       </li>
</ul>
</code>```

I would like to change the content of the img tag inside the html via the css. How can I do it ? Any advice ?

答:
You can't with pure css,but can help Jquery.

$(document).ready(function(){
  $('.nav li').hover(function(){
        $('.target').attr('src','https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRLd77JVS_4xE04KaLd3E-j2pTyiO_fTcEwHgQL9tj8GMsXZQW2');
   },function(){
 $('.target').attr('src','http://www.mrwallpaper.com/wallpapers/cute-bunny-1600x900.jpg');
   })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <ul class="nav" style="width: 100%">
   <li>
     Something

        <span itemprop="name">Something</span>
        <img class="target" src="http://www.mrwallpaper.com/wallpapers/cute-bunny-1600x900.jpg" style="vertical-align:middle; padding-left:5px; height:40px; width:70px" />

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

Body:
I need to change  source URL on hover.

I have tried this but won't work :

This is my Css:

.nav > li > div {
    position: absolute;
    display: block;
    width: 100%;
    top: 38px;
    left: 0;
    opacity: 0;
    visibility: hidden;
    overflow: hidden;
    background: #ffffff;
    border-top-color: #5f7ec7;
    border-top-style: solid;
    border-top-width: 1px;
    border-bottom-color: #5f7ec7;
    border-bottom-style: solid;
    border-bottom-width: 1px;
    -webkit-transition: all .3s ease .15s;
    -moz-transition: all .3s ease .15s;
    -o-transition: all .3s ease .15s;
    -ms-transition: all .3s ease .15s;
    transition: all .3s ease .15s;
}
.nav > li:hover > div {
    opacity: 1;
    visibility: visible;
    overflow: visible;
}

And This is my html:

        Something
        Something

I would like to change the content of the img tag inside the html via the css. How can I do it ? Any advice ?

Body:
You can't with pure css,but can help Jquery.

$(document).ready(function(){
  $('.nav li').hover(function(){
        $('.target').attr('src','https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRLd77JVS_4xE04KaLd3E-j2pTyiO_fTcEwHgQL9tj8GMsXZQW2');
   },function(){
 $('.target').attr('src','http://www.mrwallpaper.com/wallpapers/cute-bunny-1600x900.jpg');
   })
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <ul class="nav" style="width: 100%">
   <li>
     Something
     <a title="D" itemprop="url" href="/Default.aspx">
        <span itemprop="name">Something</span>
        <img class="target" src="http://www.mrwallpaper.com/wallpapers/cute-bunny-1600x900.jpg" style="vertical-align:middle; padding-left:5px; height:40px; width:70px" />
        </a>
    </li>
</ul>