问:
How to define a stable form for output tweets in getting real time tweets by python
My code works for getting real time tweets by Tweepy package of Python. I only want to get the created date and content of tweet so I define like below

```<code> def on_status(self, status):
    tweet_text = status.text
    tweet_created_date = str(status.created_at)
    tweet_data = {'Created_at':tweet_created_date,'Text':tweet_text}
    self.num_tweets += 1
    if self.num_tweets < 10001:
        with open('data.txt','a') as tf:
            #tf.write(tweet_data + '\n')
            tf.write(format(tweet_data) + '\n')
        return True
    else:
        return False
</code>```

But the outputs don't show exactly "Created_at:....., Text.....". It changes when the created date changes.

```<code>{'Text': 'RT @owen_author: Tiger Lily of Bangkok: a serial killer is on the loose in #BKK NaNoWriMo winner #Bangkoknoir #thri…', 'Created_at': '2017-06-01 22:18:28'}
{'Text': 'RT @MidwestBG: #NP Silent Stranger @SilentStranger6 - Bangkok by Night (Alternate Mix) on @MidwestBG', 'Created_at': '2017-06-01 22:18:38'}
{'Text': 'RT @IronWavesRadio: #NP Silent Stranger @SilentStranger6 - Bangkok by Night (Alternate Mix) on @IronWavesRadio', 'Created_at': '2017-06-01 22:18:42'}
{'Created_at': '2017-06-02 02:34:31', 'Text': '"RT @EXOXIUMINMAMA: 17.06.10\n2017 BANGKOK SUPER LIVE  \n#2017bkksuperlive \n\n#XIU의미소가우리에겐최고! \nXIUMIN's Smile is the BEST! \n\nรายละเอียด\n… "'}
{'Created_at': '2017-06-02 02:34:39', 'Text': '(w1-59)Stamps,Thailand stamps,MNH,wild animals,art,minerals #thailand #bangkok'}
{'Created_at': '2017-06-02 02:34:42', 'Text': 'RT @joeybirlem: reacting to cringey musicallys youtube video out tomorrow! bangkok vlog out on friday be readyyyyyyy'}
</code>```

So how can I fix this for all tweets of all day is shown in 1 form "Created_at:....., Text.....".

I'm very beginner so I need your help.

Thank you very much.

答:
You are using a dict (dictionary) type to store the tweets (tweet_data). Python's dictionaries do not maintain the order of the stored fields. Thus, you see some instances with {'Text': ..., 'Created_at': ...} while others with {'Created_at': ..., 'Text': ...}.

If you want to maintain the order of the fields, you can use OrderedDict type:

```<code>tweet_data = OrderedDict([('Created_at', tweet_created_date), ('Text', tweet_text)])
</code>```

Body:
My code works for getting real time tweets by Tweepy package of Python. I only want to get the created date and content of tweet so I define like below

 def on_status(self, status):
    tweet_text = status.text
    tweet_created_date = str(status.created_at)
    tweet_data = {'Created_at':tweet_created_date,'Text':tweet_text}
    self.num_tweets += 1
    if self.num_tweets < 10001:
        with open('data.txt','a') as tf:
            #tf.write(tweet_data + '\n')
            tf.write(format(tweet_data) + '\n')
        return True
    else:
        return False

But the outputs don't show exactly "Created_at:....., Text.....". It changes when the created date changes.

{'Text': 'RT @owen_author: Tiger Lily of Bangkok: a serial killer is on the loose in #BKK NaNoWriMo winner #Bangkoknoir #thri…', 'Created_at': '2017-06-01 22:18:28'}
{'Text': 'RT @MidwestBG: #NP Silent Stranger @SilentStranger6 - Bangkok by Night (Alternate Mix) on @MidwestBG', 'Created_at': '2017-06-01 22:18:38'}
{'Text': 'RT @IronWavesRadio: #NP Silent Stranger @SilentStranger6 - Bangkok by Night (Alternate Mix) on @IronWavesRadio', 'Created_at': '2017-06-01 22:18:42'}
{'Created_at': '2017-06-02 02:34:31', 'Text': '"RT @EXOXIUMINMAMA: 17.06.10\n2017 BANGKOK SUPER LIVE  \n#2017bkksuperlive \n\n#XIU의미소가우리에겐최고! \nXIUMIN's Smile is the BEST! \n\nรายละเอียด\n… "'}
{'Created_at': '2017-06-02 02:34:39', 'Text': '(w1-59)Stamps,Thailand stamps,MNH,wild animals,art,minerals #thailand #bangkok'}
{'Created_at': '2017-06-02 02:34:42', 'Text': 'RT @joeybirlem: reacting to cringey musicallys youtube video out tomorrow! bangkok vlog out on friday be readyyyyyyy'}

So how can I fix this for all tweets of all day is shown in 1 form "Created_at:....., Text.....".

I'm very beginner so I need your help.

Thank you very much.

Body:
You are using a dict (dictionary) type to store the tweets (tweet_data). Python's dictionaries do not maintain the order of the stored fields. Thus, you see some instances with {'Text': ..., 'Created_at': ...} while others with {'Created_at': ..., 'Text': ...}.

If you want to maintain the order of the fields, you can use OrderedDict type:

tweet_data = OrderedDict([('Created_at', tweet_created_date), ('Text', tweet_text)])


来源: stackexchange

问:
Raw query changes does not appeared in Entity Object c#
I've using raw query for update status of a column but after update, changes not appeared in Entity Object:</p>

```<code>CDIMDEntities oDB = new CDIMDEntities();
SystemYear oSY = oDB.SystemYears.FirstOrDefault(x => x.Year == Year);
if (oSY != null)
{
    string thsQuery = "UPDATE SystemYears SET  " + Column + " = {0} WHERE Id = {1}";
    oDB.Database.ExecuteSqlCommand(thsQuery, Status, oSY.Id);
    //After this changes appeared in database
    // But when again when trying get object ,It's showing old values
    oSY = oDB.SystemYears.FirstOrDefault(x => x.Id == oSY.Id);
    this.SystemYearRep.SaveSystemYear(oSY);
}
</code>```

答:
You are executing your raw query on your database, which at the point of initialisation of your CDIMDEntities() will not see that change.

```<code>using(CDIMDEntities oDB = new CDIMDEntities())
{
    SystemYear oSY = oDB.SystemYears.FirstOrDefault(x => x.Year == Year);
    if (oSY != null)
    {
        string thsQuery = "UPDATE SystemYears SET  " + Column + " = {0} WHERE Id = {1}";
        oDB.Database.ExecuteSqlCommand(thsQuery, Status, oSY.Id);

        // Your raw query will not affect the SystemYears at this point.
        oSY = oDB.SystemYears.FirstOrDefault(x => x.Id == oSY.Id);

        // This does nothing at this point.
        this.SystemYearRep.SaveSystemYear(oSY);
    }
}

// New up a another context
using(var CDIMDEntities oDB2 = new CDIMDEntities())
{
   // You will see the changes here
   SystemYear oSY = oDB2.SystemYears.FirstOrDefault(x => x.Year == Year);
}
</code>```

A good practice when new-ing up DbContext is by using the using keyword, as it helps to dispose the context after usage.

ContentLicense: CC BY-SA 3.0

Body:
I've using raw query for update status of a column but after update, changes not appeared in Entity Object:

CDIMDEntities oDB = new CDIMDEntities();
SystemYear oSY = oDB.SystemYears.FirstOrDefault(x => x.Year == Year);
if (oSY != null)
{
    string thsQuery = "UPDATE SystemYears SET  " + Column + " = {0} WHERE Id = {1}";
    oDB.Database.ExecuteSqlCommand(thsQuery, Status, oSY.Id);
    //After this changes appeared in database
    // But when again when trying get object ,It's showing old values
    oSY = oDB.SystemYears.FirstOrDefault(x => x.Id == oSY.Id);
    this.SystemYearRep.SaveSystemYear(oSY);
}

Body:
You are executing your raw query on your database, which at the point of initialisation of your CDIMDEntities() will not see that change.

using(CDIMDEntities oDB = new CDIMDEntities())
{
    SystemYear oSY = oDB.SystemYears.FirstOrDefault(x => x.Year == Year);
    if (oSY != null)
    {
        string thsQuery = "UPDATE SystemYears SET  " + Column + " = {0} WHERE Id = {1}";
        oDB.Database.ExecuteSqlCommand(thsQuery, Status, oSY.Id);

        // Your raw query will not affect the SystemYears at this point.
        oSY = oDB.SystemYears.FirstOrDefault(x => x.Id == oSY.Id);

        // This does nothing at this point.
        this.SystemYearRep.SaveSystemYear(oSY);
    }
}

// New up a another context
using(var CDIMDEntities oDB2 = new CDIMDEntities())
{
   // You will see the changes here
   SystemYear oSY = oDB2.SystemYears.FirstOrDefault(x => x.Year == Year);
}

A good practice when new-ing up DbContext is by using the using keyword, as it helps to dispose the context after usage.


问:
How should I create model class to call API (Using MVC pattern)?
Currently I am calling an API in viewcontroller itself but this is not good programming practice as per MVC.

Here is my code:

```<code>-(void)fetchData{

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"]];
    [request setHTTPMethod:@"GET"];
    [request addValue:@"text/plain" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"text/plain" forHTTPHeaderField:@"Accept"];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
        NSData * responseData = [requestReply dataUsingEncoding:NSUTF8StringEncoding];
        if (responseData != nil) {

            NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
            NSLog(@"requestReply: %@", jsonDict);
            self.content = jsonDict[@"rows"];
            self.navigationTitle = jsonDict[@"title"];

            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];

            });

            NSLog(@"result %@", self.content);

        }

    }] resume];

}
</code>```

Can you please suggest how should I arrange code/file to follow MVC  pattern?

If I create separate model class how should I manage existing code and how I transfer response to viewcontroller?

答:
Swift 3
Try this:

```<code>class WebRequester: NSObject {

    static let shared = WebRequester()

    func request(vc:UIViewController, url: String, parameter:String?, callback:@escaping (_ result:NSDictionary?, _ error:NSError?) -> Void) {

        let requestURL = url

        print("..............................")
        print("URL: ",requestURL)
        print("Parameter: ",parameter ?? "nil")
        print("..............................")

        var request = URLRequest(url: URL(string:requestURL)!)
        request.httpMethod = "POST"

        if parameter != nil {
            request.httpBody = parameter!.data(using: .utf8)
        }

        let session = URLSession.shared
        let task = session.dataTask(with: request, completionHandler: {data, response, error in
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
            DispatchQueue.main.async {
                if error == nil {
                    do {
                        let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
                        print(json)
                        let dic = json as? NSDictionary
                        if dic != nil {
                            callback(json as? NSDictionary, nil)
                        }
                        else {
                            vc.alert(title: "Oops..", message: "Something went wrong please try again later")
                        }
                    }
                    catch {
                        print(error.localizedDescription)
                        callback(nil,error as NSError?)
                    }
                }
                else {
                    print(error?.localizedDescription ?? "")
                    callback(nil, error as NSError?)
                }
            }
        })
        task.resume()
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
    }
}
</code>```

ObjectiveC

WebRequester.h

```<code>#import <Foundation/Foundation.h>

@interface WebRequester : NSObject

+(id)shared;

-(void)request1:(NSString *)url parameter:(NSString *)params callback:(void(^)(NSDictionary *result, NSError *error))callback;

@end
</code>```

WebRequester.m

```<code>#import "WebRequester.h"

@implementation WebRequester

+(id)shared {
    static WebRequesterObjC *sharedMyManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedMyManager = [[self alloc] init];
    });
    return sharedMyManager;
}

-(void)request1:(NSString *)url parameter:(NSString *)params callback:(void(^)(NSDictionary *result, NSError *error))callback {

    NSString *requestUrl = url;

    NSLog(@"====================");
    NSLog(@"%@",requestUrl);
    NSLog(@"%@",params);
    NSLog(@"====================");

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:requestUrl]];
    request.HTTPMethod = @"POST";

    if (params != nil) {
        request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding];
    }

    NSURLSession* session = [[NSURLSession alloc] init];
    NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            if (data != nil) {
                NSError * err;
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];
                if (err == nil) {
                    callback(dic,nil);
                }
                else {
                    callback(nil,err);
                }
            }
        }
        else {
            callback(nil,error);
        }
    }];
    [task resume];
}

@end
</code>```

call as follow

```<code>  [WebRequesterObjC.shared request1:<#url#> parameter:params callback:^(NSDictionary *result, NSError *error) {
        if (error == nil) {
            NSLog(@"%@",result)
        }
  }];
</code>```

Body:
Currently I am calling an API in viewcontroller itself but this is not good programming practice as per MVC.

Here is my code:

-(void)fetchData{

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"]];
    [request setHTTPMethod:@"GET"];
    [request addValue:@"text/plain" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"text/plain" forHTTPHeaderField:@"Accept"];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
        NSData * responseData = [requestReply dataUsingEncoding:NSUTF8StringEncoding];
        if (responseData != nil) {

            NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
            NSLog(@"requestReply: %@", jsonDict);
            self.content = jsonDict[@"rows"];
            self.navigationTitle = jsonDict[@"title"];

            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];

            });

            NSLog(@"result %@", self.content);

        }

    }] resume];

}

