问:
Can't figure out how to write interrupt handler for Z80 using SDCC
I'm developing a program in C for the Z80 and compiling using SDCC.  I can't figure out how to create interrupt handlers for the NMI interrupt that starts at 0x0066 and the IM1 interrupt that starts at 0x0038.  I'm using these calls:

```<code>void IM1_InterruptHandler(void) __interrupt
</code>```

and

```<code>void NMI_InterruptHandler (void) __critical __interrupt
</code>```

and the resulting assembly looks about right but they aren't located at the proper addresses.  I did spot this thread:

https://sourceforge.net/p/sdcc/feature-requests/519/

but can't figure out how to use the above example crt0.s file with SDCC for a Z80 target.
Using the --use-crt switch doesn't seem to work.

```<code>unknown compiler option '--use-crt=crt0.s' ignored
</code>```

Anyone experienced with Z80 development with SDCC that can provide some guidance?

Edit:
Still not quite there yet.  My crt.s file looks like this:

```<code>.module crt0
    .globl  _main
    .globl  _IM1_InterruptHandler
    .globl  _NMI_InterruptHandler

    .area   _HEADER (ABS)
    ;; Reset vector
    .org    0
    jp  init

    .org    0x08
    reti
    .org    0x10
    reti
    .org    0x18
    reti
    .org    0x20
    reti
    .org    0x28
    reti
    .org    0x30
    reti

    .org    0x38
    jp _IM1_InterruptHandler

    .org    0x66
    jp _NMI_InterruptHandler

    .org    0x100
init:
    ;; Stack at the top of memory.
    ld  sp,#0x8300

    call    _main

    ;; Ordering of segments for the linker.
    .area   _HOME
    .area   _CODE

    .area   _DATA

    .area   _CODE
</code>```

And I'm doing the following:

```<code>sdasz80 -l -o mycrt.rel crt0.s
sdcc -mz80 --no-std-crt0 --code-loc 0x0000 --data-loc 0x8000 mycrt.rel ppclone_menu.c
</code>```

Every thing seems to compile just fine but when I bring up the code in the disassembler I don't see any of the crt0 code being inserted above at locations  0x08 through 0x66.

答:
To use a custom crt0 file you first need to compile it using sdasz80, which should be part of your SDCC install:

```<code>sdasz80 -o crt0_int.rel crt0_int.asm
</code>```

Then you compile your program adding the following to the SDCC command line:

```<code>--no-std-crt0 crt0_int.rel
</code>```

So the full command line would be something like:

```<code>sdcc --code-loc 0xWhatever --data-loc 0xWhatever -mz80 --no-std-crt0 crt0_int.rel somelibrary.lib yoursource.c
</code>```

If you need examples of complete crt0 files, you have one in my MSX software repository.

Edit: You are passing --code-loc 0x0000 to sdcc when compiling your source, this will cause the code section to overwrite whatever was defined in crt0. Change it to a more suitable value (for your crt0 looks like 0x0110 would be fine) or leave it out, so the compiler will choose an appropriate value by itself.

Body:
I'm developing a program in C for the Z80 and compiling using SDCC.  I can't figure out how to create interrupt handlers for the NMI interrupt that starts at 0x0066 and the IM1 interrupt that starts at 0x0038.  I'm using these calls:

void IM1_InterruptHandler(void) __interrupt

and

void NMI_InterruptHandler (void) __critical __interrupt

and the resulting assembly looks about right but they aren't located at the proper addresses.  I did spot this thread:

https://sourceforge.net/p/sdcc/feature-requests/519/

but can't figure out how to use the above example crt0.s file with SDCC for a Z80 target.
Using the --use-crt switch doesn't seem to work.

unknown compiler option '--use-crt=crt0.s' ignored

Anyone experienced with Z80 development with SDCC that can provide some guidance?

Edit:
Still not quite there yet.  My crt.s file looks like this:

.module crt0
    .globl  _main
    .globl  _IM1_InterruptHandler
    .globl  _NMI_InterruptHandler

    .area   _HEADER (ABS)
    ;; Reset vector
    .org    0
    jp  init

    .org    0x08
    reti
    .org    0x10
    reti
    .org    0x18
    reti
    .org    0x20
    reti
    .org    0x28
    reti
    .org    0x30
    reti

    .org    0x38
    jp _IM1_InterruptHandler

    .org    0x66
    jp _NMI_InterruptHandler

    .org    0x100
init:
    ;; Stack at the top of memory.
    ld  sp,#0x8300

    call    _main

    ;; Ordering of segments for the linker.
    .area   _HOME
    .area   _CODE

    .area   _DATA

    .area   _CODE

And I'm doing the following:

sdasz80 -l -o mycrt.rel crt0.s
sdcc -mz80 --no-std-crt0 --code-loc 0x0000 --data-loc 0x8000 mycrt.rel ppclone_menu.c

Every thing seems to compile just fine but when I bring up the code in the disassembler I don't see any of the crt0 code being inserted above at locations  0x08 through 0x66.

Body:
To use a custom crt0 file you first need to compile it using sdasz80, which should be part of your SDCC install:

sdasz80 -o crt0_int.rel crt0_int.asm

Then you compile your program adding the following to the SDCC command line:

--no-std-crt0 crt0_int.rel

So the full command line would be something like:

sdcc --code-loc 0xWhatever --data-loc 0xWhatever -mz80 --no-std-crt0 crt0_int.rel somelibrary.lib yoursource.c

If you need examples of complete crt0 files, you have one in my MSX software repository.

Edit: You are passing --code-loc 0x0000 to sdcc when compiling your source, this will cause the code section to overwrite whatever was defined in crt0. Change it to a more suitable value (for your crt0 looks like 0x0110 would be fine) or leave it out, so the compiler will choose an appropriate value by itself.


来源: stackexchange

问:
How to Parse contents of HTML tag which is inside an HTML tag with BeautifulSoup?
In a unique case of html found on web there is a html document which has multiple html tags within the parent HTML tag. I want to parse the contents of the html tag. Can anyone point me in the direction to do so ?

Thanks in advance.

Edit 1:
Using BeautifulSoup

```<code>soup = BeautifulSoup(html, "lxml")
</code>```

gives only the parent html and the tags present within it.

However I am assuming if the browser is able to render the html BS should be able to parse it. is that assumption correct?

Edit 2:
Actually the html is a malformed html ( i am assuming here), this is the html I am parsing with beautifulsoup somehow I am only getting the tables  and  and  of 1st (outermost) html. If I manually remove the multiple HTML tags and only keep 1 html tag I am able to parse the table in BS. So the question is "Is there any way to parse the below html and get the data from the innermost or all tables in the file?

```<code><!DOCTYPE html>
<html>
<head>
    <title>Some Title</title>
</head>
<body>
    some html to display the tables.
    <html>
        <head></head>
        <title>Some other title</title>
        <body>
            some html to display even more tables.
        </body>
    </html>
</body>
</html>
</code>```

答:
here is a sample code, you can use for finding text of particular inside a particular kind of html tag</p>

```<code>soup2 = BeautifulSoup(x, 'html.parser')
    for i in soup2.find_all('ul', attrs={'class': 'results-base'}):
         for j in i.find_all('li'):
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In a unique case of html found on web there is a html document which has multiple html tags within the parent HTML tag. I want to parse the contents of the html tag. Can anyone point me in the direction to do so ?

Thanks in advance.

Edit 1:
Using BeautifulSoup

soup = BeautifulSoup(html, "lxml")

gives only the parent html and the tags present within it.

However I am assuming if the browser is able to render the html BS should be able to parse it. is that assumption correct?

Edit 2:
Actually the html is a malformed html ( i am assuming here), this is the html I am parsing with beautifulsoup somehow I am only getting the tables  and  and  of 1st (outermost) html. If I manually remove the multiple HTML tags and only keep 1 html tag I am able to parse the table in BS. So the question is "Is there any way to parse the below html and get the data from the innermost or all tables in the file?

<!DOCTYPE html>

    <title>Some Title</title>

    some html to display the tables.

        <title>Some other title</title>

            some html to display even more tables.

Body:
here is a sample code, you can use for finding text of particular inside a particular kind of html tag

soup2 = BeautifulSoup(x, 'html.parser')
    for i in soup2.find_all('ul', attrs={'class': 'results-base'}):
         for j in i.find_all('li'):


问:
Not saving output raster file name as set in input file list
When ESRI grid file format rasters are read into for loop and convert them to HFA files, output file name is not set as same as the input file name. Following code is used for the conversion;</p>

```<code>library(raster)
raster_data <- list.files(pattern='rain', full.names=FALSE)