Can you please suggest how should I arrange code/file to follow MVC  pattern?

If I create separate model class how should I manage existing code and how I transfer response to viewcontroller?

Body:
Swift 3
Try this:

class WebRequester: NSObject {

    static let shared = WebRequester()

    func request(vc:UIViewController, url: String, parameter:String?, callback:@escaping (_ result:NSDictionary?, _ error:NSError?) -> Void) {

        let requestURL = url

        print("..............................")
        print("URL: ",requestURL)
        print("Parameter: ",parameter ?? "nil")
        print("..............................")

        var request = URLRequest(url: URL(string:requestURL)!)
        request.httpMethod = "POST"

        if parameter != nil {
            request.httpBody = parameter!.data(using: .utf8)
        }

        let session = URLSession.shared
        let task = session.dataTask(with: request, completionHandler: {data, response, error in
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
            DispatchQueue.main.async {
                if error == nil {
                    do {
                        let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
                        print(json)
                        let dic = json as? NSDictionary
                        if dic != nil {
                            callback(json as? NSDictionary, nil)
                        }
                        else {
                            vc.alert(title: "Oops..", message: "Something went wrong please try again later")
                        }
                    }
                    catch {
                        print(error.localizedDescription)
                        callback(nil,error as NSError?)
                    }
                }
                else {
                    print(error?.localizedDescription ?? "")
                    callback(nil, error as NSError?)
                }
            }
        })
        task.resume()
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
    }
}

ObjectiveC

WebRequester.h

#import <Foundation/Foundation.h>

@interface WebRequester : NSObject

+(id)shared;

-(void)request1:(NSString *)url parameter:(NSString *)params callback:(void(^)(NSDictionary *result, NSError *error))callback;

@end

WebRequester.m

#import "WebRequester.h"

@implementation WebRequester

+(id)shared {
    static WebRequesterObjC *sharedMyManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedMyManager = [[self alloc] init];
    });
    return sharedMyManager;
}

-(void)request1:(NSString *)url parameter:(NSString *)params callback:(void(^)(NSDictionary *result, NSError *error))callback {

    NSString *requestUrl = url;

    NSLog(@"====================");
    NSLog(@"%@",requestUrl);
    NSLog(@"%@",params);
    NSLog(@"====================");

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:requestUrl]];
    request.HTTPMethod = @"POST";

    if (params != nil) {
        request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding];
    }

    NSURLSession* session = [[NSURLSession alloc] init];
    NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            if (data != nil) {
                NSError * err;
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];
                if (err == nil) {
                    callback(dic,nil);
                }
                else {
                    callback(nil,err);
                }
            }
        }
        else {
            callback(nil,error);
        }
    }];
    [task resume];
}

@end

call as follow

  [WebRequesterObjC.shared request1:<#url#> parameter:params callback:^(NSDictionary *result, NSError *error) {
        if (error == nil) {
            NSLog(@"%@",result)
        }
  }];


问:
FFMPEG command issue for merging mp4 videos in android
I am using following FFMPEG command for merging mp4 videos in android. But video is rotated 90 degree after merging.

I am stuck from two days .If any idea it would be highly appriciated.

Thanks in Advance !

```<code>complexCommand = new String[] {
                "ffmpeg",
                "-y",
                "-i",
                recordpath + "Vid1.mp4",
                "-i",
                recordpath + "Vid2.mp4",
                "-strict",
                "experimental",
                "-filter_complex",
                "[0:v]scale=w=640:h=480[v1]; [1:v]scale=w=640:h=480[v2]; [v1][0:a][v2][1:a] concat=n=2:v=1:a=1 [v] [a]",
                "-map", "[v]", "-map", "[a]", "-b", "2097k", "-vcodec",
                "mpeg4","-ab","64k","-ac","2","-ar","22050", recordpath + "Outputnew.mp4"};
</code>```

Body:
I am using following FFMPEG command for merging mp4 videos in android. But video is rotated 90 degree after merging.

I am stuck from two days .If any idea it would be highly appriciated.

Thanks in Advance !

complexCommand = new String[] {
                "ffmpeg",
                "-y",
                "-i",
                recordpath + "Vid1.mp4",
                "-i",
                recordpath + "Vid2.mp4",
                "-strict",
                "experimental",
                "-filter_complex",
                "[0:v]scale=w=640:h=480[v1]; [1:v]scale=w=640:h=480[v2]; [v1][0:a][v2][1:a] concat=n=2:v=1:a=1 [v] [a]",
                "-map", "[v]", "-map", "[a]", "-b", "2097k", "-vcodec",
                "mpeg4","-ab","64k","-ac","2","-ar","22050", recordpath + "Outputnew.mp4"};

Body:
Below is the working command for merging two videos and maintaining aspect ratio of both

complexCommand = new String[]{"-y", "-i", file1.toString(), "-i", file2.toString(), "-strict", "experimental", "-filter_complex",
                "[0:v]scale=iw*min(1920/iw\\,1080/ih):ih*min(1920/iw\\,1080/ih), pad=1920:1080:(1920-iw*min(1920/iw\\,1080/ih))/2:(1080-ih*min(1920/iw\\,1080/ih))/2,setsar=1:1[v0];[1:v] scale=iw*min(1920/iw\\,1080/ih):ih*min(1920/iw\\,1080/ih), pad=1920:1080:(1920-iw*min(1920/iw\\,1080/ih))/2:(1080-ih*min(1920/iw\\,1080/ih))/2,setsar=1:1[v1];[v0][0:a][v1][1:a] concat=n=2:v=1:a=1",
                "-ab", "48000", "-ac", "2", "-ar", "22050", "-s", "1920x1080", "-vcodec", "libx264", "-crf", "27", "-q", "4", "-preset", "ultrafast", rootPath + "/output.mp4"};


问:
grab data from mysql and echo into an array
I am quite new to PHP and have a problem that I am running into.

At the moment my site is locked to only IP addresses I put into my code manually. I am trying to automate this by inserting ip addresses into mysql database.

Currently my index.php file looks like this -

```<code>$allowlist = array(
'86.162.244.16','79.88.293.33'
);
</code>```

As you can see above, those are the IP addresses that do not get redirected to a 'coming soon' page.

I've created a table in my DB called allowedips, which is where I am storing the IP's I want to give access too.

How can I automatically grab the info from the DB and insert it into that array? Everything I have tried so far just stops the site from working.

So far I have tried

```<code>$allowlist = array(

$query1 = mysql_query ( "SELECT * FROM `allowedips`" );
while ( $all = mysql_fetch_object ( $query1 ) )
{
echo $all->ip;
}
);
</code>```

Kind Regards,
Jay

答:
firstly, if you are grabbing data from the DB ...you can either grab it in form of an Associative array, Numerical array(sometimes Multidimensional Array if the Row count is more than one) or in form of Object....if you are using object oriented PHP......

for example:
$dbdata = mysql_fetch_assoc($query);

the variable $dbdata is an associative array

if $dbdata = mysqql_fetch_array($query);
then the variable $dbdata is a numerical array..

to classically check the content of your variable you can use the var_dump() function......and then you can use the in_array() function to check if the ip_address are in the array....and that is;

```<code>if(in_array("THE_SPECIFIC_IP_ADDRESS", $arrayOfIPaddress)){
     echo"coming soon";
//enter any code you want here
}else{
    echo"not coming soon";
}
</code>```

Body:
I am quite new to PHP and have a problem that I am running into.

At the moment my site is locked to only IP addresses I put into my code manually. I am trying to automate this by inserting ip addresses into mysql database.

Currently my index.php file looks like this -

$allowlist = array(
'86.162.244.16','79.88.293.33'
);

As you can see above, those are the IP addresses that do not get redirected to a 'coming soon' page.

I've created a table in my DB called allowedips, which is where I am storing the IP's I want to give access too.

How can I automatically grab the info from the DB and insert it into that array? Everything I have tried so far just stops the site from working.

So far I have tried

$allowlist = array(

$query1 = mysql_query ( "SELECT * FROM `allowedips`" );
while ( $all = mysql_fetch_object ( $query1 ) )
{
echo $all->ip;
}
);