# "rain1970" "rain1971"

for (i in 1:length(raster_data)) {
    r.nc <- raster(raster_data[i])
    writeRaster(r.nc, paste0(i, '.IMG', sep = ''), format = 'HFA', overwrite = T)
}
</code>```

答:
The value i in your for loop is an integer, iterated as per your 1:length(raster_data) input. You need to reference the name from your raster_data vector using that integer, rather than pasting the integer itself.

Change this:

```<code>paste0(i, '.IMG', sep = '')
</code>```

To this:

```<code>paste0(raster_data[i], '.IMG', sep = '')
</code>```

Now you're getting the text string at location i within your input list. You'll probably want to remove the original file extension though, so maybe this would work better.

```<code>sub( "\\.[a-z|A-Z]+$", ".IMG", raster_data[i] )
</code>```

This will replace any existing file extension with your new one.

Body:
When ESRI grid file format rasters are read into for loop and convert them to HFA files, output file name is not set as same as the input file name. Following code is used for the conversion;

library(raster)
raster_data <- list.files(pattern='rain', full.names=FALSE)

# "rain1970" "rain1971"

for (i in 1:length(raster_data)) {
    r.nc <- raster(raster_data[i])
    writeRaster(r.nc, paste0(i, '.IMG', sep = ''), format = 'HFA', overwrite = T)
}

Body:
The value i in your for loop is an integer, iterated as per your 1:length(raster_data) input. You need to reference the name from your raster_data vector using that integer, rather than pasting the integer itself.

Change this:

paste0(i, '.IMG', sep = '')

To this:

paste0(raster_data[i], '.IMG', sep = '')

Now you're getting the text string at location i within your input list. You'll probably want to remove the original file extension though, so maybe this would work better.

sub( "\\.[a-z|A-Z]+$", ".IMG", raster_data[i] )

This will replace any existing file extension with your new one.


问:
jQuery IF statement (Only if a web browser on a desktop) not a mobile device / iPad
is there a easy way with jQuery to essentially have a jQUery/JS if statement along the lines of:

```<code>IF User is on a web Browser on a desktop... not a mobile device / iPad
</code>```

Thanks

答:
Although not really recommended to use this, here it is:

http://api.jquery.com/jQuery.browser/

excerpt:

Because $.browser uses navigator.userAgent to determine the platform, it is vulnerable to spoofing by the user or misrepresentation by the browser itself. It is always best to avoid browser-specific code entirely where possible. The $.support property is available for detection of support for particular features rather than relying on $.browser.

ContentLicense: CC BY-SA 2.5

Body:
is there a easy way with jQuery to essentially have a jQUery/JS if statement along the lines of:

IF User is on a web Browser on a desktop... not a mobile device / iPad

Thanks


问:
How to use kernel header <linux/gfp.h>
Hi i am developing a small program that allocates physical pages dynamically using Alloc_pages function declared in gfp.h but when i am trying to compile it encounters an error with message linux/gfp.h no such file or directory. How can i use this header to develop memory management programs. Any suggestions are heartly welcomed.

答:
Its may be due to your linux headers not installed.
try this:

```<code>apt-get install linux-headers-3.19.0-79-generic
</code>```

This command is for linux headers 3.19.0.79 generic , do this according to your kernel version.

Title: How to use kernel header <linux/gfp.h>

Body:
Its may be due to your linux headers not installed.
try this:

apt-get install linux-headers-3.19.0-79-generic

This command is for linux headers 3.19.0.79 generic , do this according to your kernel version.


问:
How to access .so library from nodejs application
I have a piece of C code which returns a string output.
The same api is packaged in the form of a .so file.

How can i use the .so file directly in my nodejs code.
Do i need to add something in my C code or there is a standard mechanism in node for the same..?

Thanks

答:
You can't. What you can do is to write a C executable which uses the so library and returns an output. You can call this in your js file using the exec function.</p>

```<code>exec('/<path_to_executable>/executable',
  function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if (error !== null) {
      console.log('exec error: ' + error);
    }
});
</code>```

Body:
You can't. What you can do is to write a C executable which uses the so library and returns an output. You can call this in your js file using the exec function.

exec('/<path_to_executable>/executable',
  function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if (error !== null) {
      console.log('exec error: ' + error);
    }
});


问:
Why is javascript not part of the project architecture?
I recently came across a question where someone asked what architecture we use in the company and someone else replied LAMP.

I am not sure why we do not include javascript as a part of the architecture. Is it implied? Or is there something I am missing? What if someone is using say ECMA script or VB script instead of javascript?

答: Javascript is a web based client side technology. It can be enabled or disabled by the user.</p>


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

Date : how many records have that date

20110105 : 5 records

20120501 : 2 records

20120602 : 15 records

This is what I have so far:

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

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

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

How do I display the number of records for each date?

答:
You should use date histogram aggregation for your purpose.
Your query will look like -

```<code>{
    "query": #if any,
    "aggs": {
        "date": {
            "date_histogram": {
                "field": "fieldName",
                "interval": "day",
                "min_doc_count": 1 #if you need key with any minimum doc count
            }
        }
    },
    "size": 0
}
</code>```

To run this query correctly, your date field type should be date. Otherwise, you will get an error.

Hope this helps

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

Date : how many records have that date

20110105 : 5 records

20120501 : 2 records

20120602 : 15 records

This is what I have so far:

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

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

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

How do I display the number of records for each date?

Body:
You should use date histogram aggregation for your purpose.
Your query will look like -

{
    "query": #if any,
    "aggs": {
        "date": {
            "date_histogram": {
                "field": "fieldName",
                "interval": "day",
                "min_doc_count": 1 #if you need key with any minimum doc count
            }
        }
    },
    "size": 0
}

To run this query correctly, your date field type should be date. Otherwise, you will get an error.

Hope this helps


问:
Processing Symbol Files in Xcode
I was wondering if anyone could tell me what Xcode is actually doing when it says: "Processing Symbol Files" after plugging in your device?

答:
Add SDK version correspond to your iPhone iOS, eg: iOS 10.3

path:

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport

It's downloading. When it's finished, it's OK. As shown in the figure:

Title: Processing Symbol Files in Xcode


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

答:
A segue defines a transition between two view controllers. While in your case the segue is presenting WelcomeViewController which have no property custid, so it is better to keep check using segue identifier.

```<code>- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

       if ([segue.identifier isEqualToString:@"YOUR_SEGUE_IDENTIFER"]) {
           //YOUR Code Here
           ProfileViewController *loadCtr = (ProfileViewController *)segue.destinationViewController;
           loadCtr.custid =self.tmpv1;
           loadCtr.mobilestrp = self.stri1;

       }
}
</code>```

Note: Make sure that the starting point(initiates the segue) and ending point(you want to display) of segues are correct. Moreover always use  unique identifier for segue on your Storyborad.

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:
A segue defines a transition between two view controllers. While in your case the segue is presenting WelcomeViewController which have no property custid, so it is better to keep check using segue identifier.

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

       if ([segue.identifier isEqualToString:@"YOUR_SEGUE_IDENTIFER"]) {
           //YOUR Code Here
           ProfileViewController *loadCtr = (ProfileViewController *)segue.destinationViewController;
           loadCtr.custid =self.tmpv1;
           loadCtr.mobilestrp = self.stri1;

       }
}

Note: Make sure that the starting point(initiates the segue) and ending point(you want to display) of segues are correct. Moreover always use  unique identifier for segue on your Storyborad.


问:
Unable to create or switch to new tab in Selenium Webdriver with JAVA on MAC
I've tried a different options just to open new tab but all of them lead to the same result : sending char "t" to google search field.
The goal in my real test is to switch between tabs in browser, but I am unable even open new one.

Very simple test

```<code>    public class LoginPhp2 {

        @Test
        public void testGoogle() {
            WebDriver driver = new SafariDriver();
            driver.get("https://www.google.com");
            //driver.findElement(By.cssSelector("body")).sendKeys(Keys.COMMAND + "t");
            Actions action= new Actions(driver);
           action.keyDown(Keys.COMMAND).sendKeys("t").build().perform();
            //action.keyDown(Keys.COMMAND).sendKeys("t").keyUp(Keys.COMMAND).build().perform();

        }
    }
</code>```

答:
There are different ways of opening new tabs in windows and Mac. Actual keys to send depend on your OS, for example, Mac uses COMMAND + t, instead of CONTROL + t.

You can open new tab in Mac using:

```<code>driver.findElement(By.cssSelector("body")).sendKeys(Keys.COMMAND +"t");
</code>```

After this you can switch to any of the opened tabs:

```<code>ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(0));
</code>```

Body:
I've tried a different options just to open new tab but all of them lead to the same result : sending char "t" to google search field.
The goal in my real test is to switch between tabs in browser, but I am unable even open new one.

Very simple test

    public class LoginPhp2 {

        @Test
        public void testGoogle() {
            WebDriver driver = new SafariDriver();
            driver.get("https://www.google.com");
            //driver.findElement(By.cssSelector("body")).sendKeys(Keys.COMMAND + "t");
            Actions action= new Actions(driver);
           action.keyDown(Keys.COMMAND).sendKeys("t").build().perform();
            //action.keyDown(Keys.COMMAND).sendKeys("t").keyUp(Keys.COMMAND).build().perform();

        }
    }

Body:
There are different ways of opening new tabs in windows and Mac. Actual keys to send depend on your OS, for example, Mac uses COMMAND + t, instead of CONTROL + t.

You can open new tab in Mac using:

driver.findElement(By.cssSelector("body")).sendKeys(Keys.COMMAND +"t");

After this you can switch to any of the opened tabs:

ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(0));


问:
Google Play App Signing and Facebook Login
I uploaded my signed apk using the new Google App Signing, and found out I need to change the authentication keys in order for the APIs to keep working.
The SHA1 is given directly on the google play console, so I used it successfully with for my Google APIs, however Facebook login key is different (28 characters ending by "=" ).
Since I don't know the alias of the new keystore created by google, I don't know how to get this  key.
Hope someone can help.
Cheers,

Q

答: Just to add another option, one can check the device's logcat & there's a Log from Facebook Sdk with the "key" expected/required to login, we can directly copy+paste from there as well instead of converting it through an online tool.</p>


问:
How many variables are too much for a class?
I want to see if anyone has a better design for a class (class as in OOP) I am writing. We have a script that puts shared folder stats in a CSV file. I am reading that in and putting it in a Share class.

My boss wants to know information like:

Total Number of Files

Total Size of Files

Number of Office Files

Size of Office Files

Number of Exe Files

Size of Exe Files

etc ....

I have a class with variables like $numOfficeFiles, $sizeOfficeFiles, etc. with a ton of get/set methods. Isn't there a better way to do this? What is the general rule if you have a class with a lot of variables/properties?

I think of this as a language agnostic question, but if it matters, I am using PHP.

答:
Sounds like you might have a ton of duplicate code.  You want the # of files and the size of files for a bunch of different types.  You can start with a class that looks like this:

```<code>public class FileStats
{
    public FileStats(String extension)
    {
        // logic to discover files goes here
    }

    public int getSize() { }
    public int getNumFiles() { }
}
</code>```

Then, in your main class, you can have an array of all the file types you want, and a collection of these helper objects:

```<code>public class Statistics
{
    private static final String[] TYPES = { "exe", "doc", "png" };
    private Collection<FileStats> stats = new HashSet<FileStats>();

    public static void collectStats()
    {
        stats.clear();
        for(String type : TYPES)
            stats.add(new FileStats(type));
    }
}
</code>```

You can clean up your API by passing a parameter to the getter method:

```<code>public int getNumFiles(String type)
{
    return stats.get(type).getNumFiles();
}
</code>```

OwnerDisplayName: Ben

LastEditorDisplayName: mmyers

Body:
Sounds like you might have a ton of duplicate code.  You want the # of files and the size of files for a bunch of different types.  You can start with a class that looks like this:

public class FileStats
{
    public FileStats(String extension)
    {
        // logic to discover files goes here
    }

    public int getSize() { }
    public int getNumFiles() { }
}

Then, in your main class, you can have an array of all the file types you want, and a collection of these helper objects:

public class Statistics
{
    private static final String[] TYPES = { "exe", "doc", "png" };
    private Collection<FileStats> stats = new HashSet<FileStats>();

    public static void collectStats()
    {
        stats.clear();
        for(String type : TYPES)
            stats.add(new FileStats(type));
    }
}

You can clean up your API by passing a parameter to the getter method:

public int getNumFiles(String type)
{
    return stats.get(type).getNumFiles();
}

OwnerDisplayName: Outlaw Programmer


问:
Database design, for optimized access
I jump straight into the problem, currently I have a table as such

```<code>id | model | CategoryId | etc...
</code>```

Now my new requirement is to have support for multiple categories. So I have two possible solutions in mind but I would like to know problems that both this designs might create. I also know that at most I can have 6 categories, also I can't create a linker table to link product to category.

On first design I would simply create column  CategoryN

```<code>id | model | CategoryId1 | CategoryId2 | CategoryId3 | CategoryId4 | etc...
</code>```

But this would make queries hideous,

```<code>   id | model | CategoryId | etc...
</code>```

My second approach is simply to add product for N categories

```<code>   id | model | CategoryId | etc...
   1 | ABC   | 1           | etc...
   2 | ABC   | 2           | etc...
   3 | ABC   | 3           | etc...
</code>```

I think queries would be cleaner but not necessarily simpler.
Another aspect is that I am looking at the performance of the queries and it looks like the first approach would be better.
I hope this is clear enough.

Thanks for any suggestions.

答:
The third option is a many-to-many table to link a model to a category:

MODEL_CATEGORIES

model_id (primary key, foreign key to MODEL table)

category_id (primary key, foreign key to CATEGORY table)

Your example data would resemble:

```<code>model_id  category_id
----------------------
1         1
1         2
1         3
</code>```

This means there's no need for a category_id column in the MODEL table.

Title: Database design, for optimized access

Body:
I jump straight into the problem, currently I have a table as such

id | model | CategoryId | etc...

Now my new requirement is to have support for multiple categories. So I have two possible solutions in mind but I would like to know problems that both this designs might create. I also know that at most I can have 6 categories, also I can't create a linker table to link product to category.

On first design I would simply create column  CategoryN

id | model | CategoryId1 | CategoryId2 | CategoryId3 | CategoryId4 | etc...

But this would make queries hideous,

   id | model | CategoryId | etc...

My second approach is simply to add product for N categories

   id | model | CategoryId | etc...
   1 | ABC   | 1           | etc...
   2 | ABC   | 2           | etc...
   3 | ABC   | 3           | etc...

I think queries would be cleaner but not necessarily simpler.
Another aspect is that I am looking at the performance of the queries and it looks like the first approach would be better.
I hope this is clear enough.

Thanks for any suggestions.

Body:
The third option is a many-to-many table to link a model to a category:

MODEL_CATEGORIES

model_id (primary key, foreign key to MODEL table)

category_id (primary key, foreign key to CATEGORY table)

Your example data would resemble:

model_id  category_id
----------------------
1         1
1         2
1         3

This means there's no need for a category_id column in the MODEL table.


问:
C LIBCHAMPLAIN SegFault?
I had a programm with C and libchamplain which showed a map. worked fine. Now i wanted to integrate it into an gtk application. But at running, i get a segfault:

```<code>#include <stdio.h>
#include <gtk/gtk.h>
#include <champlain/champlain.h>
#include <champlain-gtk/champlain-gtk.h>
#include <clutter-gtk/clutter-gtk.h>
#include <math.h>

#include "GPS_stub.h"

#define MARKER_SIZE 10
#define MAX_SIZ 4096