Kind Regards,
Jay

Body:
firstly, if you are grabbing data from the DB ...you can either grab it in form of an Associative array, Numerical array(sometimes Multidimensional Array if the Row count is more than one) or in form of Object....if you are using object oriented PHP......

for example:
$dbdata = mysql_fetch_assoc($query);

the variable $dbdata is an associative array

if $dbdata = mysqql_fetch_array($query);
then the variable $dbdata is a numerical array..

to classically check the content of your variable you can use the var_dump() function......and then you can use the in_array() function to check if the ip_address are in the array....and that is;

if(in_array("THE_SPECIFIC_IP_ADDRESS", $arrayOfIPaddress)){
     echo"coming soon";
//enter any code you want here
}else{
    echo"not coming soon";
}


问:
Is there any way to open files from Azure storage account in online office 365?
I am creating an application where I do interaction with files in Azure storage account with java services. I want to open uploaded files in office 365 so that I can edit them. How I can do that?

Is there any reference code available for the same to do it with service from java?

答:
To view the Office files (Word, Excel, PowerPoint) in Office 365 online document viewer, you can create a link to your blob by using Online Doc Viewer utility. Essentially the link that will be created will be:

https://view.officeapps.live.com/op/view.aspx?src=<Encoded URL of Blob>

Please note that:

The documents you open through this utility will be opened in read-only mode. You won't be able to edit these documents unless you save those documents in One Drive.

If the blob container containing the documents has private ACL, then you will need to create a Shared Access Signature with at least Read permission to view the documents.


问:
AS3: Can we skip an optional parameter and assign value to the parameter after the skipped one?
Can we skip an optional parameter and assign value to the parameter after the skipped one?

For example I have a function:

```<code>public function Dialog(message:String,title:String="Note",dialogsize:int=99):void
{
}
</code>```

I can easily call the function with a message and a title:

```<code> Dialog("HELLO","Intro");
</code>```

Is there a way to skip the title and just pass in the dialogsize? I've tried it but can't make it work:

```<code>Dialog("HELLO",,dialogsize);
</code>```

Is it possible to skip some optional parameters without using (rest) parameter?

答:
You can pass null, for a "defaulted" parameter, and as3 will use the default value -- same as if you had omitted it completely:

```<code>Dialog("HELLO",null,dialogsize);
</code>```

Edit

I stand corrected -- I could swear that I've done this before, with success... but my tests (and those of @www0z0k also) indicate otherwise.  That means that, in order to have the above work as described, you'd need to modify the function's implementation too.

Something like this will do the trick:

```<code>public function Dialog(message:String,title:String=null,dialogsize:int=99):void
{
    if(title===null) title = "Note";

}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Can we skip an optional parameter and assign value to the parameter after the skipped one?

For example I have a function:

public function Dialog(message:String,title:String="Note",dialogsize:int=99):void
{
}

I can easily call the function with a message and a title:

 Dialog("HELLO","Intro");

Is there a way to skip the title and just pass in the dialogsize? I've tried it but can't make it work:

Dialog("HELLO",,dialogsize);

Is it possible to skip some optional parameters without using (rest) parameter?

Body:
You can pass null, for a "defaulted" parameter, and as3 will use the default value -- same as if you had omitted it completely:

Dialog("HELLO",null,dialogsize);

Edit

I stand corrected -- I could swear that I've done this before, with success... but my tests (and those of @www0z0k also) indicate otherwise.  That means that, in order to have the above work as described, you'd need to modify the function's implementation too.

Something like this will do the trick:

public function Dialog(message:String,title:String=null,dialogsize:int=99):void
{
    if(title===null) title = "Note";

}


问:
Entrust - This cache store does not support tagging in Laravel 5.1
After searching all possible answers, I still dont know how to solve this problem. I'm using zizaco/entrust package for laravel, and everytime I save data into the database it returns an error:

BadMethodCallException in Repository.php line 294:

  This cache store does not support tagging.

They said, I just have to use CACHE_DRIVER=array and others said use memcached or redis. Do I have to use array? Some say that it is the right way to solve the problem. Or can I use cache without tagging ?

T.I.A.

答:
In your .env file, change:

```<code>CACHE_DRIVER=file
</code>```

TO

```<code>CACHE_DRIVER=array
</code>```

After this change you might have to execute the following commands in the command line:

```<code>php artisan config:clear
php artisan config:cache
</code>```

Body:
In your .env file, change:

CACHE_DRIVER=file

TO

CACHE_DRIVER=array

After this change you might have to execute the following commands in the command line:

php artisan config:clear
php artisan config:cache


问:
What is a real-world use-case for JavaScript's void operator?
Why would someone write:

```<code>function () {
    if (err) {
        return void console.log(err)
    }
}
</code>```

instead of:

```<code>function () {
    if (err) {
        console.log(err)
        return
    }
}
</code>```

Has anyone used the void operator at all? I have seen it being used as in the example case above, but very very rarely.

Update

console.log might be a poor example as it returns void itself. Let me show another use I have seen in an express app:

```<code>function (req, res) {
    ...
    // Some error occurred
    if (err) {
        return void res.send(foo)
        // `send` returns a `Response` instance
    }
}
</code>```

In eslint's source code for example, it is being used quite a lot:

config-initializer.js

jshint.js - BIG FILE WARNING!

consistent-return.js

答:
One use case is that it always returns undefined when the undefined itself was not doing the same. In most modern browsers window.undefined is not writable but can be shadowed as its a valid variable name. Well, I wouldn't say its a real case scenario but a foolproof way to return undefined.

function whendefined(){
    var undefined = 'defined';
    return undefined;
}

console.log(whendefined());

function neverdefined(){
    var undefined = 'defined';
    return void 0;
}

console.log(neverdefined());```
</div>
</div>
</p>

<p>MDN community docs has something in the same lines too</p>

<blockquote>
  <p>This operator allows inserting expressions that produce side effects
  into places where an expression that evaluates to undefined is
  desired.
  The void operator is often used merely to obtain the undefined
  primitive value, usually using "void(0)" (which is equivalent to "void
  0"). In these cases, the global variable undefined can be used instead
  (assuming it has not been assigned to a non-default value).</p>
</blockquote>

<p>The use in the es-lint example is probably having only a file size consideration as these won't be minified in any way.</p>

```"undefined".length; //9
"void 0".length;//6
```

10,000 downloads can save ~30,000 bytes.

Consistent Return has nothing to do with this directly, it just makes sure return values are specified explicitly and consistently. All through the code the consideration for using void 0 seems to be file size consideration and may be some old style coding of author carried over from old browsers where even window.undefined can be overridden.

Body:
Why would someone write:

function () {
    if (err) {
        return void console.log(err)
    }
}

instead of:

function () {
    if (err) {
        console.log(err)
        return
    }
}

Has anyone used the void operator at all? I have seen it being used as in the example case above, but very very rarely.

Update

console.log might be a poor example as it returns void itself. Let me show another use I have seen in an express app:

function (req, res) {
    ...
    // Some error occurred
    if (err) {
        return void res.send(foo)
        // `send` returns a `Response` instance
    }
}

In eslint's source code for example, it is being used quite a lot:

config-initializer.js

jshint.js - BIG FILE WARNING!

consistent-return.js

Body:
One use case is that it always returns undefined when the undefined itself was not doing the same. In most modern browsers window.undefined is not writable but can be shadowed as its a valid variable name. Well, I wouldn't say its a real case scenario but a foolproof way to return undefined.

function whendefined(){
    var undefined = 'defined';
    return undefined;
}

console.log(whendefined());

function neverdefined(){
    var undefined = 'defined';
    return void 0;
}

console.log(neverdefined());

MDN community docs has something in the same lines too

This operator allows inserting expressions that produce side effects
  into places where an expression that evaluates to undefined is
  desired.
  The void operator is often used merely to obtain the undefined
  primitive value, usually using "void(0)" (which is equivalent to "void
  0"). In these cases, the global variable undefined can be used instead
  (assuming it has not been assigned to a non-default value).

The use in the es-lint example is probably having only a file size consideration as these won't be minified in any way.

"undefined".length; //9
"void 0".length;//6

10,000 downloads can save ~30,000 bytes.

Consistent Return has nothing to do with this directly, it just makes sure return values are specified explicitly and consistently. All through the code the consideration for using void 0 seems to be file size consideration and may be some old style coding of author carried over from old browsers where even window.undefined can be overridden.


问:
Bypass a Java error
Is there a way that I can bypass an error message in Java ?
What if I get an error, but there is no viable way to change my program ? What if I suspect that I might get an error from a block of code, but I don't know when or if it will happen ? There's been a lot of times where I had to let something be in my code, but produced an error. For example, converting a string into a float with parseFloat().

Anyway to do this ?

答:
Yes, of course there is a way to do this, it is called Exception Handling.

Begin by reading about the Exception class, and the try catch and finally keywords.

Here is a starting point: https://www.tutorialspoint.com/java/java_exceptions.htm

Title: Bypass a Java error


问:
Tensorflow with GPU on Google Cloud
I have a model on Google Machine Learning using tensorflow, and it's ok.
Now I want to do some predicts using the GPU.
I saw this link, but it tells about trainning with GPU not prediction. There's nothing about GPU in prediction session.

Someone Know if its possible to do prediction using google machine learning engine with GPU? Or if I use the trainning with GPU, my Prediction automatically run with GPU?

I'm using the follow commandline:

```<code>gcloud ml-engine predict --model ${MODEL_NAME} --json-instances request.json
</code>```

This command works, but It's using CPU.
Additional information: My model is published in us-east1 zone, and my scale is automatically.

答:
You cannot choose to use the GPU for prediction in ml-engine. It's unclear whether they are using GPUs by default -- I would link to documentation but there is none available.

I am sure, however, that they are not using TPUs. Currently, Google is only using TPUs for internal services; although they have created a TPU cloud exclusively for researchers to experiment with: https://yourstory.com/2017/05/google-cloud-tpus-machine-learning-models-training/

If you want more control over how your prediction is run, for the same price you can configure a Google Compute Engine with a high-powered Tesla K80 GPU. Your Tensorflow model will work there, too, and it is straightforward to set up.

My suggestion would be to make benchmark predictions using your GCE instance and then compare them to the ml-engine. If ml-engine is faster than GCE, then Google is probably using GPUs for prediction. Surely, their goal is to provide GPUs and TPUs as an ml-engine in the future, but demand is overloading the HPC cloud these days.

Title: Tensorflow with GPU on Google Cloud

Body:
I have a model on Google Machine Learning using tensorflow, and it's ok.
Now I want to do some predicts using the GPU.
I saw this link, but it tells about trainning with GPU not prediction. There's nothing about GPU in prediction session.

Someone Know if its possible to do prediction using google machine learning engine with GPU? Or if I use the trainning with GPU, my Prediction automatically run with GPU?

I'm using the follow commandline:

gcloud ml-engine predict --model ${MODEL_NAME} --json-instances request.json

This command works, but It's using CPU.
Additional information: My model is published in us-east1 zone, and my scale is automatically.


问:
RSpec - Dependant objects
I'm fairly new to testing with RSpec, and have been on this problem for a while.

I have the following test for a user to delete their account.

```<code>require 'rails_helper'

feature 'delete account' do
  let!(:user) {create :user, :basic}

  scenario 'successfully' do

    login_as(user)
    visit dashboard_path
    click_link 'Settings'
    click_link 'Cancel my account'

    expect(page).to have_content("Your account has been cancelled.")
  end
end
</code>```

When running the test, I get the following error;

```<code>1) delete account successfully
 Failure/Error: <%= account.radio_button :plan_id, @plan.id, data: { name: @plan.name, amount: @plan.amount}, checked: true, class: 'hidden' %>

 ActionView::Template::Error:
   undefined method `id' for nil:NilClass
</code>```

Here is the controller code. When the test clicks 'Settings' the show page is rendered. The issue is that no plans exist, but they are irrelevant to what I am testing.

```<code>def show
  @plan = Plan.find_by(name: 'Premium')
  @subscription_pending_cancel =
  Account.check_subscription_status(@account)
end
</code>```

I could create the plan before the test runs, which passes the test.

```<code> before do
   Plan.create(name: 'Premium')
 end
</code>```

However having to create objects like this doesn't seem sustainable as the test suite grows - particularly in relation to speed and keeping the test DB clean.

The question is - does a real object (being a plan in my case) need to be created/persisted to the db for a test such as the above, or is there another way?

答:
Testing can be done on several levels on "reality", and each of them have their purposes.

You have written an rspec feature spec. These are in the category of so called "acceptance" tests.

The RSpec documentation says:

Feature specs are high-level tests meant to exercise slices of functionality
  through an application. They should drive the application only via its external
  interface, usually web pages.

So point of these test are to be as real as possible, and this also means having as objects as real as possible.

Your observation is correct, there is a lot of setup to be done for these kinds of tests, and they do get quite slow quite fast. And that's why you don't usually write too many of these.

The fast test are in separate category. These are called "unit" test. The point of them is to test only a single class of method, and if there are any dependencies to other classes you should stub them.

These are the kind of tests you should having a lot. And you should drive to write those classes in such a manner that you can easily stub out all the external dependencies (db for example).

This concept is called the testing pyramid. https://martinfowler.com/bliki/TestPyramid.html

Title: RSpec - Dependant objects

Body:
I'm fairly new to testing with RSpec, and have been on this problem for a while.

I have the following test for a user to delete their account.

require 'rails_helper'

feature 'delete account' do
  let!(:user) {create :user, :basic}

  scenario 'successfully' do

    login_as(user)
    visit dashboard_path
    click_link 'Settings'
    click_link 'Cancel my account'

    expect(page).to have_content("Your account has been cancelled.")
  end
end

When running the test, I get the following error;

1) delete account successfully
 Failure/Error: <%= account.radio_button :plan_id, @plan.id, data: { name: @plan.name, amount: @plan.amount}, checked: true, class: 'hidden' %>

 ActionView::Template::Error:
   undefined method `id' for nil:NilClass

Here is the controller code. When the test clicks 'Settings' the show page is rendered. The issue is that no plans exist, but they are irrelevant to what I am testing.

def show
  @plan = Plan.find_by(name: 'Premium')
  @subscription_pending_cancel =
  Account.check_subscription_status(@account)
end

I could create the plan before the test runs, which passes the test.

 before do
   Plan.create(name: 'Premium')
 end

However having to create objects like this doesn't seem sustainable as the test suite grows - particularly in relation to speed and keeping the test DB clean.

The question is - does a real object (being a plan in my case) need to be created/persisted to the db for a test such as the above, or is there another way?


问:
HOC component on HTMLElement
i wrote this nasty beast:

```<code>export type DelayHoverElementProps<TElement extends HTMLElement> = React.HTMLProps<TElement>
& {
    hoverDelay: number,
    onHoverChanged: (isHovering: boolean) => void
};

export function DelayHoverElementFactory<
    K extends keyof HTMLElementTagNameMap,
    E extends HTMLElementTagNameMap[K],
    C extends React.ComponentClass<DelayHoverElementProps<E>>
>(tagName: K): C {
    return class extends React.Component<
        DelayHoverElementProps<E>,
        { isHovering: boolean }
    >{
        constructor() {
            super();
            this.state = { isHovering: true };
        }

        private _delayTimer: NodeJS.Timer;

        private onMouseOver = (e: React.MouseEvent<E>) => {
            const { hoverDelay, onHoverChanged } = this.props;
            clearTimeout(this._delayTimer);
            this.setState({ isHovering: true }, () => {
                this._delayTimer = setTimeout(() => {
                    onHoverChanged(true);
                }, hoverDelay);
            });
        };

        private onMouseOut = (e: React.MouseEvent<E>) => {
            const { hoverDelay, onHoverChanged } = this.props;
            clearTimeout(this._delayTimer);
            this.setState({ isHovering: false }, () => {
                this._delayTimer = setTimeout(() => {
                    onHoverChanged(false);
                }, hoverDelay);
            });
        };

        render() {
            const { hoverDelay, onHoverChanged, ...props } = this.props;
            const tagProps: React.HTMLProps<E> = {
                ...props,
                onMouseOver: this.onMouseOver,
                onMouseOut: this.onMouseOut
            };

            return React.createElement(tagName, tagProps);
        }
    } as any; // <---
}
</code>```

witch this test usage: (mocha, chai, sinon, enzyme; test will pass)

```<code>const props: DelayHoverElementProps<HTMLDivElement> = {
    hoverDelay: 200,
    onHoverChanged: index => { },
    className: 'test',
    children: 'content'
};
const spy = sinon.spy(props, 'onHoverChanged');
const expected =
    <div className="test" onMouseOver={()=>{}} onMouseOut={()=>{}}>content</div>;

const Div = DelayHoverElementFactory('div');
const actual = shallow(<Div {...props as any} />) // <---
// equalJsx is custom asserting method, with will convert JSX to string and compare that ...
expect(actual).to.equalJsx(expected);

actual.find('div').simulate('mouseOver');
expect(spy).to.be.not.called;
await new Promise(resolve => setTimeout(resolve, props.hoverDelay))
expect(spy).to.be.calledOnce;
expect(spy).to.be.calledWith(true);
</code>```

it i remove these as any then i get these errors:

```<code>// first
Type 'typeof (Anonymous class)' is not assignable to type 'C'.

// second
Type '{ defaultChecked?: boolean; defaultValue?: string | string[]; suppressContentEditableWarning?: bo...' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<DelayHoverElementProps<HTMLDivElement>, ...'.
  Type '{ defaultChecked?: boolean; defaultValue?: string | string[]; suppressContentEditableWarning?: bo...' is not assignable to type 'IntrinsicClassAttributes<Component<DelayHoverElementProps<HTMLDivElement>, ComponentState>>'.
    Types of property 'ref' are incompatible.
      Type 'Ref<HTMLDivElement>' is not assignable to type 'Ref<Component<DelayHoverElementProps<HTMLDivElement>, ComponentState>>'.
        Type '(instance: HTMLDivElement) => any' is not assignable to type 'Ref<Component<DelayHoverElementProps<HTMLDivElement>, ComponentState>>'.
          Type '(instance: HTMLDivElement) => any' is not assignable to type '(instance: Component<DelayHoverElementProps<HTMLDivElement>, ComponentState>) => any'.
            Types of parameters 'instance' and 'instance' are incompatible.
              Type 'Component<DelayHoverElementProps<HTMLDivElement>, ComponentState>' is not assignable to type 'HTMLDivElement'.
                Property 'align' is missing in type 'Component<DelayHoverElementProps<HTMLDivElement>, ComponentState>'.
</code>```

so im posting this here and hope, that some typescript guru will know how to fix it... (as any is working, but i dont like it - feels wrong)

答:
After some fiddling i end up with this code:

```<code>import * as React from 'react';

export type DelayHoverElementProps<TElement extends HTMLElement> =
    React.HTMLProps<TElement> & {
        hoverDelay: number,
        onHoverChanged: (isHovering: boolean) => void
    };

export function DelayHoverElementFactory<
    K extends keyof HTMLElementTagNameMap,
    E extends HTMLElementTagNameMap[K]
>(tagName: K): React.StatelessComponent<DelayHoverElementProps<E>> {
    return function (props: DelayHoverElementProps<E>) {
        const { hoverDelay, onHoverChanged, ...rest } = props;

        let _delayTimer: NodeJS.Timer;

        const onMouseOver = (e: React.MouseEvent<E>) => {
            clearTimeout(_delayTimer);
            _delayTimer = setTimeout(() => {
                onHoverChanged(true);
            }, hoverDelay);
        };

        const onMouseOut = (e: React.MouseEvent<E>) => {
            clearTimeout(_delayTimer);
            _delayTimer = setTimeout(() => {
                onHoverChanged(false);
            }, hoverDelay);
        };

        const tagProps: React.HTMLProps<E> = { ...rest, onMouseOver, onMouseOut };
        return React.createElement(tagName, tagProps);
    };
}
</code>```

with no longer relly on casting to any

Title: HOC component on HTMLElement

Body:
i wrote this nasty beast:

export type DelayHoverElementProps<TElement extends HTMLElement> = React.HTMLProps<TElement>
& {
    hoverDelay: number,
    onHoverChanged: (isHovering: boolean) => void
};

export function DelayHoverElementFactory<
    K extends keyof HTMLElementTagNameMap,
    E extends HTMLElementTagNameMap[K],
    C extends React.ComponentClass<DelayHoverElementProps<E>>
>(tagName: K): C {
    return class extends React.Component<
        DelayHoverElementProps<E>,
        { isHovering: boolean }
    >{
        constructor() {
            super();
            this.state = { isHovering: true };
        }

        private _delayTimer: NodeJS.Timer;

        private onMouseOver = (e: React.MouseEvent<E>) => {
            const { hoverDelay, onHoverChanged } = this.props;
            clearTimeout(this._delayTimer);
            this.setState({ isHovering: true }, () => {
                this._delayTimer = setTimeout(() => {
                    onHoverChanged(true);
                }, hoverDelay);
            });
        };

        private onMouseOut = (e: React.MouseEvent<E>) => {
            const { hoverDelay, onHoverChanged } = this.props;
            clearTimeout(this._delayTimer);
            this.setState({ isHovering: false }, () => {
                this._delayTimer = setTimeout(() => {
                    onHoverChanged(false);
                }, hoverDelay);
            });
        };

        render() {
            const { hoverDelay, onHoverChanged, ...props } = this.props;
            const tagProps: React.HTMLProps<E> = {
                ...props,
                onMouseOver: this.onMouseOver,
                onMouseOut: this.onMouseOut
            };

            return React.createElement(tagName, tagProps);
        }
    } as any; // <---
}

witch this test usage: (mocha, chai, sinon, enzyme; test will pass)

const props: DelayHoverElementProps<HTMLDivElement> = {
    hoverDelay: 200,
    onHoverChanged: index => { },
    className: 'test',
    children: 'content'
};
const spy = sinon.spy(props, 'onHoverChanged');
const expected =

{}} onMouseOut={()=>{}}>content
;

const Div = DelayHoverElementFactory('div');
const actual = shallow(
) // <---
// equalJsx is custom asserting method, with will convert JSX to string and compare that ...
expect(actual).to.equalJsx(expected);

actual.find('div').simulate('mouseOver');
expect(spy).to.be.not.called;
await new Promise(resolve => setTimeout(resolve, props.hoverDelay))
expect(spy).to.be.calledOnce;
expect(spy).to.be.calledWith(true);

it i remove these as any then i get these errors:

// first
Type 'typeof (Anonymous class)' is not assignable to type 'C'.

// second
Type '{ defaultChecked?: boolean; defaultValue?: string | string[]; suppressContentEditableWarning?: bo...' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<DelayHoverElementProps<HTMLDivElement>, ...'.
  Type '{ defaultChecked?: boolean; defaultValue?: string | string[]; suppressContentEditableWarning?: bo...' is not assignable to type 'IntrinsicClassAttributes<Component<DelayHoverElementProps<HTMLDivElement>, ComponentState>>'.
    Types of property 'ref' are incompatible.
      Type 'Ref<HTMLDivElement>' is not assignable to type 'Ref<Component<DelayHoverElementProps<HTMLDivElement>, ComponentState>>'.
        Type '(instance: HTMLDivElement) => any' is not assignable to type 'Ref<Component<DelayHoverElementProps<HTMLDivElement>, ComponentState>>'.
          Type '(instance: HTMLDivElement) => any' is not assignable to type '(instance: Component<DelayHoverElementProps<HTMLDivElement>, ComponentState>) => any'.
            Types of parameters 'instance' and 'instance' are incompatible.
              Type 'Component<DelayHoverElementProps<HTMLDivElement>, ComponentState>' is not assignable to type 'HTMLDivElement'.
                Property 'align' is missing in type 'Component<DelayHoverElementProps<HTMLDivElement>, ComponentState>'.

so im posting this here and hope, that some typescript guru will know how to fix it... (as any is working, but i dont like it - feels wrong)

Body:
After some fiddling i end up with this code:

import * as React from 'react';

export type DelayHoverElementProps<TElement extends HTMLElement> =
    React.HTMLProps<TElement> & {
        hoverDelay: number,
        onHoverChanged: (isHovering: boolean) => void
    };

export function DelayHoverElementFactory<
    K extends keyof HTMLElementTagNameMap,
    E extends HTMLElementTagNameMap[K]
>(tagName: K): React.StatelessComponent<DelayHoverElementProps<E>> {
    return function (props: DelayHoverElementProps<E>) {
        const { hoverDelay, onHoverChanged, ...rest } = props;

        let _delayTimer: NodeJS.Timer;

        const onMouseOver = (e: React.MouseEvent<E>) => {
            clearTimeout(_delayTimer);
            _delayTimer = setTimeout(() => {
                onHoverChanged(true);
            }, hoverDelay);
        };

        const onMouseOut = (e: React.MouseEvent<E>) => {
            clearTimeout(_delayTimer);
            _delayTimer = setTimeout(() => {
                onHoverChanged(false);
            }, hoverDelay);
        };

        const tagProps: React.HTMLProps<E> = { ...rest, onMouseOver, onMouseOut };
        return React.createElement(tagName, tagProps);
    };
}

with no longer relly on casting to any


问:
Xdebug connects to IDE when it shouldn't
I have remote_autostart disabled and no cookie present:

Still, Xdebug is connecting to my IDE (PhpStorm) at 192.168.22.101:9000 and zero-config debugging works. Why? How do I disable it? (It looks like autostart is somehow enabled and the PHP app is slow.)

答:
My first bet would be that this is not the php.ini you're looking for. If you have CLI and normal php.ini, make sure you have this set up in both. Integrated PHP server counter-intuitively uses web php.ini instead of CLI one.

Next step would be to check whether it's actually xdebug that's causing the issue. I'd do that by disabling the extension alltogether.
Note that xdebug can slow down you app in some cases no matter what just by being enabled.

Next I'd check that xdebug profiler information is not generated. If the app is slow in general it's the profiler. If it just hangs for few seconds and then runs normally it's waiting for remote debugger. Might be a good idea to measure (even by simple means like putting dump on first and last line of code) speed of the app to rule out this possibility.


问:
How to add HQL clause (WHERE COUNT()< MAX_VAL) to complex query
Now my query returns map of flight and its ticket count.
My aim is to exclude full flights from query result (count(t) < f.aircraft.model.passengersSeatsQuantity). But I cannot manage to create such query. Thus now I have to exclude full flights within method, and that is depressing, because i think there should be way to do it in query. Can anyone help to build query? p.s. i am now allowed to use Criteria API

```<code>String queryString = "SELECT f, COUNT(t)"
            + " FROM Flight f"
            + " JOIN FETCH f.tickets AS t"
            + " WHERE f.departureAirport=:departureAirport"
            + " GROUP BY t.flight"
            + " ORDER BY f.id ASC";

Query query = em.createQuery(queryString);
query.setParameter("departureAirport", departureAirport);

Map<Flight, Long>) flightsTicketCountMap =
            query.getResultList().stream()
            .collect(Collectors.toMap(resultElement -> (Flight) (((Object[]) resultElement)[0]),
                    resultElement -> (Long) (((Object[]) resultElement)[1])));

//below i exclude full flights from map, but i want to do it in query
Map<Flight, Long> availableFlightTicketPriceMap = new HashMap();
for (Map.Entry<Flight, Long> entry : flightsTicketCountMap.entrySet()) {
        flight = entry.getKey();
        ticketsQuantity = entry.getValue();
        if (flight.getAircraft().getModel().getPassengersSeatsQuantity() > ticketsQuantity) {
            availableFlightTicketPriceMap.put(flight, calculateTicketPrice(tariffsDetails, flight, ticketsQuantity));
        }
    }
</code>```

UPDATE.
aircraft and model have eager policy, but HAVING COUNT(t) < f.aircraft.model.passengersSeatsQuantity hot working with exception com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column aircraftmo3_.passenger_seats_quantity in having clause

```<code>public class Flight{
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "aircraft_id")
    private Aircraft aircraft;
}

public class Aircraft{
  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "model_id")
  private AircraftModel model;
}

public class AircraftModel{
  @Column(name = "passenger_seats_quantity")
  @Range(min = 0, max = 450)
  private Integer passengersSeatsQuantity;
}
</code>```

答:
Have you tried adding a HAVING clause?

```<code>SELECT f, COUNT(t)
FROM Flight f
JOIN FETCH f.tickets AS t
WHERE f.departureAirport=:departureAirport
GROUP BY t.flight
HAVING COUNT(t) < f.aircraft.model.passengersSeatsQuantity
ORDER BY f.id ASC
</code>```

Body:
Now my query returns map of flight and its ticket count.
My aim is to exclude full flights from query result (count(t) < f.aircraft.model.passengersSeatsQuantity). But I cannot manage to create such query. Thus now I have to exclude full flights within method, and that is depressing, because i think there should be way to do it in query. Can anyone help to build query? p.s. i am now allowed to use Criteria API

String queryString = "SELECT f, COUNT(t)"
            + " FROM Flight f"
            + " JOIN FETCH f.tickets AS t"
            + " WHERE f.departureAirport=:departureAirport"
            + " GROUP BY t.flight"
            + " ORDER BY f.id ASC";

Query query = em.createQuery(queryString);
query.setParameter("departureAirport", departureAirport);

Map<Flight, Long>) flightsTicketCountMap =
            query.getResultList().stream()
            .collect(Collectors.toMap(resultElement -> (Flight) (((Object[]) resultElement)[0]),
                    resultElement -> (Long) (((Object[]) resultElement)[1])));