static gboolean draw_center(ClutterCanvas *canvas, cairo_t *cr, int width, int height){
  cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR);
  cairo_paint(cr);
  cairo_set_operator(cr, CAIRO_OPERATOR_OVER);

  cairo_set_source_rgb(cr, 0, 0, 0);
  cairo_arc(cr, MARKER_SIZE / 2.0, MARKER_SIZE / 2.0, MARKER_SIZE / 2.0, 0, 2 * M_PI);
  cairo_close_path(cr);
  cairo_set_source_rgba(cr, 0.1, 0.1, 0.9, 1.0);
  cairo_fill(cr);

  return TRUE;
}

static ClutterActor *create_marker(void){
  ClutterActor *marker;
  ClutterActor *bg;
  ClutterContent *canvas;
  ClutterTransition *transition;

  marker = champlain_custom_marker_new();

  canvas = clutter_canvas_new();
  clutter_canvas_set_size(CLUTTER_CANVAS(canvas), MARKER_SIZE, MARKER_SIZE);
  g_signal_connect(canvas, "draw", G_CALLBACK(draw_center), NULL);

  bg = clutter_actor_new();
  clutter_actor_set_size(bg, MARKER_SIZE, MARKER_SIZE);
  clutter_actor_set_content(bg, canvas);
  clutter_content_invalidate(canvas);
  g_object_unref(canvas);

  clutter_actor_add_child(marker, bg);
  clutter_actor_set_pivot_point(bg, 0.5, 0.5);
  clutter_actor_set_position(bg, -MARKER_SIZE, -MARKER_SIZE);

  transition = clutter_property_transition_new("opacity");
  clutter_actor_set_easing_mode(bg, CLUTTER_EASE_OUT_SINE);
  clutter_timeline_set_duration(CLUTTER_TIMELINE(transition), 1000);
  clutter_timeline_set_repeat_count(CLUTTER_TIMELINE(transition), -1);
  clutter_transition_set_from(transition, G_TYPE_UINT, 255);
  clutter_transition_set_to(transition, G_TYPE_UINT, 0);
  clutter_actor_add_transition(bg, "animate-opacity", transition);

  transition = clutter_property_transition_new("scale-x");
  clutter_actor_set_easing_mode(bg, CLUTTER_EASE_OUT_SINE);
  clutter_timeline_set_duration(CLUTTER_TIMELINE(transition), 1000);
  clutter_timeline_set_repeat_count(CLUTTER_TIMELINE(transition), -1);
  clutter_transition_set_from(transition, G_TYPE_FLOAT, 0.5);
  clutter_transition_set_to(transition, G_TYPE_FLOAT, 1.0);
  clutter_actor_add_transition(bg, "animate-scale-x", transition);

  transition = clutter_property_transition_new("scale-y");
  clutter_actor_set_easing_mode(bg, CLUTTER_EASE_OUT_SINE);
  clutter_timeline_set_duration(CLUTTER_TIMELINE(transition), 1000);
  clutter_timeline_set_repeat_count(CLUTTER_TIMELINE(transition), -1);
  clutter_transition_set_from(transition, G_TYPE_FLOAT, 0.5);
  clutter_transition_set_to(transition, G_TYPE_FLOAT, 1.0);
  clutter_actor_add_transition(bg, "animate-scale-y", transition);

  return marker;
}

static gboolean gps_callback(ChamplainMarker *marker[MAX_SIZ]){
  return TRUE;
}

typedef struct{
  double lat;
  double lng;
} GpsCallbackData;

static void load_map(GpsCallbackData *data){
  ClutterActor *actor, *stage;
  ChamplainMarkerLayer *layer;
  ClutterActor *marker[MAX_SIZ];

  stage = clutter_stage_new();
  clutter_actor_set_size(stage, 800, 600);
  g_signal_connect(stage, "destroy", G_CALLBACK(clutter_main_quit), NULL);

  actor = champlain_view_new();
  clutter_actor_set_size(CLUTTER_ACTOR(actor), 800, 600);
  clutter_actor_add_child(stage, actor);

  layer = champlain_marker_layer_new_full(CHAMPLAIN_SELECTION_SINGLE);
  clutter_actor_show(CLUTTER_ACTOR(layer));
  champlain_view_add_layer(CHAMPLAIN_VIEW(actor), CHAMPLAIN_LAYER(layer));

  for(int i = 0; i < MAX_SIZ/40; i++){
    marker[i] = create_marker();
    champlain_marker_layer_add_marker(layer, CHAMPLAIN_MARKER(marker[i]));
    champlain_location_set_location(CHAMPLAIN_LOCATION(marker[i]), data->lat+i/10, data->lng+i/10);
  }

  g_object_set(G_OBJECT(actor), "zoom-level", 2, "kinetic-mode", TRUE, NULL);
  champlain_view_center_on(CHAMPLAIN_VIEW(actor), 40, 0);

  g_timeout_add(1000, (GSourceFunc) gps_callback, CHAMPLAIN_MARKER(marker));

  clutter_actor_show(stage);
  clutter_main();
}

int main(int argc, char *argv[]){
  GtkWidget *window, *button;

  GpsCallbackData *gps;

  double lat, lng;

  gtk_clutter_init(&argc, &argv);
  hs_init(&argc, &argv);

  getGPS("166.82.21.200", &lat, &lng);
  printf("GPS: %f %f\n", lat, lng);

  gps->lat = lat;
  gps->lng = lng;

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
  gtk_container_set_border_width(GTK_CONTAINER(window), 10);

  button = gtk_button_new_with_label("Load Map");
  g_signal_connect(button, "clicked", G_CALLBACK(load_map), &gps);

  gtk_container_add(GTK_CONTAINER(window), button);
  gtk_widget_show(window);
  gtk_main();

  hs_exit();

  return 0;
}
</code>```

like you can see in main , it prints out coordinates. This works fine. But then after the printing i'm getting an segfault.

Why?

答:
I have a same problem on ARM Linux from here.

```<code> stage = clutter_stage_new();
 clutter_actor_set_size(stage, 800, 600);