//below i exclude full flights from map, but i want to do it in query
Map<Flight, Long> availableFlightTicketPriceMap = new HashMap();
for (Map.Entry<Flight, Long> entry : flightsTicketCountMap.entrySet()) {
        flight = entry.getKey();
        ticketsQuantity = entry.getValue();
        if (flight.getAircraft().getModel().getPassengersSeatsQuantity() > ticketsQuantity) {
            availableFlightTicketPriceMap.put(flight, calculateTicketPrice(tariffsDetails, flight, ticketsQuantity));
        }
    }

UPDATE.
aircraft and model have eager policy, but HAVING COUNT(t) < f.aircraft.model.passengersSeatsQuantity hot working with exception com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column aircraftmo3_.passenger_seats_quantity in having clause

public class Flight{
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "aircraft_id")
    private Aircraft aircraft;
}

public class Aircraft{
  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "model_id")
  private AircraftModel model;
}

public class AircraftModel{
  @Column(name = "passenger_seats_quantity")
  @Range(min = 0, max = 450)
  private Integer passengersSeatsQuantity;
}

Body:
Have you tried adding a HAVING clause?

SELECT f, COUNT(t)
FROM Flight f
JOIN FETCH f.tickets AS t
WHERE f.departureAirport=:departureAirport
GROUP BY t.flight
HAVING COUNT(t) < f.aircraft.model.passengersSeatsQuantity
ORDER BY f.id ASC


问:
How to count all combined occurrences in SQL?
Is there any option to gain counted combinations of all elements in one SQL query, without using temp tables or procedures?

Consider these three tables:

products (id, product_name)

transactions (id, date)

transaction_has_product (id, product_id, transaction_id)

Sample data

products

```<code>1   AAA
2   BBB
3   CCC
</code>```

transactions

```<code>1   some_date
2   some_date
</code>```

transaction_has_products

```<code>1   1   1
2   2   1
3   3   1
4   1   2
5   2   2
</code>```

Result should be:

```<code>AAA, BBB = 2
AAA, CCC = 1
BBB, CCC = 1
AAA, BBB, CCC = 1
</code>```

答:
If you know what all the products will be up front, you could do it by pivoting the data like this.

If you don't know what the products will be up front, you could build this query dynamically in a stored procedure.  The practicality of either approach would break down if the number of products is large, but I think that would probably be true no matter how this requirement is accomplished.

```<code>select
    product_combination,
    case product_combination
        when 'AAA, BBB' then aaa_bbb
        when 'AAA, CCC' then aaa_ccc
        when 'BBB, CCC' then bbb_ccc
        when 'AAA, BBB, CCC' then aaa_bbb_ccc
    end as number_of_transactions
from
(
    select 'AAA, BBB' as product_combination union all
    select 'AAA, CCC' union all
    select 'BBB, CCC' union all
    select 'AAA, BBB, CCC'
) as combination_list
cross join
(
    select
        sum(case when aaa = 1 and bbb = 1 then 1 else 0 end) as aaa_bbb,
        sum(case when aaa = 1 and ccc = 1 then 1 else 0 end) as aaa_ccc,
        sum(case when bbb = 1 and ccc = 1 then 1 else 0 end) as bbb_ccc,
        sum(case when aaa = 1 and bbb = 1 and ccc = 1 then 1 else 0 end) as aaa_bbb_ccc
    from
    (
        select
            count(case when a.product_name = 'AAA' then 1 else null end) as aaa,
            count(case when a.product_name = 'BBB' then 1 else null end) as bbb,
            count(case when a.product_name = 'CCC' then 1 else null end) as ccc,
            b.transaction_id
        from
            products a
        inner join
            transaction_has_products b
        on
            a.id = b.product_id
        group by
            b.transaction_id
    ) as product_matrix
) as combination_counts```

Result:

```<code>product_combination  number_of_transactions
AAA, BBB             2
AAA, CCC             1
BBB, CCC             1
AAA, BBB, CCC        1```

Body:
Is there any option to gain counted combinations of all elements in one SQL query, without using temp tables or procedures?

Consider these three tables:

products (id, product_name)

transactions (id, date)

transaction_has_product (id, product_id, transaction_id)

Sample data

products

1   AAA
2   BBB
3   CCC

transactions

1   some_date
2   some_date

transaction_has_products

1   1   1
2   2   1
3   3   1
4   1   2
5   2   2

Result should be:

AAA, BBB = 2
AAA, CCC = 1
BBB, CCC = 1
AAA, BBB, CCC = 1

Body:
If you know what all the products will be up front, you could do it by pivoting the data like this.

If you don't know what the products will be up front, you could build this query dynamically in a stored procedure.  The practicality of either approach would break down if the number of products is large, but I think that would probably be true no matter how this requirement is accomplished.

select
    product_combination,
    case product_combination
        when 'AAA, BBB' then aaa_bbb
        when 'AAA, CCC' then aaa_ccc
        when 'BBB, CCC' then bbb_ccc
        when 'AAA, BBB, CCC' then aaa_bbb_ccc
    end as number_of_transactions
from
(
    select 'AAA, BBB' as product_combination union all
    select 'AAA, CCC' union all
    select 'BBB, CCC' union all
    select 'AAA, BBB, CCC'
) as combination_list
cross join
(
    select
        sum(case when aaa = 1 and bbb = 1 then 1 else 0 end) as aaa_bbb,
        sum(case when aaa = 1 and ccc = 1 then 1 else 0 end) as aaa_ccc,
        sum(case when bbb = 1 and ccc = 1 then 1 else 0 end) as bbb_ccc,
        sum(case when aaa = 1 and bbb = 1 and ccc = 1 then 1 else 0 end) as aaa_bbb_ccc
    from
    (
        select
            count(case when a.product_name = 'AAA' then 1 else null end) as aaa,
            count(case when a.product_name = 'BBB' then 1 else null end) as bbb,
            count(case when a.product_name = 'CCC' then 1 else null end) as ccc,
            b.transaction_id
        from
            products a
        inner join
            transaction_has_products b
        on
            a.id = b.product_id
        group by
            b.transaction_id
    ) as product_matrix
) as combination_counts

Result:

product_combination  number_of_transactions
AAA, BBB             2
AAA, CCC             1
BBB, CCC             1
AAA, BBB, CCC        1


问:
Specify VPC when creating RDS instance using boto3
I can't seem to find the right argument to specify the VPC I need for creating the RDS, as the most relevant parameter I see is "VpcSecurityGroupIds", but it is definitely not the VPC, as trying to put my VPC id there outputs an error: Invalid security group , groupId= <vpc_id>, groupName=. What am I missing here?

答:
With RDS you need to provide a security group for the VPC and a subnet group for RDS, here is an example.

VpcSecurityGroupIds=['sg-7xxxx14'] - created in AWS VPC,
DBSubnetGroupName='sample-subnet-group' - created in RDS

Once that is done you can use the commands above to connect to the VPC in question.

The information is hidden deep in the docs, here is a link. http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_VPC.html


答:
I think you need a try...catch statement.

```<code>try {
    // parse your float here
} catch (NumberFormatException ex) { // parsing a float might throw a NumberFormatException
    // code in here will be executed if a NumberFormatException occurs
}
</code>```

Title: Bypass a Java error

Body:
Is there a way that I can bypass an error message in Java ?
What if I get an error, but there is no viable way to change my program ? What if I suspect that I might get an error from a block of code, but I don't know when or if it will happen ? There's been a lot of times where I had to let something be in my code, but produced an error. For example, converting a string into a float with parseFloat().

Anyway to do this ?

Body:
I think you need a try...catch statement.

try {
    // parse your float here
} catch (NumberFormatException ex) { // parsing a float might throw a NumberFormatException
    // code in here will be executed if a NumberFormatException occurs
}


问:
CSS transform scale: which box is scaled?
When using the CSS transform: scale(2,2); on an element, is it that element's content-box, padding-box, border-box, or margin-box that is to become scaled?

(I have a intuitive feeling that the answer is border-box, but I need confirmation.)

答: The element's box is scaled in its entirety, so the answer in terms of the CSS2 box model would be margin-box, since that's what an element's box usually refers to. But no one refers to an element's box in those terms.</p>


问:
How do I put a Bootstrap Glyphicon inside an asp:Button in ASP.Net?
I'm using Bootstrap 3 in my project, and I want to use Bootstrap Glyphicons in ASP.net buttons.

Here is the code I used, though it didn't work out (I got a sample which uses Twitter Bootstrap  tags instead of  tags):

```<code><asp:Button ID="btnRandom"
    runat="server"
    Text="<span aria-hidden='true'
        class='glyphicon glyphicon-refresh'>
        </span>"
    onclick="btnRandom_Click" />
</code>```

Maybe something extra should be done.

How can I get it to work?

答:
You can use linkButton instead of button or asp:Button just like this;</p>

```<code><linkbutton runat="server"><a class="btn btn-info btn-md"> <span
 class="glyphicon glyphicon-plus" style="font-size: x-large; font-weight:
 bolder"></span> </a></linkbutton>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using Bootstrap 3 in my project, and I want to use Bootstrap Glyphicons in ASP.net buttons.

Here is the code I used, though it didn't work out (I got a sample which uses Twitter Bootstrap  tags instead of  tags):

<asp:Button ID="btnRandom"
    runat="server"
    Text="
        "
    onclick="btnRandom_Click" />

Maybe something extra should be done.

How can I get it to work?

Body:
You can use linkButton instead of button or asp:Button just like this;

<linkbutton runat="server"><a class="btn btn-info btn-md"> <span
 class="glyphicon glyphicon-plus" style="font-size: x-large; font-weight:
 bolder"></span> </a></linkbutton>


问:
No Token Passed PayPal Express Checkout in Rails 5
I'm putting together a basic shopping cart with PayPal Express Checkout functionality. Everything appears to be working until I click on the checkout button, then I get a blank page that says "no token passed". In the server logs it appears that no token is being created but I'm not sure why. I think that this is most likely a problem with the creation of the express checkout token but I'm really not sure what I'm doing wrong.
Here is what the server log looks like:

```<code>Started GET "/express_checkout" for 10.240.0.204 at 2017-05-27 16:54:43 +0000
Cannot render console from 10.240.0.204! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by OrdersController#express_checkout as HTML
  Order Load (0.1ms)  SELECT  "orders".* FROM "orders" WHERE "orders"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  OrderItem Load (0.1ms)  SELECT "order_items".* FROM "order_items" WHERE "order_items"."order_id" = ?  [["order_id", 1]]
  Product Load (0.2ms)  SELECT  "products".* FROM "products" WHERE "products"."active" = ? AND "products"."id" = ? LIMIT ?  [["active", true], ["id", 1], ["LIMIT", 1]]
Redirected to https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=
Completed 302 Found in 615ms (ActiveRecord: 0.5ms)
</code>```

Here is my Order.rb:

```<code>class Order < ApplicationRecord
  has_many :order_items
  before_save :update_subtotal

  def subtotal
    order_items.collect { |oi| oi.valid? ? (oi.quantity * oi.unit_price) : 0 }.sum
  end

  def purchase
    response = EXPRESS_GATEWAY.purchase(order.total, express_purchase_options)
    order.update_attribute(:purchased_at, Time.now) if response.success?
    response.success?
  end

  def express_token=(token)
      self[:express_token]=token
      if new_record? && !token.blank?
        details = EXPRESS_GATEWAY.details_for(token)
        self.express_payer_id = details.payer_id
      end
  end

private

  def update_subtotal
    self[:subtotal] = subtotal
  end

  def express_purchase_options
    {
      :ip => ip,
      :token => express_token,
      :payer_id => express_payer_id
    }
  end
end
</code>```

My orders_controller.rb:

```<code>class OrdersController < ApplicationController

    def express_checkout
        @order = current_order
        response = EXPRESS_GATEWAY.setup_purchase(@order.subtotal,
        ip: request.remote_ip,
        return_url: 'carts/show',
        cancel_return_url: 'carts/cancel',
        currency: "USD",
        allow_guest_checkout: true,
        items: [{name: "Order", description: "Order description", quantity: "1", amount: @order.subtotal}]
    )
        redirect_to EXPRESS_GATEWAY.redirect_url_for(response.token)
    end

def new
    @order = Order.new(:express_token => params[:token])
end

def create
    @order = current_order.create!(order_params)
    @order.ip = request.remote_ip
    if @order.save
        if @order.purchase
            redirect_to order_url(@order)
        else
            render :action => "failure"
        end
    else
        render :action => 'new'
    end
end

private
def order_params
  params.require(:order).permit(:subtotal, :total, :ip, :express_token, :express_payer_id)
end
end
</code>```

My application_controller.rb:

```<code>class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  helper_method :current_order

  def current_order
    if !session[:order_id].nil?
      Order.find(session[:order_id])
    else
      Order.new(order_params)
    end
  end