</code>```

When I removed or blocked "clutter_actor_set", there's no seg fault error.

actor is O.K, but stage is matter.
But on X86 Ubuntu desktop, it's O.K.

Title: C LIBCHAMPLAIN SegFault?

Body:
I had a programm with C and libchamplain which showed a map. worked fine. Now i wanted to integrate it into an gtk application. But at running, i get a segfault:

#include <stdio.h>
#include <gtk/gtk.h>
#include <champlain/champlain.h>
#include <champlain-gtk/champlain-gtk.h>
#include <clutter-gtk/clutter-gtk.h>
#include <math.h>

#include "GPS_stub.h"

#define MARKER_SIZE 10
#define MAX_SIZ 4096

static gboolean draw_center(ClutterCanvas *canvas, cairo_t *cr, int width, int height){
  cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR);
  cairo_paint(cr);
  cairo_set_operator(cr, CAIRO_OPERATOR_OVER);

  cairo_set_source_rgb(cr, 0, 0, 0);
  cairo_arc(cr, MARKER_SIZE / 2.0, MARKER_SIZE / 2.0, MARKER_SIZE / 2.0, 0, 2 * M_PI);
  cairo_close_path(cr);
  cairo_set_source_rgba(cr, 0.1, 0.1, 0.9, 1.0);
  cairo_fill(cr);

  return TRUE;
}

static ClutterActor *create_marker(void){
  ClutterActor *marker;
  ClutterActor *bg;
  ClutterContent *canvas;
  ClutterTransition *transition;

  marker = champlain_custom_marker_new();

  canvas = clutter_canvas_new();
  clutter_canvas_set_size(CLUTTER_CANVAS(canvas), MARKER_SIZE, MARKER_SIZE);
  g_signal_connect(canvas, "draw", G_CALLBACK(draw_center), NULL);

  bg = clutter_actor_new();
  clutter_actor_set_size(bg, MARKER_SIZE, MARKER_SIZE);
  clutter_actor_set_content(bg, canvas);
  clutter_content_invalidate(canvas);
  g_object_unref(canvas);

  clutter_actor_add_child(marker, bg);
  clutter_actor_set_pivot_point(bg, 0.5, 0.5);
  clutter_actor_set_position(bg, -MARKER_SIZE, -MARKER_SIZE);

  transition = clutter_property_transition_new("opacity");
  clutter_actor_set_easing_mode(bg, CLUTTER_EASE_OUT_SINE);
  clutter_timeline_set_duration(CLUTTER_TIMELINE(transition), 1000);
  clutter_timeline_set_repeat_count(CLUTTER_TIMELINE(transition), -1);
  clutter_transition_set_from(transition, G_TYPE_UINT, 255);
  clutter_transition_set_to(transition, G_TYPE_UINT, 0);
  clutter_actor_add_transition(bg, "animate-opacity", transition);

  transition = clutter_property_transition_new("scale-x");
  clutter_actor_set_easing_mode(bg, CLUTTER_EASE_OUT_SINE);
  clutter_timeline_set_duration(CLUTTER_TIMELINE(transition), 1000);
  clutter_timeline_set_repeat_count(CLUTTER_TIMELINE(transition), -1);
  clutter_transition_set_from(transition, G_TYPE_FLOAT, 0.5);
  clutter_transition_set_to(transition, G_TYPE_FLOAT, 1.0);
  clutter_actor_add_transition(bg, "animate-scale-x", transition);

  transition = clutter_property_transition_new("scale-y");
  clutter_actor_set_easing_mode(bg, CLUTTER_EASE_OUT_SINE);
  clutter_timeline_set_duration(CLUTTER_TIMELINE(transition), 1000);
  clutter_timeline_set_repeat_count(CLUTTER_TIMELINE(transition), -1);
  clutter_transition_set_from(transition, G_TYPE_FLOAT, 0.5);
  clutter_transition_set_to(transition, G_TYPE_FLOAT, 1.0);
  clutter_actor_add_transition(bg, "animate-scale-y", transition);

  return marker;
}

static gboolean gps_callback(ChamplainMarker *marker[MAX_SIZ]){
  return TRUE;
}

typedef struct{
  double lat;
  double lng;
} GpsCallbackData;

static void load_map(GpsCallbackData *data){
  ClutterActor *actor, *stage;
  ChamplainMarkerLayer *layer;
  ClutterActor *marker[MAX_SIZ];

  stage = clutter_stage_new();
  clutter_actor_set_size(stage, 800, 600);
  g_signal_connect(stage, "destroy", G_CALLBACK(clutter_main_quit), NULL);

  actor = champlain_view_new();
  clutter_actor_set_size(CLUTTER_ACTOR(actor), 800, 600);
  clutter_actor_add_child(stage, actor);

  layer = champlain_marker_layer_new_full(CHAMPLAIN_SELECTION_SINGLE);
  clutter_actor_show(CLUTTER_ACTOR(layer));
  champlain_view_add_layer(CHAMPLAIN_VIEW(actor), CHAMPLAIN_LAYER(layer));

  for(int i = 0; i < MAX_SIZ/40; i++){
    marker[i] = create_marker();
    champlain_marker_layer_add_marker(layer, CHAMPLAIN_MARKER(marker[i]));
    champlain_location_set_location(CHAMPLAIN_LOCATION(marker[i]), data->lat+i/10, data->lng+i/10);
  }

  g_object_set(G_OBJECT(actor), "zoom-level", 2, "kinetic-mode", TRUE, NULL);
  champlain_view_center_on(CHAMPLAIN_VIEW(actor), 40, 0);

  g_timeout_add(1000, (GSourceFunc) gps_callback, CHAMPLAIN_MARKER(marker));

  clutter_actor_show(stage);
  clutter_main();
}

int main(int argc, char *argv[]){
  GtkWidget *window, *button;

  GpsCallbackData *gps;

  double lat, lng;

  gtk_clutter_init(&argc, &argv);
  hs_init(&argc, &argv);

  getGPS("166.82.21.200", &lat, &lng);
  printf("GPS: %f %f\n", lat, lng);

  gps->lat = lat;
  gps->lng = lng;

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
  gtk_container_set_border_width(GTK_CONTAINER(window), 10);

  button = gtk_button_new_with_label("Load Map");
  g_signal_connect(button, "clicked", G_CALLBACK(load_map), &gps);

  gtk_container_add(GTK_CONTAINER(window), button);
  gtk_widget_show(window);
  gtk_main();

  hs_exit();

  return 0;
}

like you can see in main , it prints out coordinates. This works fine. But then after the printing i'm getting an segfault.

Why?

Body:
I have a same problem on ARM Linux from here.

 stage = clutter_stage_new();
 clutter_actor_set_size(stage, 800, 600);

When I removed or blocked "clutter_actor_set", there's no seg fault error.

actor is O.K, but stage is matter.
But on X86 Ubuntu desktop, it's O.K.


问:
git commit modified and untracked content
I have setup git to my project to push modifications to gitlab repository.

I installed a plugin from github which lies in /vendor/dereuromar/cakephp-queue

There is also a .git directory and other files associated with git in the plugin's directory

When I push my project to gitlab, everything pushes except this directory.

When trying git status it gives error as

```<code>On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)
  (commit or discard the untracked or modified content in submodules)

    modified:   vendor/dereuromark/cakephp-queue (modified content, untracked content)

no changes added to commit (use "git add" and/or "git commit -a")
</code>```

I tried removing .git directory, .gitignore and .gitattributes directory from vendor/dereuromark/cakephp-queue.

The output of git status is

```<code>On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working directory clean
</code>```

But the contents of that directory is not uploaded to gitlab.

How can I push the content of this directory? I have not created any submodule.

答:
You cannot push anything that hasn't been committed yet. The order of operations is:

Make your change.

git add - this stages your changes for committing

git commit - this commits your staged changes locally

git push - this pushes your committed changes to a remote

If you push without committing, nothing gets pushed. If you commit without adding, nothing gets committed. If you add without committing, nothing at all happens, git merely remembers that the changes you added should be considered for the following commit.

The message you're seeing (your branch is ahead by 1 commit) means that your local repository has one commit that hasn't been pushed yet.

In other words: add and commit are local operations, push, pull and fetch are operations that interact with a remote.

Since there seems to be an official source control workflow in place where you work, you should ask internally how this should be handled.

Body:
I have setup git to my project to push modifications to gitlab repository.

I installed a plugin from github which lies in /vendor/dereuromar/cakephp-queue

There is also a .git directory and other files associated with git in the plugin's directory

When I push my project to gitlab, everything pushes except this directory.

When trying git status it gives error as

On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)
  (commit or discard the untracked or modified content in submodules)

    modified:   vendor/dereuromark/cakephp-queue (modified content, untracked content)

no changes added to commit (use "git add" and/or "git commit -a")

I tried removing .git directory, .gitignore and .gitattributes directory from vendor/dereuromark/cakephp-queue.

The output of git status is

On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working directory clean

But the contents of that directory is not uploaded to gitlab.

How can I push the content of this directory? I have not created any submodule.


问:
Length of Longest increasing subsequence
I am not expecting for a solution here. But I have trouble finding out what could be a possible error. I feel that this is correct solution but however, the solution is not passing all the test case I have. e.g {2,2} . Below is the code I have written in a brute force (worst case - n! complexity) approach. Any help would be greatly appreciated. I am not expecting the solution but would like to know where I am going wrong and how to get it right.

```<code> package org.practice;
    import java.util.Arrays;
    import java.util.HashSet;
    import java.util.LinkedList;
    import java.util.List;

    public class LengthofLIS {
        int maxLength = 0;

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            LengthofLIS l = new LengthofLIS();
            int[] nums = { 2,2 };
            l.lengthOfLIS(nums);
        }

        public int lengthOfLIS(int[] nums) {
            if (nums.length == 1)
                return nums.length;
            List<Integer> hs = new LinkedList<>();
            dfs(nums, 0, 0, nums.length - 1, hs);
            System.out.println(maxLength);
            return maxLength;
        }

        public void dfs(int[] nums, int index, int length, int end, List<Integer> hs) {

        if (index > end) {
            return;
        }

        for (int i = index; i <= end; i++) {

            if (hs.size() == 0) {
                hs.add(nums[i]);
                length++;
            } else if (nums[i] > hs.get(hs.size() - 1)) {
                hs.add(nums[i]);
                length++;
            }

            else if (nums[i] <= hs.get(hs.size() - 1))
                continue;

            dfs(nums, i + 1, length, end, hs);
            //System.out.println("Printing " + Arrays.asList(hs));
            maxLength = Math.max(maxLength, hs.size());

            if (maxLength == nums.length)
                break;

            if (hs.size() != 0) {
                hs.remove(hs.get(hs.size() - 1));
                length--;
            }
        }
    }
    }
</code>```

答:
Since you didn't ask for any solution, I won't provide you one, and on the other hand, you could simply find lots of answers by just a simple search.

Here is what I understand from your code:

```<code>public void dfs(int[] nums, int index, int length, int end, List<Integer> hs) {
    if (index > end) {
        return;
    }
    for (int i = index; i <= end; i++) {
        if (hs.size() == 0) {
            hs.add(nums[i]);
            length++;
        }
        else if (nums[i] > hs.get(hs.size() - 1)) {
            hs.add(nums[i]);
            length++;
        }
        else if (i == end && nums[i] < hs.get(hs.size() - 1)) { //(1)
            maxLength = Math.max(maxLength, hs.size());
        }
        else if (nums[i] < hs.get(hs.size() - 1))
            continue;
        dfs(nums, i + 1, length, end, hs);
        if (hs.size() != 0) { //(2)
            hs.remove(hs.get(hs.size() - 1));
            length--;
        }
    }
}
</code>```

what do you want to accomplish with that? consider the situation when the last element is the biggest element, then you will always print 0 because you'll never set maxLength.

your main problem is here. Because you remove a[i] , a[i+1] recursively from the list. suppose you have {2, 3, 100, 4, 5, 6, 1} instead of considering [2, 3, 4, 5, 6] longest list, your code will consider [2, 4, 5, 6] the longest list.

Body:
I am not expecting for a solution here. But I have trouble finding out what could be a possible error. I feel that this is correct solution but however, the solution is not passing all the test case I have. e.g {2,2} . Below is the code I have written in a brute force (worst case - n! complexity) approach. Any help would be greatly appreciated. I am not expecting the solution but would like to know where I am going wrong and how to get it right.

 package org.practice;
    import java.util.Arrays;
    import java.util.HashSet;
    import java.util.LinkedList;
    import java.util.List;

    public class LengthofLIS {
        int maxLength = 0;

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            LengthofLIS l = new LengthofLIS();
            int[] nums = { 2,2 };
            l.lengthOfLIS(nums);
        }

        public int lengthOfLIS(int[] nums) {
            if (nums.length == 1)
                return nums.length;
            List<Integer> hs = new LinkedList<>();
            dfs(nums, 0, 0, nums.length - 1, hs);
            System.out.println(maxLength);
            return maxLength;
        }

        public void dfs(int[] nums, int index, int length, int end, List<Integer> hs) {

        if (index > end) {
            return;
        }

        for (int i = index; i <= end; i++) {

            if (hs.size() == 0) {
                hs.add(nums[i]);
                length++;
            } else if (nums[i] > hs.get(hs.size() - 1)) {
                hs.add(nums[i]);
                length++;
            }

            else if (nums[i] <= hs.get(hs.size() - 1))
                continue;

            dfs(nums, i + 1, length, end, hs);
            //System.out.println("Printing " + Arrays.asList(hs));
            maxLength = Math.max(maxLength, hs.size());

            if (maxLength == nums.length)
                break;

            if (hs.size() != 0) {
                hs.remove(hs.get(hs.size() - 1));
                length--;
            }
        }
    }
    }

Body:
Since you didn't ask for any solution, I won't provide you one, and on the other hand, you could simply find lots of answers by just a simple search.

Here is what I understand from your code:

public void dfs(int[] nums, int index, int length, int end, List<Integer> hs) {
    if (index > end) {
        return;
    }
    for (int i = index; i <= end; i++) {
        if (hs.size() == 0) {
            hs.add(nums[i]);
            length++;
        }
        else if (nums[i] > hs.get(hs.size() - 1)) {
            hs.add(nums[i]);
            length++;
        }
        else if (i == end && nums[i] < hs.get(hs.size() - 1)) { //(1)
            maxLength = Math.max(maxLength, hs.size());
        }
        else if (nums[i] < hs.get(hs.size() - 1))
            continue;
        dfs(nums, i + 1, length, end, hs);
        if (hs.size() != 0) { //(2)
            hs.remove(hs.get(hs.size() - 1));
            length--;
        }
    }
}

what do you want to accomplish with that? consider the situation when the last element is the biggest element, then you will always print 0 because you'll never set maxLength.

your main problem is here. Because you remove a[i] , a[i+1] recursively from the list. suppose you have {2, 3, 100, 4, 5, 6, 1} instead of considering [2, 3, 4, 5, 6] longest list, your code will consider [2, 4, 5, 6] the longest list.


问:
How to call PL/SQL procedure in Ibatis from java
I have written a PLSQL stored procedure , i want to call the procedure and return the resultset back to the java in a hashmap or arraylist  format . I want to configure it in the xml file using Ibatis. kindly let me know how to configure in Ibatis.</p>

答:
```<code><procedure id="yourProc" parameterClass="yourclass" resultMap="result">
    {call yourProc(#param1#,#param2#)}
</procedure>
</code>```


问:
generating dynamic graphs from tableau onto an android app
Im trying to design an android app that will invoke some dynamically generated graphs from the tableau software. for example, the event can be a button click or selecting from a drop down...when this is done, another page should open with the graphs generated. is there an android developer api for tableau community edition or the desktop edition? or is it something that can be achieved through the server edition of tableau? i am a student and i am looking for something that is free (isnt tableau server edition a paid service?)
any help is appreciated...thanks!</p>

答:
Publish your dashboard in tableau public.

Click on share and copy embed code.

Create web view in android.

Design html for mobile view and paste that embed code.


问:
suddenly user_engagement event is missing in firebase analytics dashboard
Till yesterday (June 1st IST) I was able to see user_engagement event in firebase analytics dashboard under events tab but I could not find any user_engagement event from the morning of June 2nd. is it a issue in firebase?</p>

答: Reached Firebase support. Team has intentionally hidden the user_engagement event from firebase console for only one day. Now we are able to see that event in console. I also requested firebase team not to hide this event in future as it's very important.</p>


问:
InvokeCommand from Observable.Timer causes cross-thread issue
I have a ReactiveCommand that refreshes data and is bound to a Button in XAML. The functionality works fine, but I also want to execute the command on a timer.

I have the following code - SetupAutoRefresh is called from the ctor in my VM, but when the Observable fires, I get an exception with the message: "The calling thread cannot access this object because a different thread owns it."

VM:

```<code>private void SetupAutoRefresh() {
    Observable.Timer(TimeSpan.FromSeconds(5))
            .Select(_ => Unit.Default)
            .ObserveOn(RxApp.MainThreadScheduler)
            .InvokeCommand(RefreshData);

    RefreshData = ReactiveCommand.CreateFromTask(Refresh);
}

private async Task Refresh()
{
    var updatedData = await _repository.GetAll();
    Data.Merge(updatedData);
}

private ReactiveCommand<Unit, Unit> _refreshData;
public ReactiveCommand<Unit, Unit> RefreshData
{
    get { return _refreshData; }
    set { this.RaiseAndSetIfChanged(ref _refreshData, value); }
}

private IReactiveList<Model> _data;
public IReactiveList<Model> Data
{
    get { return _data; }
    set { this.RaiseAndSetIfChanged(ref _data, value); }
}
</code>```

XAML:

```<code><Button Grid.Column="2"
        Command="{Binding RefreshData}"
        Style="{StaticResource ToolbarButtonTheme}"
        Content="{StaticResource RefreshToolbarIcon}"
        ToolTip="Refresh Search"/>
</code>```

Debug output provides this stacktrace:

at System.Windows.Threading.Dispatcher.VerifyAccess()
    at System.Windows.DependencyObject.GetValue(DependencyProperty dp)
    at System.Windows.Controls.Primitives.ButtonBase.get_Command()
    at System.Windows.Controls.Primitives.ButtonBase.UpdateCanExecute()
    at System.Windows.Controls.Primitives.ButtonBase.OnCanExecuteChanged(Object >sender, EventArgs e)
    at
   System.Windows.Input.CanExecuteChangedEventManager.HandlerSink.OnCanExecuteChanged(Object sender, EventArgs e)
     at ReactiveUI.ReactiveCommand.OnCanExecuteChanged() in C:\projects\reactiveui\src\ReactiveUI\ReactiveCommand.cs:line 628

I've tried many different variations of attempting to schedule this on the RxApp.MainThreadScheduler but without any joy - ObserveOn, SubscribeOn, setting the output scheduler... none of which I had much hope for anyway.

Feel like I'm missing something obvious here, but have been banging my head against a brick wall for the whole afternoon. Surely this scenario is possible in RxUI?

答: Figured out the issue - looks like the Observable needed to be created on the UI thread. I missed it from the original post, but the SetupAutoRefresh method had  been called from another async method, which had switched context during a prior await.</p>

Body:
I have a ReactiveCommand that refreshes data and is bound to a Button in XAML. The functionality works fine, but I also want to execute the command on a timer.

I have the following code - SetupAutoRefresh is called from the ctor in my VM, but when the Observable fires, I get an exception with the message: "The calling thread cannot access this object because a different thread owns it."

VM:

private void SetupAutoRefresh() {
    Observable.Timer(TimeSpan.FromSeconds(5))
            .Select(_ => Unit.Default)
            .ObserveOn(RxApp.MainThreadScheduler)
            .InvokeCommand(RefreshData);

    RefreshData = ReactiveCommand.CreateFromTask(Refresh);
}

private async Task Refresh()
{
    var updatedData = await _repository.GetAll();
    Data.Merge(updatedData);
}

private ReactiveCommand<Unit, Unit> _refreshData;
public ReactiveCommand<Unit, Unit> RefreshData
{
    get { return _refreshData; }
    set { this.RaiseAndSetIfChanged(ref _refreshData, value); }
}

private IReactiveList<Model> _data;
public IReactiveList<Model> Data
{
    get { return _data; }
    set { this.RaiseAndSetIfChanged(ref _data, value); }
}

XAML:

<Button Grid.Column="2"
        Command="{Binding RefreshData}"
        Style="{StaticResource ToolbarButtonTheme}"
        Content="{StaticResource RefreshToolbarIcon}"
        ToolTip="Refresh Search"/>

Debug output provides this stacktrace:

at System.Windows.Threading.Dispatcher.VerifyAccess()
    at System.Windows.DependencyObject.GetValue(DependencyProperty dp)
    at System.Windows.Controls.Primitives.ButtonBase.get_Command()
    at System.Windows.Controls.Primitives.ButtonBase.UpdateCanExecute()
    at System.Windows.Controls.Primitives.ButtonBase.OnCanExecuteChanged(Object >sender, EventArgs e)
    at
   System.Windows.Input.CanExecuteChangedEventManager.HandlerSink.OnCanExecuteChanged(Object sender, EventArgs e)
     at ReactiveUI.ReactiveCommand.OnCanExecuteChanged() in C:\projects\reactiveui\src\ReactiveUI\ReactiveCommand.cs:line 628

I've tried many different variations of attempting to schedule this on the RxApp.MainThreadScheduler but without any joy - ObserveOn, SubscribeOn, setting the output scheduler... none of which I had much hope for anyway.

Feel like I'm missing something obvious here, but have been banging my head against a brick wall for the whole afternoon. Surely this scenario is possible in RxUI?


问:
How to show image from the imagePath in swift3
I have response from soap as image_path

(self.posts.value(forKey: "image_path") as! [String])[indexPath.row]

This is my response

"http://sf.iipl.info/ImageCSharp.aspx?Location=C:\\infinityhost\\demo11.iipl.info\\data\\app\\user_location_photo\\8000034939_Resize\\&FileName=1_35f28e55-ca31-4918-8b41-9eb7f3070ace"

i cant convert this response to my url, i want to show this image in my tableViewCell

```<code>public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        print((self.posts.value(forKey: "image_path") as! [String])[indexPath.row])

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AlllLocationTableViewCell

         let urlString = (self.posts.value(forKey: "image_path") as! [String])[indexPath.row] as String
        print("\(urlString)")

        let fileUrl = NSURL(fileURLWithPath: (self.posts.value(forKey: "image_path") as! [String])[indexPath.row])
        print(fileUrl as Any)

            let data = try? Data(contentsOf: fileUrl) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch

                self.Responseimage = UIImage(data: data!)!

        cell.LocationImage?.image = LocationImagView1
    return cell as UITableViewCell

    }
</code>```

答:
First of all import SDWebImage library into your project then write the following code in your view controller as per your requirements.

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCell", for: indexPath as IndexPath) as! ItemCell

    let urlStr = "https:\\images.com\image\12345.png".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

    print("URL :: \(urlStr!)");

    cell.imgItem.sd_setImage(with: URL(string: urlStr!), placeholderImage: UIImage(named: "item_placeholder"), options: [.refreshCached, .retryFailed, .allowInvalidSSLCertificates])

    }else{
        cell.imgItem.image = UIImage (named: "item_placeholder")
    }

    return cell
}
</code>```

Body:
I have response from soap as image_path

(self.posts.value(forKey: "image_path") as! [String])[indexPath.row]

This is my response

"http://sf.iipl.info/ImageCSharp.aspx?Location=C:\\infinityhost\\demo11.iipl.info\\data\\app\\user_location_photo\\8000034939_Resize\\&FileName=1_35f28e55-ca31-4918-8b41-9eb7f3070ace"

i cant convert this response to my url, i want to show this image in my tableViewCell

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        print((self.posts.value(forKey: "image_path") as! [String])[indexPath.row])

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AlllLocationTableViewCell

         let urlString = (self.posts.value(forKey: "image_path") as! [String])[indexPath.row] as String
        print("\(urlString)")

        let fileUrl = NSURL(fileURLWithPath: (self.posts.value(forKey: "image_path") as! [String])[indexPath.row])
        print(fileUrl as Any)

            let data = try? Data(contentsOf: fileUrl) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch

                self.Responseimage = UIImage(data: data!)!

        cell.LocationImage?.image = LocationImagView1
    return cell as UITableViewCell

    }