end
</code>```

The Active Merchant code in my development.rb:

```<code>config.after_initialize do
ActiveMerchant::Billing::Base.mode = :test
paypal_options = {
  login: "merchant_api1.christianorourke.com",
  password: ************,
  signature: ***************************
}
::EXPRESS_GATEWAY = ActiveMerchant::Billing::PaypalExpressGateway.new(paypal_options)
  end
</code>```

My Routes file:

```<code>Rails.application.routes.draw do

  root "products#index"
  resources :products, only: [:index]
  resource :cart, only: [:show]
  resources :order_items, only: [:create, :update, :destroy]
  get 'express_checkout', to: 'orders#express_checkout'
  resources :orders do
    collection do
      post 'express_checkout'
    end
  end
end
</code>```

答:
I just found this link it explains how to configure

paypal-express

https://github.com/nov/paypal-express/wiki

```<code>paypal_options = {
  no_shipping: true, # if you want to disable shipping information
  allow_note: false, # if you want to disable notes
  pay_on_paypal: true # if you don't plan on showing your own confirmation step
}

request = Paypal::Express::Request.new(
  :username   => SET_YOUR_OWN,
  :password   => SET_YOUR_OWN,
  :signature  => SET_YOUR_OWN
)
payment_request = Paypal::Payment::Request.new(
  :currency_code => :JPY,   # if nil, PayPal use USD as default
  :description   => FOO,    # item description
  :quantity      => 1,      # item quantity
  :amount        => 1.00,   # item value
  :custom_fields => {
    CARTBORDERCOLOR: "C00000",
    LOGOIMG: "https://example.com/logo.png"
  }
)
response = request.setup(
  payment_request,
  YOUR_SUCCESS_CALLBACK_URL,
  YOUR_CANCEL_CALLBACK_URL,
  paypal_options  # Optional
)
response.redirect_uri
</code>```

Then you have the ActiveMerchant cofiguration and you can find guides hear:

https://duckduckgo.com/?q=rails+paypal+active+merchant+gem&atb=v52-6_b&ia=qa

How to integrate Paypal with Ruby on Rails

https://spin.atomicobject.com/2011/10/24/integrating-paypal-express-with-rails-3-1-part-1/

Body:
I'm putting together a basic shopping cart with PayPal Express Checkout functionality. Everything appears to be working until I click on the checkout button, then I get a blank page that says "no token passed". In the server logs it appears that no token is being created but I'm not sure why. I think that this is most likely a problem with the creation of the express checkout token but I'm really not sure what I'm doing wrong.
Here is what the server log looks like:

Started GET "/express_checkout" for 10.240.0.204 at 2017-05-27 16:54:43 +0000
Cannot render console from 10.240.0.204! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by OrdersController#express_checkout as HTML
  Order Load (0.1ms)  SELECT  "orders".* FROM "orders" WHERE "orders"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  OrderItem Load (0.1ms)  SELECT "order_items".* FROM "order_items" WHERE "order_items"."order_id" = ?  [["order_id", 1]]
  Product Load (0.2ms)  SELECT  "products".* FROM "products" WHERE "products"."active" = ? AND "products"."id" = ? LIMIT ?  [["active", true], ["id", 1], ["LIMIT", 1]]
Redirected to https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=
Completed 302 Found in 615ms (ActiveRecord: 0.5ms)

Here is my Order.rb:

class Order < ApplicationRecord
  has_many :order_items
  before_save :update_subtotal

  def subtotal
    order_items.collect { |oi| oi.valid? ? (oi.quantity * oi.unit_price) : 0 }.sum
  end

  def purchase
    response = EXPRESS_GATEWAY.purchase(order.total, express_purchase_options)
    order.update_attribute(:purchased_at, Time.now) if response.success?
    response.success?
  end

  def express_token=(token)
      self[:express_token]=token
      if new_record? && !token.blank?
        details = EXPRESS_GATEWAY.details_for(token)
        self.express_payer_id = details.payer_id
      end
  end

private

  def update_subtotal
    self[:subtotal] = subtotal
  end

  def express_purchase_options
    {
      :ip => ip,
      :token => express_token,
      :payer_id => express_payer_id
    }
  end
end

My orders_controller.rb:

class OrdersController < ApplicationController

    def express_checkout
        @order = current_order
        response = EXPRESS_GATEWAY.setup_purchase(@order.subtotal,
        ip: request.remote_ip,
        return_url: 'carts/show',
        cancel_return_url: 'carts/cancel',
        currency: "USD",
        allow_guest_checkout: true,
        items: [{name: "Order", description: "Order description", quantity: "1", amount: @order.subtotal}]
    )
        redirect_to EXPRESS_GATEWAY.redirect_url_for(response.token)
    end

def new
    @order = Order.new(:express_token => params[:token])
end

def create
    @order = current_order.create!(order_params)
    @order.ip = request.remote_ip
    if @order.save
        if @order.purchase
            redirect_to order_url(@order)
        else
            render :action => "failure"
        end
    else
        render :action => 'new'
    end
end

private
def order_params
  params.require(:order).permit(:subtotal, :total, :ip, :express_token, :express_payer_id)
end
end

My application_controller.rb:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  helper_method :current_order

  def current_order
    if !session[:order_id].nil?
      Order.find(session[:order_id])
    else
      Order.new(order_params)
    end
  end

end

The Active Merchant code in my development.rb:

config.after_initialize do
ActiveMerchant::Billing::Base.mode = :test
paypal_options = {
  login: "merchant_api1.christianorourke.com",
  password: ************,
  signature: ***************************
}
::EXPRESS_GATEWAY = ActiveMerchant::Billing::PaypalExpressGateway.new(paypal_options)
  end

My Routes file:

Rails.application.routes.draw do

  root "products#index"
  resources :products, only: [:index]
  resource :cart, only: [:show]
  resources :order_items, only: [:create, :update, :destroy]
  get 'express_checkout', to: 'orders#express_checkout'
  resources :orders do
    collection do
      post 'express_checkout'
    end
  end
end

Body:
I just found this link it explains how to configure

paypal-express

https://github.com/nov/paypal-express/wiki

paypal_options = {
  no_shipping: true, # if you want to disable shipping information
  allow_note: false, # if you want to disable notes
  pay_on_paypal: true # if you don't plan on showing your own confirmation step
}

request = Paypal::Express::Request.new(
  :username   => SET_YOUR_OWN,
  :password   => SET_YOUR_OWN,
  :signature  => SET_YOUR_OWN
)
payment_request = Paypal::Payment::Request.new(
  :currency_code => :JPY,   # if nil, PayPal use USD as default
  :description   => FOO,    # item description
  :quantity      => 1,      # item quantity
  :amount        => 1.00,   # item value
  :custom_fields => {
    CARTBORDERCOLOR: "C00000",
    LOGOIMG: "https://example.com/logo.png"
  }
)
response = request.setup(
  payment_request,
  YOUR_SUCCESS_CALLBACK_URL,
  YOUR_CANCEL_CALLBACK_URL,
  paypal_options  # Optional
)
response.redirect_uri

Then you have the ActiveMerchant cofiguration and you can find guides hear:

https://duckduckgo.com/?q=rails+paypal+active+merchant+gem&atb=v52-6_b&ia=qa

How to integrate Paypal with Ruby on Rails

https://spin.atomicobject.com/2011/10/24/integrating-paypal-express-with-rails-3-1-part-1/


问:
Where is located the source code of IWindowManager.java?
Something strange I can't understand, under the source code of android I can not find the file IWindowManager.java ? Where is it located ? normally must be in import android.view.IWindowManager;

答:
IWindowManager is autogenerated from an AIDL file located here and in order to see the Java source you must build the Android source code first. There's no IWindowManager.java currently checked in.

If you don't want to build Android itself but still want to see an example of what the Java source looks like then there's a few websites like grepcode.com that can show you that (see: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/view/IWindowManager.java#IWindowManager).


问:
How do I get http headers in React.js
I've made a request to a React page, and I need to get the headers from the request.

I call the page via the URL:

http://localhost/dashboard

and I set headers, for example authcode=1234.

I then load the page with this route:

```<code><Route path="dashboard" name="dashboard" component={Dashboard} onEnter={requireAuth}></Route>
</code>```

is there something like this.props.header, I can call in the page constructor?

答:
It's not possible to access page headers via client JavaScript. You can get these request headers on your server side and then pass them into index.html of your React app. For example:

```<code>//in index.html
<head>
...
  <script>
    window.__INITIAL_HEADERS__ = {/* page headers */};
  </script>
</head>
<body>
...
</body>
</code>```

Then in your app you can access the headers via window.__INITIAL_HEADERS__ variable.

Title: How do I get http headers in React.js

Body:
I've made a request to a React page, and I need to get the headers from the request.

I call the page via the URL:

http://localhost/dashboard

and I set headers, for example authcode=1234.

I then load the page with this route:

<Route path="dashboard" name="dashboard" component={Dashboard} onEnter={requireAuth}></Route>

is there something like this.props.header, I can call in the page constructor?

Body:
It's not possible to access page headers via client JavaScript. You can get these request headers on your server side and then pass them into index.html of your React app. For example:

//in index.html
<head>
...
  <script>
    window.__INITIAL_HEADERS__ = {/* page headers */};
  </script>
</head>
<body>
...
</body>

Then in your app you can access the headers via window.__INITIAL_HEADERS__ variable.


问:
(JavaScript) Import external <object> svg from File or FileReader Object
I'm using Two.js, I want to allow the user to import an svg file and display it on my scene.

Two.interpret() can take any dom of  tag that has SVG data in it, so I've created this function to simulate  tag from a file:

```<code>this.m_Two.interpretFromFile = function (two, fname) {
        //Create an object and load an svg from 'fname'
        var object = document.createElement("object");
        //Set the id to the filename without path or extension
        object.id = fname;
        object.id = object.id.replace(/\\/g, '/');
        object.id = object.id.substring(object.id.lastIndexOf('/')+1, object.id.lastIndexOf('.'));
        console.log("Importing " + object.id);
        object.data = fname; //HTML takes care of the rest
        object.type = "image/svg+xml";
        object.width = 64; //Import from file maybe?
        object.height = 64;
        object.style = "visibility:hidden;position:absolute;left:0px;top:0px;";
        document.body.appendChild(object); //Add it to the body (invis) that way it loads
        //When it loads, finish up
        object.onload = function () {
            if (!object.contentDocument || object.contentDocument.getElementsByTagName("svg").length < 1) return;
            var svgObj = object.contentDocument.getElementsByTagName('svg')[0];
            var ret = two.interpret(svgObj);
            document.body.removeChild(object); //Remove it. Use path.clone to duplicate stuff..
            return ret; //Return our new svg path
        }
    };
</code>```

This function takes a Two instance, and a file url, and returns a two.path.

This all works fine and dandy when use the console with
twoInstance.interpretFromFile (twoInstance, "images/Test.svg");

However, I am running these files locally for testing, and I certainly don't expect anyone to go into their browser's console and use the function, already knowing the file's exact path, and also know to type "file://" before that path... Yeesh

```<code>    document.getElementById("dWorkSpace").ondrop = function(e) {
            e.preventDefault(); //Default event loads the file itself.. KILL IT WITH FIRE.

            if (!e.dataTransfer || !e.dataTransfer.items.length > 0 || !e.dataTransfer.files[0]) return;

            var file = e.dataTransfer.files[0];

            twoInstance.interpretFromFile(twoInstance, "file://" + file.name);
    }
</code>```

'file.name' only gives the file, not the path (yes, I know this is a securety thing in browsers. I've already looked at all of the other questions about that..)

So NOW, I could use a FileReader to read the svg file itself, but how do I get that data into an  tag? I need it in this format at some point:

```<code>            <object data="Test.svg" type="image/svg+xml"></object>
</code>```

Because Two.js seems to not like 'svg' tag.. Just 'object' tag..

I am SO sorry for the enlongated question.. I'm pretty deep down this rabbit hole, as you can see. I tried to only use relevant code, but honestly the whole thing is monstrously large, and I'd hate to post it all.

答:
You will have to create an BlobURL from your File object (which is just a direct pointer to the file on the user's disk), and then set your <object>'s data to this BlobURL.

Here I will just use an <input> element, but its basically the same with any Blob/File, where-ever they came (note though that IIRC you need to call getAsFile() method from dataTransfer's Files.

f.onchange = e =>{
  var file = f.files[0];
  if(file.type === 'image/svg+xml'){
    var obj = document.createElement('object');
    obj.data = URL.createObjectURL(file);
    obj.onload = e => URL.revokeObjectURL(obj.data);
    document.body.appendChild(obj);
    }
  };
      ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="file" id="f"/></code>```

Body:
I'm using Two.js, I want to allow the user to import an svg file and display it on my scene.

Two.interpret() can take any dom of  tag that has SVG data in it, so I've created this function to simulate  tag from a file:

this.m_Two.interpretFromFile = function (two, fname) {
        //Create an object and load an svg from 'fname'
        var object = document.createElement("object");
        //Set the id to the filename without path or extension
        object.id = fname;
        object.id = object.id.replace(/\\/g, '/');
        object.id = object.id.substring(object.id.lastIndexOf('/')+1, object.id.lastIndexOf('.'));
        console.log("Importing " + object.id);
        object.data = fname; //HTML takes care of the rest
        object.type = "image/svg+xml";
        object.width = 64; //Import from file maybe?
        object.height = 64;
        object.style = "visibility:hidden;position:absolute;left:0px;top:0px;";
        document.body.appendChild(object); //Add it to the body (invis) that way it loads
        //When it loads, finish up
        object.onload = function () {
            if (!object.contentDocument || object.contentDocument.getElementsByTagName("svg").length < 1) return;
            var svgObj = object.contentDocument.getElementsByTagName('svg')[0];
            var ret = two.interpret(svgObj);
            document.body.removeChild(object); //Remove it. Use path.clone to duplicate stuff..
            return ret; //Return our new svg path
        }
    };

This function takes a Two instance, and a file url, and returns a two.path.

This all works fine and dandy when use the console with
twoInstance.interpretFromFile (twoInstance, "images/Test.svg");

However, I am running these files locally for testing, and I certainly don't expect anyone to go into their browser's console and use the function, already knowing the file's exact path, and also know to type "file://" before that path... Yeesh

    document.getElementById("dWorkSpace").ondrop = function(e) {
            e.preventDefault(); //Default event loads the file itself.. KILL IT WITH FIRE.

            if (!e.dataTransfer || !e.dataTransfer.items.length > 0 || !e.dataTransfer.files[0]) return;

            var file = e.dataTransfer.files[0];

            twoInstance.interpretFromFile(twoInstance, "file://" + file.name);
    }

'file.name' only gives the file, not the path (yes, I know this is a securety thing in browsers. I've already looked at all of the other questions about that..)

So NOW, I could use a FileReader to read the svg file itself, but how do I get that data into an  tag? I need it in this format at some point:

            <object data="Test.svg" type="image/svg+xml"></object>

Because Two.js seems to not like 'svg' tag.. Just 'object' tag..

I am SO sorry for the enlongated question.. I'm pretty deep down this rabbit hole, as you can see. I tried to only use relevant code, but honestly the whole thing is monstrously large, and I'd hate to post it all.

Body:
You will have to create an BlobURL from your File object (which is just a direct pointer to the file on the user's disk), and then set your <object>'s data to this BlobURL.

Here I will just use an <input> element, but its basically the same with any Blob/File, where-ever they came (note though that IIRC you need to call getAsFile() method from dataTransfer's Files.

f.onchange = e =>{
  var file = f.files[0];
  if(file.type === 'image/svg+xml'){
    var obj = document.createElement('object');
    obj.data = URL.createObjectURL(file);
    obj.onload = e => URL.revokeObjectURL(obj.data);
    document.body.appendChild(obj);
    }
  };

<input type="file" id="f"/>


问:
Linkedin Share URL preview not showing correctly?
I need to share dynamically created URLs in website to Facebook and LinkedIn. I am sharing to Facebook properly and all needed og tags have been set. But for LinkedIn, it is not working.

This is my URL: https://www.fourthambit.com/blogs_fa/102048

It is properly parsed in Facebook and preview is shown correctly.

But the same link is not working in LinkedIn.

Am I missing anything else?

All needed meta tags are set:

```<code><meta property="og:title" content="Indian Media: Then.... Now... and Later" />
<meta content="Sensationalism has become synonymous with the Indian Media, especially Television. In 2008 dur..." name="description" />
<meta property="og:description" content="Sensationalism has become synonymous with the Indian Media, especially Television. In 2008 dur..." />
<meta content="Academic network" name="keywords" />
<meta property="og:image" content="https://www.fourthambit.com/article/getarticlephoto/big/ZGNlZQD4/0/102/20150807050217-12217198186.jpg" />
<img src="https://www.fourthambit.com/article/getarticlephoto/big/ZGNlZQD4/0/102/20150807050217-12217198186.jpg" style="display: none !important;" />
<meta property="og:type" content="website" />
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
</code>```

This is the ajax call going while I try to view a preview in LinkedIn update status bar text-area.

https://www.linkedin.com/sharing/api/url-preview?url=https://www.fourthambit.com/blogs_fa/102048

答:
The reason to this problem could be the following:

"Unfortunately LinkedIn caches the data it retrieves the first time the link is previewed and keeps it cached for a week!"

and the solution:

"The only way to “clear” the sharing preview cache for LinkedIn is to trick LinkedIn into thinking your page is a different (and new) page.

This is done by adding a made-up parameter to the link. It doesn’t affect your webpage, but it does force the metadata to be re-fetched.

Example:

Original link: http://beantin.se/consultant-resume

"New" link: http://beantin.se/consultant-resume?1

Body:
I need to share dynamically created URLs in website to Facebook and LinkedIn. I am sharing to Facebook properly and all needed og tags have been set. But for LinkedIn, it is not working.

This is my URL: https://www.fourthambit.com/blogs_fa/102048

It is properly parsed in Facebook and preview is shown correctly.

But the same link is not working in LinkedIn.

Am I missing anything else?

All needed meta tags are set:

<meta property="og:title" content="Indian Media: Then.... Now... and Later" />
<meta content="Sensationalism has become synonymous with the Indian Media, especially Television. In 2008 dur..." name="description" />
<meta property="og:description" content="Sensationalism has become synonymous with the Indian Media, especially Television. In 2008 dur..." />
<meta content="Academic network" name="keywords" />
<meta property="og:image" content="https://www.fourthambit.com/article/getarticlephoto/big/ZGNlZQD4/0/102/20150807050217-12217198186.jpg" />

<meta property="og:type" content="website" />
<meta content="width=device-width, initial-scale=1.0" name="viewport" />

This is the ajax call going while I try to view a preview in LinkedIn update status bar text-area.

https://www.linkedin.com/sharing/api/url-preview?url=https://www.fourthambit.com/blogs_fa/102048


问:
Tree Hierarchy in Oracle
I just came across this question from 'HackerRank'.
The BST table contains two columns, N and P. N stands for Node, P stands for Parent:

```<code> N  P
-- --
 1  2
 3  2
 6  8
 9  8
 2  5
 8  5
 5  null
</code>```

Sample Output should be:

1 leaf
2 inner
3 leaf
5 root
6 leaf
8 inner
9 leaf
```

<p>What I have tried is : </p>

```select     N,
           case
               when level = 3 then 'leaf'
               when level = 2 then 'inner'
               else 'root'
           end
from       BST
start with P is NULL
connect by P = prior N
order by   N;
```

Although it gives the correct result, I  am not happy with the code as it hardcodes the name (whether it should be leaf, inner or root). Also this code will fail when there are multiple hierarchies in the tree.

Can someone please suggest any other elegant way of writing the same code so that it does not fail for multiple hierarchy?

答:
You can make use of the connect_by_isleaf pseudocolumn, and the fact that the root will always have level 1:

```<code>select      n,
            case
                when connect_by_isleaf = 1 then 'leaf'
                when level = 1 then 'root'
                else 'inner'
            end
from        bst
start with  p is null
connect by  p = prior n
order by    n;
</code>```

Title: Tree Hierarchy in Oracle

Body:
I just came across this question from 'HackerRank'.
The BST table contains two columns, N and P. N stands for Node, P stands for Parent:

 N  P
-- --
 1  2
 3  2
 6  8
 9  8
 2  5
 8  5
 5  null

Sample Output should be:

1 leaf
2 inner
3 leaf
5 root
6 leaf
8 inner
9 leaf

What I have tried is :

select     N,
           case
               when level = 3 then 'leaf'
               when level = 2 then 'inner'
               else 'root'
           end
from       BST
start with P is NULL
connect by P = prior N
order by   N;

Although it gives the correct result, I  am not happy with the code as it hardcodes the name (whether it should be leaf, inner or root). Also this code will fail when there are multiple hierarchies in the tree.

Can someone please suggest any other elegant way of writing the same code so that it does not fail for multiple hierarchy?

Body:
You can make use of the connect_by_isleaf pseudocolumn, and the fact that the root will always have level 1:

select      n,
            case
                when connect_by_isleaf = 1 then 'leaf'
                when level = 1 then 'root'
                else 'inner'
            end
from        bst
start with  p is null
connect by  p = prior n
order by    n;