Body:
First of all import SDWebImage library into your project then write the following code in your view controller as per your requirements.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCell", for: indexPath as IndexPath) as! ItemCell

    let urlStr = "https:\\images.com\image\12345.png".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

    print("URL :: \(urlStr!)");

    cell.imgItem.sd_setImage(with: URL(string: urlStr!), placeholderImage: UIImage(named: "item_placeholder"), options: [.refreshCached, .retryFailed, .allowInvalidSSLCertificates])

    }else{
        cell.imgItem.image = UIImage (named: "item_placeholder")
    }

    return cell
}


问:
Copy data from Spreadsheet[LibreOffice Calc] to tables of Text Document[LibreOffice]
This was very interesting and challenging task for me. I want to copy data (1000s of rows with multiple columns) from Libre Office calc[spreadsheet] to the tables in Libre Office Writer[Text Document]. I spent almost a day to figure out the solution. Couldn't find the solution from any sites.</p>

答:
Copy the data[rows] from Spreadsheet.

Paste the same to the MS Word document[I did it by using Google docs as  I'm using ubuntu].The table is created with rows and columns which is same as copied data.

Copy the table from word document and paste it in the Libre office Text Document.

Create the table with number of rows and columns Libre office Text Document.

Copy the table from Libre office Text Document[copied in point(3)] and paste in the table which is created in point(4).

NOTE / CAUTION : If you skip or alter any steps, it wont work.


问:
React redux - componentDidMount fetching vs action
If I use react with redux - does it always necessary to fetch data from the redux action? Or it depends if I need the data to be stateful?

For example: I have a container which displays a user profile page. Can I fetch its data from the componentDidMount?

Thanks.

答:
Below a list of rules of thumb which could help you to determinate what kind of data should be put into Redux or in your component, I tried to write down few assumptions, but please in mind you know only the right answers :):

Is the data used by other part of your application? Probably in your case yes as a User Profile property like name could be used in different components, like the head of your site, profile details, basket.

Do you need to be able to create further derived data based on this original data?

Is the same data being used by multiple components? Probably yes.

Do you need to cache the data? Probably no.


问:
Apply operations on groupBy result of stream
I have a List of fruit which contains name and ID

```<code>List<Fruit> fruitList = Arrays.asList(new Fruit("apple", 1), new Fruit("orange", 2), new Fruit("orange", 3));
</code>```

I want to rename the fruit name with name_Id only if duplicate fruit name exists like in case of my list orange will rename to orange_2 and orange_3 but the apple will remain apple..
How can I do it in single stream expression.

The solution that I came up with is

```<code>Map<String, List<Fruit>> fruitMap = fruitList.stream().collect(Collectors.groupingBy(Fruit::getName));

        Set<Entry<String, List<Fruit>>> entry = fruitMap.entrySet();

        for (Entry<String, List<Fruit>> en : entry) {
            List<Fruit> fruit = en.getValue();
            if (fruit.size() > 1) {
                fruit.stream().map(d -> {
                    d.setName(d.getName() + "_" + d.getId());
                    return d;
                }).collect(Collectors.toList());
            }
        }
    }
</code>```

but this is way more than one stream expression.

答:
I don't think you can get away without streaming a few times. Here is a smaller solution and slightly more readable I think:</p>

```<code> Set<String> repeated = fruits.stream()
            .collect(Collectors.groupingBy(Fruit::getName, Collectors.counting()))
            .entrySet()
            .stream()
            .filter(e -> e.getValue() > 1)
            .map(Entry::getKey)
            .collect(Collectors.toSet());

    fruits.forEach(f -> {
        if (repeated.contains(f.getName())) {
            f.setName(f.getName() + "_" + f.getId());
        }
    });

    System.out.println(fruits); // [name = apple id = 1, name = orange_2 id = 2, name = orange_3 id = 3]
</code>```

Body:
I have a List of fruit which contains name and ID

List<Fruit> fruitList = Arrays.asList(new Fruit("apple", 1), new Fruit("orange", 2), new Fruit("orange", 3));

I want to rename the fruit name with name_Id only if duplicate fruit name exists like in case of my list orange will rename to orange_2 and orange_3 but the apple will remain apple..
How can I do it in single stream expression.

The solution that I came up with is

Map<String, List<Fruit>> fruitMap = fruitList.stream().collect(Collectors.groupingBy(Fruit::getName));

        Set<Entry<String, List<Fruit>>> entry = fruitMap.entrySet();

        for (Entry<String, List<Fruit>> en : entry) {
            List<Fruit> fruit = en.getValue();
            if (fruit.size() > 1) {
                fruit.stream().map(d -> {
                    d.setName(d.getName() + "_" + d.getId());
                    return d;
                }).collect(Collectors.toList());
            }
        }
    }

but this is way more than one stream expression.

Body:
I don't think you can get away without streaming a few times. Here is a smaller solution and slightly more readable I think:

 Set<String> repeated = fruits.stream()
            .collect(Collectors.groupingBy(Fruit::getName, Collectors.counting()))
            .entrySet()
            .stream()
            .filter(e -> e.getValue() > 1)
            .map(Entry::getKey)
            .collect(Collectors.toSet());

    fruits.forEach(f -> {
        if (repeated.contains(f.getName())) {
            f.setName(f.getName() + "_" + f.getId());
        }
    });

    System.out.println(fruits); // [name = apple id = 1, name = orange_2 id = 2, name = orange_3 id = 3]


问:
How to hide bpopup jquery?
How can i hide the bpopup jquery using a button? i have an ajax response that if the data return error has failed bpopup will be called. then inside my bpopup i have a "Got it!" button when the user click it, it will just close the bpopup

```<code> $.ajax({
     url: 'my_url',
     type: "POST",
     success: function(data){
         if(data.error == 'failed){
            $('#popup').bPopup({
               modalClose: false,
               opacity: 0.6,
               positionStyle: 'fixed'
            });

            //then my bpopup has a button "Got it!"
            $('.gotit').click(function(e) {
               //Code the will hide the bpopup.
            }
         }
     }
 })
</code>```

i have tried $('#popup).hide(); but it does not completely closed the bpopup.

BTW here's my popup html.

```<code> <div id="popup" style="display: none; min-width: 350px;">
     <span class="button b-close"><span>X</span></span>
     <div class="col-lg-12">
          <p><span class="ui-icon ui-icon-alert"></span>  The Code does not match the information provided.</p>
          <button class="btn btn-primary btn-sm pull-right gotit">Got it</button>
     </div>
 </div>
</code>```

答:
First of all

if(data.error == 'failed){ here ' is missed so add it and make it:-

if(data.error == 'failed'){

Closing pop-up can do it in two ways

1.Hide the pop-up directly.

```<code>$('.gotit').click(function() {

  $(this).closest('#popup').hide();//hidepop-up directly

  // also you can use $(this).parent().parent('#popup').hide();
});
</code>```

Example:-

$('.gotit').click(function() {

  $(this).closest('#popup').hide();//hidepop-up directly

  // also you can use $(this).parent().parent('#popup').hide();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="popup" style="display: block; min-width: 350px;"><!--changed disply:block to show you that how it will work -->
     <span class="button b-close"><span>X</span></span>
     <div class="col-lg-12">
          <p><span class="ui-icon ui-icon-alert"></span>  The Code does not match the information provided.</p>
          <button class="btn btn-primary btn-sm pull-right gotit">Got it</button>
     </div>
 </div></code>```

2.Trigger close button click event of pop-up (if close button code is already written and working)

```<code>$('.gotit').click(function() {
  $('.b-close').click();
});
</code>```

Example:-

$('.b-close').click(function() { //if your close button code is alwready written
  $('#popup').hide();
});

$('.gotit').click(function(){
  $('.b-close').click(); // trigger close button clik event
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="popup" style="display: block; min-width: 350px;"><!--changed disply:block to show you that how it will work -->
     <span class="button b-close"><span>X</span></span>
     <div class="col-lg-12">
          <p><span class="ui-icon ui-icon-alert"></span>  The Code does not match the information provided.</p>
          <button class="btn btn-primary btn-sm pull-right gotit">Got it</button>
     </div>
 </div></code>```

Title: How to hide bpopup jquery?

Body:
How can i hide the bpopup jquery using a button? i have an ajax response that if the data return error has failed bpopup will be called. then inside my bpopup i have a "Got it!" button when the user click it, it will just close the bpopup

 $.ajax({
     url: 'my_url',
     type: "POST",
     success: function(data){
         if(data.error == 'failed){
            $('#popup').bPopup({
               modalClose: false,
               opacity: 0.6,
               positionStyle: 'fixed'
            });

            //then my bpopup has a button "Got it!"
            $('.gotit').click(function(e) {
               //Code the will hide the bpopup.
            }
         }
     }
 })

i have tried $('#popup).hide(); but it does not completely closed the bpopup.

BTW here's my popup html.

     X

  The Code does not match the information provided.

          <button class="btn btn-primary btn-sm pull-right gotit">Got it</button>

Body:
First of all

if(data.error == 'failed){ here ' is missed so add it and make it:-

if(data.error == 'failed'){

Closing pop-up can do it in two ways

1.Hide the pop-up directly.

$('.gotit').click(function() {

  $(this).closest('#popup').hide();//hidepop-up directly

  // also you can use $(this).parent().parent('#popup').hide();
});

Example:-

$('.gotit').click(function() {

  $(this).closest('#popup').hide();//hidepop-up directly

  // also you can use $(this).parent().parent('#popup').hide();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="popup" style="display: block; min-width: 350px;"><!--changed disply:block to show you that how it will work -->
     <span class="button b-close"><span>X</span></span>
     <div class="col-lg-12">
          <p><span class="ui-icon ui-icon-alert"></span>&nbsp;&nbsp;The Code does not match the information provided.</p>
          <button class="btn btn-primary btn-sm pull-right gotit">Got it</button>
     </div>
 </div>

2.Trigger close button click event of pop-up (if close button code is already written and working)

$('.gotit').click(function() {
  $('.b-close').click();
});

Example:-

$('.b-close').click(function() { //if your close button code is alwready written
  $('#popup').hide();
});

$('.gotit').click(function(){
  $('.b-close').click(); // trigger close button clik event
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="popup" style="display: block; min-width: 350px;"><!--changed disply:block to show you that how it will work -->
     <span class="button b-close"><span>X</span></span>
     <div class="col-lg-12">
          <p><span class="ui-icon ui-icon-alert"></span>&nbsp;&nbsp;The Code does not match the information provided.</p>
          <button class="btn btn-primary btn-sm pull-right gotit">Got it</button>
     </div>
 </div>