问:
Need help figuring out why my app is crashing when I try to switch views
Hello I am developing apps on for 4.1 and on Xcode3.2. My Apps crash when press back button . When press back back button Last class is appeared slightly than crash, with no error or warning ....
Here are the code....crash on Back Function</p>

```<code>#import "TransactionSummaryDetailViewController.h"
#import "TransactionSummaryData.h"
#import "Constant.h"
#import "DataBase.h";
#import "Common.h"
#import "YPCardHolderServiceService.h"
#import "SelectionScreenViewController.h"

@implementation TransactionSummaryDetailViewController
@synthesize table,cardReference;
@synthesize waitIndicator,transactionsummary,keyArray,valueArray,isSummaryAvailable;
@synthesize startDate,endDate;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

-(void)getrowcount{
    if(transactionsummary.cardholdernmae !=nil){
        [keyArray addObject:@"Card Holder Name: "];
        [valueArray addObject:transactionsummary.cardholdernmae];
    }
    if(transactionsummary.cardnumber!=nil){
        [keyArray addObject:@"Card Number: "];
        [valueArray addObject:transactionsummary.cardnumber];
    }
    if(transactionsummary.debittransactioncount != nil){
        [keyArray addObject:@"Debit Tx. Count: "];
        [valueArray addObject:transactionsummary.debittransactioncount];
    }
    if(transactionsummary.debittransactionvalue!=nil){
        [keyArray addObject:@"Debit Tx. Value"];
        [valueArray addObject:transactionsummary.debittransactionvalue];
    }
    if(transactionsummary.credittransactioncount!=nil){
        [keyArray addObject:@"Credit Tx. Count: "];
        [valueArray addObject:transactionsummary.credittransactioncount];
    }
    if(transactionsummary.credittransactionvalue!=nil){
        [keyArray addObject:@"Credit Tx. Value: "];
        [valueArray addObject:transactionsummary.credittransactionvalue];
    }
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    appDelegate = [[UIApplication sharedApplication]delegate];
    keyArray = [[NSMutableArray alloc]init];
    valueArray = [[NSMutableArray alloc]init];
    [self getrowcount];
    NSLog(@"Key Array Count is %d",[keyArray count]);
    [table setBackgroundColor:[UIColor clearColor]];
    [table setSeparatorColor:TableViewCellSeperatorColor];
    [waitIndicator setHidden:YES];
    [self setTitle:@"Summary Details"];
    UIButton *button =  [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"list.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(BacktoView) forControlEvents:UIControlEventTouchUpInside];
    [button setFrame:CGRectMake(0, 0, 76, 44)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    if(!isSummaryAvailable)
    {
        if([Common isNetworkAvailable])
        {
            [waitIndicator startAnimating];
            YPCardHolderServiceService *services = [[YPCardHolderServiceService alloc] init];
            YPTransactionsSummaryRequest *summaryRequest = [[YPTransactionsSummaryRequest alloc] init];
            summaryRequest.SC = appDelegate.SC;
            summaryRequest.userName = appDelegate.userName;
            summaryRequest.valid =TRUE;
            summaryRequest.cardReference =[NSString stringWithFormat:@"%@",cardReference];
            NSLog(@"Start Date Is %@ and End Date is %@",startDate,endDate);
            summaryRequest.startDate = startDate;
            summaryRequest.endDate = endDate;
            summaryRequest.applicationType = @"M";
            [services getTransactionsSummary:self action:@selector(getTransactionsSummaryHandlers:) transactionsSummaryRequest:summaryRequest];
            [summaryRequest release];
            [services release];
        }
    }

    [super viewDidLoad];
}

//Handle the Response of getTransactionsSummary
-(void)getTransactionsSummaryHandlers:(id) value
{
    [waitIndicator stopAnimating];
    // Handle errors
    if([value isKindOfClass:[NSError class]]) {
        NSLog(@"%@", value);
        return;
    }

    // Handle faults
    if([value isKindOfClass:[SoapFault class]]) {
        NSLog(@"%@", value);
        return;
    }

    // Do something with the YPLoginResponse* result
    YPTransactionsSummaryResponse* result = (YPTransactionsSummaryResponse*)value;
    if(result.statusCode == 0)
    {
        NSLog(@"Number of Transaction is =%d",[result.transactionSummaryList count]);
        NSLog(@"Step 1 ='%@'",appDelegate.userID);
        NSString *deleteQuery = @"delete from TransactionSummary where userid = ";
        NSLog(@"Step 1 ='%@'",appDelegate.userID);
        deleteQuery = [deleteQuery stringByAppendingString:[NSString stringWithFormat:@"%@ and cardreference = '%@'",appDelegate.userID,cardReference]];
        NSLog(@"delete query= '%@'",deleteQuery);
        [DataBase deleteDataFromTable:deleteQuery];
        NSLog(@"delete query= '%@'",deleteQuery);
        //for (int i =0; i< [result.transactionSummaryList count]; i++)
        for (int i =0; i< [result.transactionSummaryList count] -2; i++)
        {
            NSLog(@"for loop= %d",i);
            YPTransactionSummaryDetails *transactionSummary = (YPTransactionSummaryDetails*)[result.transactionSummaryList objectAtIndex:i];
            NSLog(@"cardholdername= '%@'",transactionSummary.cardholderName);

            /*NSString *insertQuery = @"Insert into TransactionSummary(cardholdername,cardnumber,debittransactioncount,debittransactionvalue,credittransactioncount,credittransactionvalue,userid) values(";
            insertQuery =[insertQuery stringByAppendingString:[NSString stringWithFormat:@"'%@','xxxx xxxx xxxx %@',%d,%d,%d,%d,'%@',%@)",
                                                               transactionSummary.cardholderName,transactionSummary.cardNumber,transactionSummary.debitTransactionCount,
                                                               transactionSummary.debitTransactionValue,transactionSummary.creditTransactionCount,transactionSummary.creditTransactionValue,
                                                               appDelegate.userID]];*/
            //Add by sarvesh
            NSString *insertQuery = @"Insert into TransactionSummary(cardholdername,cardnumber,debittransactioncount,debittransactionvalue,credittransactioncount,credittransactionvalue,cardreference,userid) values(";
            insertQuery =[insertQuery stringByAppendingString:[NSString stringWithFormat:@"'%@','%@',%d,%d,%d,%d,'%@',%@)",
                                                               transactionSummary.cardholderName,transactionSummary.cardNumber,transactionSummary.debitTransactionCount,
                                                               transactionSummary.debitTransactionValue,transactionSummary.creditTransactionCount,transactionSummary.creditTransactionValue,cardReference,
                                                               appDelegate.userID]];
            NSLog(@"Insert Query for Transaction Summary is %@",insertQuery);
            [DataBase InsertIntoTable:insertQuery];
        }
        //Read Update Data From DataBase and Refresh Table
            NSString *query = @"Select * from TransactionSummary where userid = ";
            query = [query stringByAppendingString:[NSString stringWithFormat:@"%@ and cardreference = '%@'",appDelegate.userID,cardReference]];
        NSLog(@"select query= %@",query);
            NSMutableArray *temp=[DataBase getTransactionSummaryTableData:query];
            if([temp count] > 0)
            {
                transactionsummary = (TransactionSummaryData*)[temp objectAtIndex:0];
                [keyArray removeAllObjects];
                [valueArray removeAllObjects];
            }
            [self getrowcount];
            [table reloadData];

    }
}

-(void)viewDidAppear:(BOOL)animated
{
    CGFloat navBarHeight = 50.0f;
    CGRect frame = CGRectMake(0.0f, 20.0f, 320.0f, navBarHeight);
    [self.navigationController.navigationBar setFrame:frame];
    [super viewDidAppear:animated];
}

-(IBAction)BacktoView
{
    NSLog(@"in back function..TrasactionSummaryDetail");
    SelectionScreenViewController *screenView=[[SelectionScreenViewController alloc] initWithNibName:@"SelectionScreenViewController" bundle:nil];
    [self.navigationController popViewControllerAnimated:YES];
    [screenView release];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleNone;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return cellHeightForGroupedTable;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0)
        return [keyArray count];

    else
        return 0;

}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSString *title = nil;
    switch (section){
        case 0:{
            //title = @"Summary Details";
            break;
        }
    }
    return title;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ([self tableView:tableView titleForHeaderInSection:section] != nil) {
        return tableHeaderHeight;
    }
    else {
        // If no section header title, no section header needed
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
    if (sectionTitle == nil) {
        return nil;
    }

    // Create label with section title
    UILabel *label = [[[UILabel alloc] init] autorelease];
    label.frame = CGRectMake(20, 6, 300, 30);
    label.backgroundColor = [UIColor clearColor];
    label.textColor = HeaderTextColor;
    label.shadowColor = HeaderTextShadowColor;
    label.shadowOffset = CGSizeMake(0.0, 1.0);
    label.font = HeaderTextFontSize;
    label.text = sectionTitle;

    // Create header view and add label as a subview
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320,60)];
    [view autorelease];
    [view addSubview:label];

    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = nil;

    NSString *cellIdentifier;

    cellIdentifier = @"SectionsTableIdentifier";
    int row = [indexPath row];

    CGRect nameLabelRect = CGRectMake(19 , 8, 240, 29);
    CGRect cardlabelRect = CGRectMake(19,31,240,15);
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:nameLabelRect];
    UILabel *cardnumber = [[UILabel alloc] initWithFrame:cardlabelRect];
    cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if(cell == nil){
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
    }

    // Remove all subview from cell content view
    for (UIView *view in cell.contentView.subviews){
        [view removeFromSuperview];
    }

     [cell setAccessoryType:UITableViewCellAccessoryNone];
    [nameLabel setTextColor:firstLabelFontColor];
    [nameLabel setFont:firstLabelFont];
    [nameLabel setFont:firstLabelFontSize];

     nameLabel.textAlignment = UITextAlignmentLeft;
     nameLabel.text = [NSString stringWithFormat:@"%@ : %@",[keyArray objectAtIndex:row],[valueArray objectAtIndex:row]];

     [cell.contentView addSubview: nameLabel];

     cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setBackgroundColor:[UIColor clearColor]];
    [cell setBackgroundColor:TableViewCellColor];

    [nameLabel setBackgroundColor:[UIColor clearColor]];
    [cardnumber setBackgroundColor:[UIColor clearColor]];

    [cardnumber release];
    [nameLabel release];
    return cell;
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [table release];
    [waitIndicator release];
    [keyArray release];
    [valueArray release];
    [transactionsummary release];
    [super dealloc];
}

@end
</code>```

答:
DOn't you think that this

```<code>-(IBAction)BacktoView
{
    NSLog(@"in back function..TrasactionSummaryDetail");
    SelectionScreenViewController *screenView=[[SelectionScreenViewController alloc] initWithNibName:@"SelectionScreenViewController" bundle:nil];
    [self.navigationController popViewControllerAnimated:YES];
    [screenView release];
}
</code>```

should be this

```<code>-(IBAction)BacktoView
 {
    NSLog(@"in back function..TrasactionSummaryDetail");
    SelectionScreenViewController *screenView=[[SelectionScreenViewController alloc] initWithNibName:@"SelectionScreenViewController" bundle:nil];
    [self.navigationController pushViewController:screenView animated:YES];
    [screenView release];
 }
</code>```

It seems you are trying to push a controller on stack but accidentally you popped.

Body:
Hello I am developing apps on for 4.1 and on Xcode3.2. My Apps crash when press back button . When press back back button Last class is appeared slightly than crash, with no error or warning ....
Here are the code....crash on Back Function

#import "TransactionSummaryDetailViewController.h"
#import "TransactionSummaryData.h"
#import "Constant.h"
#import "DataBase.h";
#import "Common.h"
#import "YPCardHolderServiceService.h"
#import "SelectionScreenViewController.h"

@implementation TransactionSummaryDetailViewController
@synthesize table,cardReference;
@synthesize waitIndicator,transactionsummary,keyArray,valueArray,isSummaryAvailable;
@synthesize startDate,endDate;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

-(void)getrowcount{
    if(transactionsummary.cardholdernmae !=nil){
        [keyArray addObject:@"Card Holder Name: "];
        [valueArray addObject:transactionsummary.cardholdernmae];
    }
    if(transactionsummary.cardnumber!=nil){
        [keyArray addObject:@"Card Number: "];
        [valueArray addObject:transactionsummary.cardnumber];
    }
    if(transactionsummary.debittransactioncount != nil){
        [keyArray addObject:@"Debit Tx. Count: "];
        [valueArray addObject:transactionsummary.debittransactioncount];
    }
    if(transactionsummary.debittransactionvalue!=nil){
        [keyArray addObject:@"Debit Tx. Value"];
        [valueArray addObject:transactionsummary.debittransactionvalue];
    }
    if(transactionsummary.credittransactioncount!=nil){
        [keyArray addObject:@"Credit Tx. Count: "];
        [valueArray addObject:transactionsummary.credittransactioncount];
    }
    if(transactionsummary.credittransactionvalue!=nil){
        [keyArray addObject:@"Credit Tx. Value: "];
        [valueArray addObject:transactionsummary.credittransactionvalue];
    }
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    appDelegate = [[UIApplication sharedApplication]delegate];
    keyArray = [[NSMutableArray alloc]init];
    valueArray = [[NSMutableArray alloc]init];
    [self getrowcount];
    NSLog(@"Key Array Count is %d",[keyArray count]);
    [table setBackgroundColor:[UIColor clearColor]];
    [table setSeparatorColor:TableViewCellSeperatorColor];
    [waitIndicator setHidden:YES];
    [self setTitle:@"Summary Details"];
    UIButton *button =  [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"list.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(BacktoView) forControlEvents:UIControlEventTouchUpInside];
    [button setFrame:CGRectMake(0, 0, 76, 44)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    if(!isSummaryAvailable)
    {
        if([Common isNetworkAvailable])
        {
            [waitIndicator startAnimating];
            YPCardHolderServiceService *services = [[YPCardHolderServiceService alloc] init];
            YPTransactionsSummaryRequest *summaryRequest = [[YPTransactionsSummaryRequest alloc] init];
            summaryRequest.SC = appDelegate.SC;
            summaryRequest.userName = appDelegate.userName;
            summaryRequest.valid =TRUE;
            summaryRequest.cardReference =[NSString stringWithFormat:@"%@",cardReference];
            NSLog(@"Start Date Is %@ and End Date is %@",startDate,endDate);
            summaryRequest.startDate = startDate;
            summaryRequest.endDate = endDate;
            summaryRequest.applicationType = @"M";
            [services getTransactionsSummary:self action:@selector(getTransactionsSummaryHandlers:) transactionsSummaryRequest:summaryRequest];
            [summaryRequest release];
            [services release];
        }
    }

    [super viewDidLoad];
}

//Handle the Response of getTransactionsSummary
-(void)getTransactionsSummaryHandlers:(id) value
{
    [waitIndicator stopAnimating];
    // Handle errors
    if([value isKindOfClass:[NSError class]]) {
        NSLog(@"%@", value);
        return;
    }

    // Handle faults
    if([value isKindOfClass:[SoapFault class]]) {
        NSLog(@"%@", value);
        return;
    }

    // Do something with the YPLoginResponse* result
    YPTransactionsSummaryResponse* result = (YPTransactionsSummaryResponse*)value;
    if(result.statusCode == 0)
    {
        NSLog(@"Number of Transaction is =%d",[result.transactionSummaryList count]);
        NSLog(@"Step 1 ='%@'",appDelegate.userID);
        NSString *deleteQuery = @"delete from TransactionSummary where userid = ";
        NSLog(@"Step 1 ='%@'",appDelegate.userID);
        deleteQuery = [deleteQuery stringByAppendingString:[NSString stringWithFormat:@"%@ and cardreference = '%@'",appDelegate.userID,cardReference]];
        NSLog(@"delete query= '%@'",deleteQuery);
        [DataBase deleteDataFromTable:deleteQuery];
        NSLog(@"delete query= '%@'",deleteQuery);
        //for (int i =0; i< [result.transactionSummaryList count]; i++)
        for (int i =0; i< [result.transactionSummaryList count] -2; i++)
        {
            NSLog(@"for loop= %d",i);
            YPTransactionSummaryDetails *transactionSummary = (YPTransactionSummaryDetails*)[result.transactionSummaryList objectAtIndex:i];
            NSLog(@"cardholdername= '%@'",transactionSummary.cardholderName);

            /*NSString *insertQuery = @"Insert into TransactionSummary(cardholdername,cardnumber,debittransactioncount,debittransactionvalue,credittransactioncount,credittransactionvalue,userid) values(";
            insertQuery =[insertQuery stringByAppendingString:[NSString stringWithFormat:@"'%@','xxxx xxxx xxxx %@',%d,%d,%d,%d,'%@',%@)",
                                                               transactionSummary.cardholderName,transactionSummary.cardNumber,transactionSummary.debitTransactionCount,
                                                               transactionSummary.debitTransactionValue,transactionSummary.creditTransactionCount,transactionSummary.creditTransactionValue,
                                                               appDelegate.userID]];*/
            //Add by sarvesh
            NSString *insertQuery = @"Insert into TransactionSummary(cardholdername,cardnumber,debittransactioncount,debittransactionvalue,credittransactioncount,credittransactionvalue,cardreference,userid) values(";
            insertQuery =[insertQuery stringByAppendingString:[NSString stringWithFormat:@"'%@','%@',%d,%d,%d,%d,'%@',%@)",
                                                               transactionSummary.cardholderName,transactionSummary.cardNumber,transactionSummary.debitTransactionCount,
                                                               transactionSummary.debitTransactionValue,transactionSummary.creditTransactionCount,transactionSummary.creditTransactionValue,cardReference,
                                                               appDelegate.userID]];
            NSLog(@"Insert Query for Transaction Summary is %@",insertQuery);
            [DataBase InsertIntoTable:insertQuery];
        }
        //Read Update Data From DataBase and Refresh Table
            NSString *query = @"Select * from TransactionSummary where userid = ";
            query = [query stringByAppendingString:[NSString stringWithFormat:@"%@ and cardreference = '%@'",appDelegate.userID,cardReference]];
        NSLog(@"select query= %@",query);
            NSMutableArray *temp=[DataBase getTransactionSummaryTableData:query];
            if([temp count] > 0)
            {
                transactionsummary = (TransactionSummaryData*)[temp objectAtIndex:0];
                [keyArray removeAllObjects];
                [valueArray removeAllObjects];
            }
            [self getrowcount];
            [table reloadData];

    }
}

-(void)viewDidAppear:(BOOL)animated
{
    CGFloat navBarHeight = 50.0f;
    CGRect frame = CGRectMake(0.0f, 20.0f, 320.0f, navBarHeight);
    [self.navigationController.navigationBar setFrame:frame];
    [super viewDidAppear:animated];
}

-(IBAction)BacktoView
{
    NSLog(@"in back function..TrasactionSummaryDetail");
    SelectionScreenViewController *screenView=[[SelectionScreenViewController alloc] initWithNibName:@"SelectionScreenViewController" bundle:nil];
    [self.navigationController popViewControllerAnimated:YES];
    [screenView release];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleNone;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return cellHeightForGroupedTable;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0)
        return [keyArray count];

    else
        return 0;

}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSString *title = nil;
    switch (section){
        case 0:{
            //title = @"Summary Details";
            break;
        }
    }
    return title;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ([self tableView:tableView titleForHeaderInSection:section] != nil) {
        return tableHeaderHeight;
    }
    else {
        // If no section header title, no section header needed
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
    if (sectionTitle == nil) {
        return nil;
    }

    // Create label with section title
    UILabel *label = [[[UILabel alloc] init] autorelease];
    label.frame = CGRectMake(20, 6, 300, 30);
    label.backgroundColor = [UIColor clearColor];
    label.textColor = HeaderTextColor;
    label.shadowColor = HeaderTextShadowColor;
    label.shadowOffset = CGSizeMake(0.0, 1.0);
    label.font = HeaderTextFontSize;
    label.text = sectionTitle;

    // Create header view and add label as a subview
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320,60)];
    [view autorelease];
    [view addSubview:label];

    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = nil;

    NSString *cellIdentifier;

    cellIdentifier = @"SectionsTableIdentifier";
    int row = [indexPath row];

    CGRect nameLabelRect = CGRectMake(19 , 8, 240, 29);
    CGRect cardlabelRect = CGRectMake(19,31,240,15);
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:nameLabelRect];
    UILabel *cardnumber = [[UILabel alloc] initWithFrame:cardlabelRect];
    cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if(cell == nil){
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
    }

    // Remove all subview from cell content view
    for (UIView *view in cell.contentView.subviews){
        [view removeFromSuperview];
    }

     [cell setAccessoryType:UITableViewCellAccessoryNone];
    [nameLabel setTextColor:firstLabelFontColor];
    [nameLabel setFont:firstLabelFont];
    [nameLabel setFont:firstLabelFontSize];

     nameLabel.textAlignment = UITextAlignmentLeft;
     nameLabel.text = [NSString stringWithFormat:@"%@ : %@",[keyArray objectAtIndex:row],[valueArray objectAtIndex:row]];

     [cell.contentView addSubview: nameLabel];

     cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setBackgroundColor:[UIColor clearColor]];
    [cell setBackgroundColor:TableViewCellColor];

    [nameLabel setBackgroundColor:[UIColor clearColor]];
    [cardnumber setBackgroundColor:[UIColor clearColor]];

    [cardnumber release];
    [nameLabel release];
    return cell;
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [table release];
    [waitIndicator release];
    [keyArray release];
    [valueArray release];
    [transactionsummary release];
    [super dealloc];
}

@end

Body:
DOn't you think that this

-(IBAction)BacktoView
{
    NSLog(@"in back function..TrasactionSummaryDetail");
    SelectionScreenViewController *screenView=[[SelectionScreenViewController alloc] initWithNibName:@"SelectionScreenViewController" bundle:nil];
    [self.navigationController popViewControllerAnimated:YES];
    [screenView release];
}

should be this

-(IBAction)BacktoView
 {
    NSLog(@"in back function..TrasactionSummaryDetail");
    SelectionScreenViewController *screenView=[[SelectionScreenViewController alloc] initWithNibName:@"SelectionScreenViewController" bundle:nil];
    [self.navigationController pushViewController:screenView animated:YES];
    [screenView release];
 }

It seems you are trying to push a controller on stack but accidentally you popped.


来源: stackexchange

问:
Is 'this php file' can be called or referred as HTTP API?
So I'm make an PHP file that used by Arduino to send coordinate to my database
In Arduino, there are GPS to get coordinate, relay to turn on/off LED, and SIM800L to send data over GPRS connection
When Arduino want to send data to my database, Arduino create http request by access

http://myserver.com/gprs?lat=-6.123&lng=100.123
gprs is a PHP file that created using codeigniter so there is not '.php' in the URL

enter image description here

The output when gprs.php is executed is 0 or 1. The 0 or 1 value is use to Arduino to control the relay. If output is 0, relay is on.. 1 relay is off..  The 0 or 1 value is received by relay_status table in mysql database...

So the gprs.php:
-> passing latitude and logitude to table coordinate in mysql database
(SQL like insert into bla bla bla)
-> querying the relay status
(SQL like Select column from relay_status)

Then, can gprs.php is called or referred as HTTP API. I'm looking in internet and found an API is usually generated JSON output, in my gprs.php file.. the output is not JSON output.

I want to know because I'm write an article or report about this

答:
Your API can return whatever you want it to return. While APIs usually return XML or JSON, you can let yours return whatever you want. Binary, a string, single digit responses - it's totally up to you. People mostly use JSON and XML because those are standardized formats which most other applications that call the API can easily read and process.

Basically, every PHP-Script can be an API. The difference between an API and a "normal" PHP script is the fact that an API returns only data, whereas a normal script returns a view.

ContentLicense: CC BY-SA 4.0


Title: How to remove one of two consecutive duplicate strings in list?

Body:
I have a list that has duplicated 'STRING' elements and looks like this:

a = ['32', '55', '74', '58', 'STRING', 'STRING','STRING', 'STRING','56', '53', '51', '59', '49', '45', '45', '43', '62', '57', '53', '52', '49', '50', '47', '63', 'STRING', 'STRING', '90', '84', '82', '85', '86', 'STRING', 'STRING', '78', '88', '81', '88', '88', '73', '88', '81', '92', '129', '115', '105', '94', '91', '85', '79', '74', '69', '55', 'STRING', 'STRING', '86', '89', '88', '66', '70', 'STRING', 'STRING', '75', '73', '86', '75', '65', '57', '69', '59', '55']

One of every two consecuitive 'STRING' elements has to be in its place. I need to remove every second of the consecutive STRINGelements. And the list should look like this:

a = ['32', '55', '74', '58', 'STRING', 'STRING','56', '53', '51', '59', '49', '45', '45', '43', '62', '57', '53', '52', '49', '50', '47', '63', 'STRING', '90', '84', '82', '85', '86', 'STRING', '78', '88', '81', '88', '88', '73', '88', '81', '92', '129', '115', '105', '94', '91', '85', '79', '74', '69', '55', 'STRING', '86', '89', '88', '66', '70', 'STRING', '75', '73', '86', '75', '65', '57', '69', '59', '55']

This is what I tried:

    for i in reversed(range(len(a)-1)):
        if (list1[i] == list1[i-1]) & (list1[i] == 'STRING'):
            list1.remove(list1[i-1])

but it doesn't work. When it's not reversed I get the IndexError.

Body:
Probably not the simplest or cleanest solution, but this works:

a = ['32', '55', '74', '58', 'STRING', 'STRING','STRING', 'STRING','56', '53', '51', '59', '49', '45', '45', '43', '62', '57', '53', '52', '49', '50', '47', '63', 'STRING', 'STRING', '90', '84', '82', '85', '86', 'STRING', 'STRING', '78', '88', '81', '88', '88', '73', '88', '81', '92', '129', '115', '105', '94', '91', '85', '79', '74', '69', '55', 'STRING', 'STRING', '86', '89', '88', '66', '70', 'STRING', 'STRING', '75', '73', '86', '75', '65', '57', '69', '59', '55']

prev = a[0]
for el in a:
    if prev == el and el == 'STRING':
        a.remove(el)
        prev = None
    else:
        prev = el
print(a)


问:
Kafka Consumer diamond operator cannot infer arguments
I am creating a Kafka consumer. Mentioned piece of code is running fine on my sample POC project.

Somehow when I use this in my project application, it gives error, of not able to resolve Diamond Operator.

Project Code

```<code>private Consumer<Long, String> createConsumer(String topicName) {
    final Properties props = new Properties();
    // todo: use @Value instead of hardcodes
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(ConsumerConfig.GROUP_ID_CONFIG, "application");
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName());
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
    props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");

    final Consumer<Long, String> consumer = new KafkaConsumer<>(props);
    consumer.subscribe(Collections.singletonList(topicName));
    return consumer;
}
</code>```

Error Snapshot

答:
This is reproducible as long as you import java.util.function.Consumer (having one generic type) which is not an interface that KafkaConsumer implements. You need to import the correct one:

```<code>org.apache.kafka.clients.consumer.Consumer
</code>```

This one has two generic types and it should work with no compilation errors.

```<code>final Consumer<Long, String> consumer = new KafkaConsumer<>(props);
</code>```

Body:
I am creating a Kafka consumer. Mentioned piece of code is running fine on my sample POC project.

Somehow when I use this in my project application, it gives error, of not able to resolve Diamond Operator.

Project Code

private Consumer<Long, String> createConsumer(String topicName) {
    final Properties props = new Properties();
    // todo: use @Value instead of hardcodes
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(ConsumerConfig.GROUP_ID_CONFIG, "application");
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName());
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
    props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");

    final Consumer<Long, String> consumer = new KafkaConsumer<>(props);
    consumer.subscribe(Collections.singletonList(topicName));
    return consumer;
}

Error Snapshot

Body:
This is reproducible as long as you import java.util.function.Consumer (having one generic type) which is not an interface that KafkaConsumer implements. You need to import the correct one:

org.apache.kafka.clients.consumer.Consumer

This one has two generic types and it should work with no compilation errors.

final Consumer<Long, String> consumer = new KafkaConsumer<>(props);


问:
Referenced property not a (One|Many)ToOne: in mappedBy of
I'm pretty new in hibernate. I have to class: User (parent) and Area (child) that are related, User has the FK with Area. I'm doing the hibernate relations but I'm getting error :

```<code>2020-05-31 12:39:53.442  WARN  --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered
</code>```

during context initialization - cancelling refresh attempt:
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'entityManagerFactory' defined in class path
  resource
  [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]:
  Invocation of init method failed; nested exception is
  org.hibernate.AnnotationException: Referenced property not a
  (One|Many)ToOne: com.telefonica.npro.model.Area.id_area in mappedBy of
  com.telefonica.npro.model.User.area

This is USER:

```<code>    @Entity
@Table(name = "NPRO_USUARIOS")
public class User implements Serializable {

    private static final long serialVersionUID = -1330075515340995797L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @NotNull
    @Column
    private int id_usuario;

    @Column
    @NotNull
    private String nombre_usuario;

    @OneToOne(mappedBy = "id_sociedad", cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH })
    private Sociedad sociedad;

    @OneToOne(mappedBy = "id_area", cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH })
    private Area area;

    @Column
    @NotNull
    private String matricula_usuario;

    @Column
    @NotNull
    private String email_usuario;

    @ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH })
    @JoinColumn(name="id_perfil")
    private Perfil perfil;

}
</code>```

This is Area:

```<code>@Entity
@Table(name = "NPRO_MAESTRO_AREAS")
public class Area implements Serializable {

    private static final long serialVersionUID = -1330075515340995797L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @NotNull
    @Column
    private int id_area;

    @NotNull
    @Column
    private String nombre_area;

    @Column
    private LocalDateTime fecha_modif;
    @Column
    private String observaciones;
    @Column
    private int usuario_modif;
    @Column
    @NotNull
    private String activo;

    @ManyToOne
    @JoinColumn(name="id_sociedad")
    private Sociedad sociedad;

    @OneToOne
    @JoinColumn(name="id_usuario")
    private User user;
}
</code>```

I have no idea what is wrong.. Thanks in advance!

Antonio

答:
mappedBy should be the field in the related entity that can be navigated back to the current entity. So for User , it should be the user field in Area :

@Entity
@Table(name = "NPRO_USUARIOS")
public class User implements Serializable {

     @OneToOne(mappedBy = "user", cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH })
     private Area area;
}
```

Body:
I'm pretty new in hibernate. I have to class: User (parent) and Area (child) that are related, User has the FK with Area. I'm doing the hibernate relations but I'm getting error :

2020-05-31 12:39:53.442  WARN  --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered

during context initialization - cancelling refresh attempt:
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'entityManagerFactory' defined in class path
  resource
  [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]:
  Invocation of init method failed; nested exception is
  org.hibernate.AnnotationException: Referenced property not a
  (One|Many)ToOne: com.telefonica.npro.model.Area.id_area in mappedBy of
  com.telefonica.npro.model.User.area

This is USER:

    @Entity
@Table(name = "NPRO_USUARIOS")
public class User implements Serializable {

    private static final long serialVersionUID = -1330075515340995797L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @NotNull
    @Column
    private int id_usuario;

    @Column
    @NotNull
    private String nombre_usuario;

    @OneToOne(mappedBy = "id_sociedad", cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH })
    private Sociedad sociedad;

    @OneToOne(mappedBy = "id_area", cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH })
    private Area area;

    @Column
    @NotNull
    private String matricula_usuario;

    @Column
    @NotNull
    private String email_usuario;

    @ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH })
    @JoinColumn(name="id_perfil")
    private Perfil perfil;

}

This is Area:

@Entity
@Table(name = "NPRO_MAESTRO_AREAS")
public class Area implements Serializable {

    private static final long serialVersionUID = -1330075515340995797L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @NotNull
    @Column
    private int id_area;

    @NotNull
    @Column
    private String nombre_area;

    @Column
    private LocalDateTime fecha_modif;
    @Column
    private String observaciones;
    @Column
    private int usuario_modif;
    @Column
    @NotNull
    private String activo;

    @ManyToOne
    @JoinColumn(name="id_sociedad")
    private Sociedad sociedad;

    @OneToOne
    @JoinColumn(name="id_usuario")
    private User user;
}

I have no idea what is wrong.. Thanks in advance!

Antonio


问:
Error When Creating Search Index in Cassandra Enterprise (DSE)
I'm trying to create a search index on my table in DSE 6.8. This is my table in the test keyspace:

```<code>CREATE TABLE users (
   username text,
   first_name text,
   last_name text,
   password text,
   email text,
   last_access timeuuid,
   PRIMARY KEY(username));
</code>```

I tried this query:

```<code>CREATE SEARCH INDEX ON test.users;
</code>```

and this is the response:

```<code>InvalidRequest: Error from server: code=2200 [Invalid query] message="Search statements are not supported on this node"
</code>```

I think there must be something that I should change in some file for DSE to support search statements. I've already set the SOLR_ENABLED in /etc/default/dse to 1. I'm totally new to this and I don't know if there's something wrong with my table or anything else.

can anyone suggest what might be causing this error? Thanks in advance.

答:
As the error message suggests, you can only create a Search index on DSE nodes running in Search mode.

Check the node's workload by running the command below. It will tell you if the node is running in pure Cassandra mode or Search mode.

```<code>$ dsetool status
</code>```

If you have installed DSE using the binary tarball, it doesn't use /etc/default/dse. Instead start DSE as a standalone process with the -s flag to start it in Search mode:

```<code>$ dse cassandra -s
</code>```

Cheers!

Body:
I'm trying to create a search index on my table in DSE 6.8. This is my table in the test keyspace:

CREATE TABLE users (
   username text,
   first_name text,
   last_name text,
   password text,
   email text,
   last_access timeuuid,
   PRIMARY KEY(username));

I tried this query:

CREATE SEARCH INDEX ON test.users;

and this is the response:

InvalidRequest: Error from server: code=2200 [Invalid query] message="Search statements are not supported on this node"

I think there must be something that I should change in some file for DSE to support search statements. I've already set the SOLR_ENABLED in /etc/default/dse to 1. I'm totally new to this and I don't know if there's something wrong with my table or anything else.

can anyone suggest what might be causing this error? Thanks in advance.

Body:
As the error message suggests, you can only create a Search index on DSE nodes running in Search mode.

Check the node's workload by running the command below. It will tell you if the node is running in pure Cassandra mode or Search mode.

$ dsetool status

If you have installed DSE using the binary tarball, it doesn't use /etc/default/dse. Instead start DSE as a standalone process with the -s flag to start it in Search mode:

$ dse cassandra -s

Cheers!


问:
sns.pairplot shows density curve instead of histogram
My understanding is that the below code shall produce histograms in the diagonal boxes. Instead, I am getting density curves? Why is this? If I remove 'hue','palette' and 'diag_kws', it produces histograms as expected. Any inputs?

```<code>sns.pairplot(data=ins_pre,
        vars=["fatal_collisions", "premiums",'insurance_losses'],
        kind='scatter',
        hue='Region',
        palette='RdBu',
        diag_kws={'alpha':.5})

plt.show()
plt.clf()
</code>```

Plot the same data but remove 'hue','palette' and 'diag_kws'

```<code>sns.pairplot(data=ins_pre,
        vars=["fatal_collisions", "premiums",'insurance_losses'],
        kind='scatter')

plt.show()
plt.clf()
</code>```

答:
from the documentation:

```<code>seaborn.pairplot(data, hue=None, hue_order=None, palette=None, vars=None, x_vars=None,
y_vars=None, kind='scatter', diag_kind='auto', markers=None, height=2.5, aspect=1,
corner=False, dropna=True, plot_kws=None, diag_kws=None, grid_kws=None, size=None)

[...]

diag_kind{‘auto’, ‘hist’, ‘kde’, None}, optional
Kind of plot for the diagonal subplots. The default depends on whether "hue" is used or not.
</code>```

So, you should call the function like so:

```<code>sns.pairplot(data=ins_pre,
        vars=["fatal_collisions", "premiums",'insurance_losses'],
        kind='scatter',
        hue='Region',
        palette='RdBu',
        diag_kind='hist')
</code>```

Body:
My understanding is that the below code shall produce histograms in the diagonal boxes. Instead, I am getting density curves? Why is this? If I remove 'hue','palette' and 'diag_kws', it produces histograms as expected. Any inputs?

sns.pairplot(data=ins_pre,
        vars=["fatal_collisions", "premiums",'insurance_losses'],
        kind='scatter',
        hue='Region',
        palette='RdBu',
        diag_kws={'alpha':.5})

plt.show()
plt.clf()

Plot the same data but remove 'hue','palette' and 'diag_kws'

sns.pairplot(data=ins_pre,
        vars=["fatal_collisions", "premiums",'insurance_losses'],
        kind='scatter')

plt.show()
plt.clf()

Body:
from the documentation:

seaborn.pairplot(data, hue=None, hue_order=None, palette=None, vars=None, x_vars=None,
y_vars=None, kind='scatter', diag_kind='auto', markers=None, height=2.5, aspect=1,
corner=False, dropna=True, plot_kws=None, diag_kws=None, grid_kws=None, size=None)

[...]

diag_kind{‘auto’, ‘hist’, ‘kde’, None}, optional
Kind of plot for the diagonal subplots. The default depends on whether "hue" is used or not.

So, you should call the function like so:

sns.pairplot(data=ins_pre,
        vars=["fatal_collisions", "premiums",'insurance_losses'],
        kind='scatter',
        hue='Region',
        palette='RdBu',
        diag_kind='hist')


问:
What is wrong with my PHP WordPress code?
This is my code in index.php of the WordPress theme:

```<code><div id="content">
            <?php if (have_posts()) : ?>
            <?php $counter = "0"; ?>
            <?php while (have_posts()) : the_post(); ?>
            <?php
                if ($counter % 2) {
                    $specialprt = "";
                } else {
                    $specialprt = "prt-right";
                }
            ?>
            <div class="partial <?php echo $specialprt; ?>" id="post-<?php the_ID(); ?>">
                <div class="prt-img">
                    <?php echo bdw_get_images($post->the_ID, 'medium'); ?>
                </div>
                <div class="prt-tags">
                    <?php the_tags(' ', ''); ?>
                </div>
                <h2 class="prt-title">
                    <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a>
                </h2>
                <span class="prt-small">Posted on <?php the_time('l F jS') ?> by <?php the_author() ?></span>
                <p><?php the_excerpt(); ?></p>
                <p><?php edit_post_link('Edit', '', ''); ?></p>
            </div>
            <?php $counter++; ?>
            <?php endwhile; ?>
            <?php endif; ?>
        </div><!-- #content -->
</code>```

Problems:

All the posts have the same image. Why?

Page loads very slow. Why?

Can anybody give a hand of help? :)

Thanks.

UPDATE:

I have better results with this:

```<code><div id="content">
            <?php if (have_posts()) : ?>
            <?php $counter = "0"; ?>
            <?php while (have_posts()) : the_post(); $counter++; ?>
            <?php
                if ($counter % 2) {
                    $specialprt = "prt-right";
                } else {
                    $specialprt = "";
                }
            ?>
            <div class="partial <?php echo $specialprt; ?>" id="post-<?php the_ID(); ?>">
                <div class="prt-img">
                    <?php
                    $args = array( 'post_type' => 'attachment', 'numberposts' => 1, 'post_status' => null, 'post_parent' => $post->ID );
                    $attachments = get_posts($args);
                    if ($attachments) {
                        foreach ( $attachments as $attachment ) {
                            the_attachment_link( $attachment->ID , true, false, false );
                        }
                    } else {
                        echo "<img src=\"<?php bloginfo('stylesheet_directory'); ?>/images/no-image.jpg\" width=\"250\" height=\"155\" />";
                    }
                    ?>
                </div>
                <div class="prt-tags">
                    <?php the_tags(' ', ''); ?>
                </div>
                <h2 class="prt-title">
                    <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a>
                </h2>
                <span class="prt-small">Posted on <?php the_time('l F jS') ?> by <?php the_author() ?></span>
                <p><?php the_excerpt(); ?></p>
                <p><?php edit_post_link('Edit', '', ''); ?></p>
            </div>
            <?php endwhile; ?>
            <?php endif; ?>
        </div><!-- #content -->
</code>```

答:
I can answer your first question:

$post->the_ID is incorrect. Although it isn't recognized as part of the $post object, PHP keeps notices quiet so you don't see any error happening. Instead, bdw_get_images() just receives a null ID and produces the same "image" for every post.

The correct value to pass in is either $post->ID or calling get_the_ID().

But not the second one, as I don't think there's enough information in your post to start figuring out what's slowing things down. Try perhaps using your browser's web development tools to analyze the request and response to see what's going on.

ContentLicense: CC BY-SA 3.0

Body:
This is my code in index.php of the WordPress theme:

            <?php if (have_posts()) : ?>
            <?php $counter = "0"; ?>
            <?php while (have_posts()) : the_post(); ?>
            <?php
                if ($counter % 2) {
                    $specialprt = "";
                } else {
                    $specialprt = "prt-right";
                }
            ?>
            <div class="partial <?php echo $specialprt; ?>" id="post-<?php the_ID(); ?>">

                    <?php echo bdw_get_images($post->the_ID, 'medium'); ?>

                    <?php the_tags(' ', ''); ?>

                    <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?>

                Posted on <?php the_time('l F jS') ?> by <?php the_author() ?>

<?php the_excerpt(); ?>

<?php edit_post_link('Edit', '', ''); ?>

            <?php $counter++; ?>
            <?php endwhile; ?>
            <?php endif; ?>

Problems:

All the posts have the same image. Why?

Page loads very slow. Why?

Can anybody give a hand of help? :)

Thanks.

UPDATE:

I have better results with this:

            <?php if (have_posts()) : ?>
            <?php $counter = "0"; ?>
            <?php while (have_posts()) : the_post(); $counter++; ?>
            <?php
                if ($counter % 2) {
                    $specialprt = "prt-right";
                } else {
                    $specialprt = "";
                }
            ?>
            <div class="partial <?php echo $specialprt; ?>" id="post-<?php the_ID(); ?>">

                    <?php
                    $args = array( 'post_type' => 'attachment', 'numberposts' => 1, 'post_status' => null, 'post_parent' => $post->ID );
                    $attachments = get_posts($args);
                    if ($attachments) {
                        foreach ( $attachments as $attachment ) {
                            the_attachment_link( $attachment->ID , true, false, false );
                        }
                    } else {
                        echo "<img src=\"<?php bloginfo('stylesheet_directory'); ?>/images/no-image.jpg\" width=\"250\" height=\"155\" />";
                    }
                    ?>

                    <?php the_tags(' ', ''); ?>

                    <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?>

                Posted on <?php the_time('l F jS') ?> by <?php the_author() ?>

<?php the_excerpt(); ?>

<?php edit_post_link('Edit', '', ''); ?>

            <?php endwhile; ?>
            <?php endif; ?>


问:
if then else condition in json schema
```<code>{
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "http://example.com/example.json",
"type": "object",
"required": [
    "FileID",
    "MString",
    "desc",
    "elements"
],
"properties": {
    "FileID": {
        "type": "string"
    },
    "MString": {
        "type": "string"
    },
    "desc": {
        "type": "string"
    },
    "elements": {
        "type": "array",
        "items": {
            "type": "object",
            "required": [
                "Mytype",
                "filename",
                "compression"
            ],
            "properties": {
                "Mytype": {
                    "type": "string"
                },
                "filename": {
                    "type": "string"
                },
                "compression": {
                    "type": "string"
                }
            }
        }
    }
}
</code>```

}

I want to add a condition in this schema (if Mytype == "abc") then "filename" can be only "tutor.txt". Please can some one help me out to write this add this condition in the schema. I tried many ways but always giving some error. Thanks in advance.

答:
There are different approaches to achieve that behavior. One is using conditional in-place applicators, which are available since JSON Schema Draft 7. The syntax looks as follows (I will extract the involved subschema for the sake of clarity):

```<code>{
  "type": "object",
  "required": [
    "Mytype",
    "filename",
    "compression"
  ],
  "properties": {
    "Mytype": {
      "type": "string"
    },
    "filename": {
      "type": "string"
    },
    "compression": {
      "type": "string"
    }
  },
  "if": {
    "properties": {"Mytype": {"const": "abc"}}
  },
  "then": {
    "properties": {"filename": {"const": "tutor.txt"}}
  }
}
</code>```

The following JSON document is valid against this JSON Schema:

```<code>{
  "Mytype": "abc",
  "filename": "tutor.txt",
  "compression": "foo"
}
</code>```

And this will be invalid:

```<code>{
  "Mytype": "abc",
  "filename": "tutor",
  "compression": "foo"
}
</code>```

For more complex conditions, JSON Schema provides an "else" keyword. To learn more I suggest you to check out this educative reference, under the Applying subschemas conditionally section.

On top of this conditional approach, you can express this same grammar by using boolean-logic applicators instead of the conditional applicators demonstrated above. Personally, Though usually more verbose, I tend to prefer this solution as it represents a purely declarative solution instead of that "procedural" if-then-else notion, remaining more clear after all.

Here is the example:

```<code>{
  "type": "object",
  "required": [
    "Mytype",
    "filename",
    "compression"
  ],
  "oneOf": [
    {
      "properties": {
        "Mytype": {
          "const": "abc"
        },
        "filename": {
          "const": "tutor.txt"
        },
        "compression": {
          "type": "string"
        }
      }
    },
    {
      "properties": {
        "Mytype": {
          "not": {
            "const": "abc"
          }
        },
        "filename": {
          "type": "string"
        },
        "compression": {
          "type": "string"
        }
      }
    }
  ]
}
</code>```

Explanation: the JSON document has to be valid against only one of the subschemas included in the "oneOf". The first expresses the constrained case obliging "filename" to be "tutor.txt" if "Mytype" is "abc". The second subschema represents the case when "Mytype" is not "abc", so the "filename" is not constrained, just any "string".

As stated, the boolean-logic applicators syntax yields more verbose schemas, and they may need some time to get used to them, but overall they are the best option in my opinion.

Title: if then else condition in json schema

Body:
{
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "http://example.com/example.json",
"type": "object",
"required": [
    "FileID",
    "MString",
    "desc",
    "elements"
],
"properties": {
    "FileID": {
        "type": "string"
    },
    "MString": {
        "type": "string"
    },
    "desc": {
        "type": "string"
    },
    "elements": {
        "type": "array",
        "items": {
            "type": "object",
            "required": [
                "Mytype",
                "filename",
                "compression"
            ],
            "properties": {
                "Mytype": {
                    "type": "string"
                },
                "filename": {
                    "type": "string"
                },
                "compression": {
                    "type": "string"
                }
            }
        }
    }
}

}

I want to add a condition in this schema (if Mytype == "abc") then "filename" can be only "tutor.txt". Please can some one help me out to write this add this condition in the schema. I tried many ways but always giving some error. Thanks in advance.

Body:
There are different approaches to achieve that behavior. One is using conditional in-place applicators, which are available since JSON Schema Draft 7. The syntax looks as follows (I will extract the involved subschema for the sake of clarity):

{
  "type": "object",
  "required": [
    "Mytype",
    "filename",
    "compression"
  ],
  "properties": {
    "Mytype": {
      "type": "string"
    },
    "filename": {
      "type": "string"
    },
    "compression": {
      "type": "string"
    }
  },
  "if": {
    "properties": {"Mytype": {"const": "abc"}}
  },
  "then": {
    "properties": {"filename": {"const": "tutor.txt"}}
  }
}

The following JSON document is valid against this JSON Schema:

{
  "Mytype": "abc",
  "filename": "tutor.txt",
  "compression": "foo"
}

And this will be invalid:

{
  "Mytype": "abc",
  "filename": "tutor",
  "compression": "foo"
}

For more complex conditions, JSON Schema provides an "else" keyword. To learn more I suggest you to check out this educative reference, under the Applying subschemas conditionally section.

On top of this conditional approach, you can express this same grammar by using boolean-logic applicators instead of the conditional applicators demonstrated above. Personally, Though usually more verbose, I tend to prefer this solution as it represents a purely declarative solution instead of that "procedural" if-then-else notion, remaining more clear after all.

Here is the example:

{
  "type": "object",
  "required": [
    "Mytype",
    "filename",
    "compression"
  ],
  "oneOf": [
    {
      "properties": {
        "Mytype": {
          "const": "abc"
        },
        "filename": {
          "const": "tutor.txt"
        },
        "compression": {
          "type": "string"
        }
      }
    },
    {
      "properties": {
        "Mytype": {
          "not": {
            "const": "abc"
          }
        },
        "filename": {
          "type": "string"
        },
        "compression": {
          "type": "string"
        }
      }
    }
  ]
}

Explanation: the JSON document has to be valid against only one of the subschemas included in the "oneOf". The first expresses the constrained case obliging "filename" to be "tutor.txt" if "Mytype" is "abc". The second subschema represents the case when "Mytype" is not "abc", so the "filename" is not constrained, just any "string".

As stated, the boolean-logic applicators syntax yields more verbose schemas, and they may need some time to get used to them, but overall they are the best option in my opinion.


问:
how to get value from odoo purchase lines order to stock.picking lines?
i'am added analytic account field on stock move model, I need as the stock move lines get quantity form PO lines to get analytic account field form lines when I confirm the order,
how can I do that </p>

```<code> class StockMove(models.Model):
_inherit = "stock.move"

 analytic_account_id = fields.Many2one(string='Analytic Account',comodel_name='account.analytic.account',)
</code>```

<p>any help will be appreciated </p>

答:
Override _prepare_stock_moves method which prepares the stock moves data for one order line and returns a list of dictionary ready to be used in stock.move's create().

```<code>class PurchaseOrderLine(models.Model):
    _inherit = 'purchase.order.line'

    @api.multi
    def _prepare_stock_moves(self, picking):
        res = super(PurchaseOrderLine, self)._prepare_stock_moves(picking)
        res[0]['analytic_account_id'] = self.account_analytic_id.id
        return res
</code>```

To get field values from purchase order use the inverse_name order_id.

```<code>res[0]['analytic_account_id'] = self.order_id.account_analytic_id.id
</code>```

Edit:

To use the same logic on production orders, you can set the account when you mark the order as done:

```<code>class ManufacturingOrder(models.Model):
    _inherit = 'mrp.production'

    analytic_account_id = fields.Many2one(string='Analytic Account', comodel_name='account.analytic.account')

    @api.multi
    def button_mark_done(self):
        for order in self:
            for move in order.move_finished_ids:
                move.analytic_account_id = order.analytic_account_id
        res = super(ManufacturingOrder, self).button_mark_done()
        return res
</code>```

Body:
i'am added analytic account field on stock move model, I need as the stock move lines get quantity form PO lines to get analytic account field form lines when I confirm the order,
how can I do that

 class StockMove(models.Model):
_inherit = "stock.move"

 analytic_account_id = fields.Many2one(string='Analytic Account',comodel_name='account.analytic.account',)

any help will be appreciated

Body:
Override _prepare_stock_moves method which prepares the stock moves data for one order line and returns a list of dictionary ready to be used in stock.move's create().

class PurchaseOrderLine(models.Model):
    _inherit = 'purchase.order.line'

    @api.multi
    def _prepare_stock_moves(self, picking):
        res = super(PurchaseOrderLine, self)._prepare_stock_moves(picking)
        res[0]['analytic_account_id'] = self.account_analytic_id.id
        return res

To get field values from purchase order use the inverse_name order_id.

res[0]['analytic_account_id'] = self.order_id.account_analytic_id.id

Edit:

To use the same logic on production orders, you can set the account when you mark the order as done:

class ManufacturingOrder(models.Model):
    _inherit = 'mrp.production'

    analytic_account_id = fields.Many2one(string='Analytic Account', comodel_name='account.analytic.account')

    @api.multi
    def button_mark_done(self):
        for order in self:
            for move in order.move_finished_ids:
                move.analytic_account_id = order.analytic_account_id
        res = super(ManufacturingOrder, self).button_mark_done()
        return res


问:
Nextjs dynamic routing
In my nextjs app I have profile pages. I want the routing to be like this:

```<code>/@username
</code>```

That's why I have used this file format:

```<code>@[username].js
</code>```

But this is not working. Is there any other way to accomplish this?

答:
You'll have to add it under a page something like this:

```<code>pages/user/[username].js
</code>```

Any route like /user/@john, /user/@mark, etc. will be matched by pages/user/[username].js. The matched path parameter will be sent as a query parameter to the page.

You'll have access to the query object as

```<code>{ "username": "@john" }
</code>```

[username].js

```<code>export default function User(props) {
  return (
    <div>
      <h1>Username: {props.url.query.username} </h1>
      ```{JSON.stringify(props, null, 2)}```
    </div>
  );
}
</code>```

eg: Codesandbox

Hope this helps !

Title: Nextjs dynamic routing

Body:
In my nextjs app I have profile pages. I want the routing to be like this:

/@username

That's why I have used this file format:

@[username].js

But this is not working. Is there any other way to accomplish this?

Body:
You'll have to add it under a page something like this:

pages/user/[username].js

Any route like /user/@john, /user/@mark, etc. will be matched by pages/user/[username].js. The matched path parameter will be sent as a query parameter to the page.

You'll have access to the query object as

{ "username": "@john" }

[username].js

export default function User(props) {
  return (
    <div>
      <h1>Username: {props.url.query.username} </h1>
      <pre>{JSON.stringify(props, null, 2)}</pre>
    </div>
  );
}

eg: Codesandbox

Hope this helps !


问:
no tests found with test runner JUnit 5 even after adding Junit Library
I wanted to test my classes in Java using JUnit 5, in Eclipse. all the files are in the same package. My test file is correct (syntax wise) and i get no errors from eclipse regarding the file itself. Only when i try to run the testfile, do i get the error: No tests found with test runner JUnit 5

I am really frustrated because i cannot seem to find the issue. i have included the JUnit-Library in my module path. I dont know if posting my code makes any sense, because i think it might be a different issue. Does anyone have any experience with this kind of error?

edit: here's a screenshot of my run configurations

答:
Please check, if you added the Junit5 Library to your Java build path (Libraries).

If not, add the Library to your Java build path.


问:
What are the tricks to make lazy initialization thread safe and efficiency considering the costs of sychronized keyword?
After reading the lazy initialization of expensive resources in the book around Page 106-108 - functional programming in Java by Venkat Subramaniam, it is found hard to understand the tricks with this code snippet

my understandings:
variable heavy in class Holder is of type Supplier<Heavy>

vs

local class HeavyFactory inside the method createAndCacheHeavy is a sub class extends Supplier

It seems only run once to execute that lambda method and then alter the outer member variable of class Holder.heavy

I am confused about below code the heavy is then later assigned with new reference pointing to the sub class extends Supplier

please if anyone could share hints the tricks here to gain the advantages of author proposed to save performance penalty from synchronized keyword and also taking care of thread safety. It also mentioned virtual proxy pattern. Did I miss out any key info to understand it?

```<code>package fpij;

import java.util.function.Supplier;

public class Holder {
//only run once here? before heavy get reassigned to HeavyFactory, the local class to that lambda method?
  private Supplier<Heavy> heavy = () -> createAndCacheHeavy();

  public Holder() {
    System.out.println("Holder created");
  }

  public Heavy getHeavy() {
//the 2nd time it will call always the HeavyFactory.heavyInstance?
    return heavy.get();
  }

  private synchronized Heavy createAndCacheHeavy() {
//create a local class inside method? Is the real trick/hack here I missed out so it will avoid 2nd time the synchronized penalty?
    class HeavyFactory implements Supplier<Heavy> {
      private final Heavy heavyInstance = new Heavy();

      public Heavy get() { return heavyInstance; }
    }

    if(!HeavyFactory.class.isInstance(heavy)) {
      heavy = new HeavyFactory();
    }

    return heavy.get();
  }

  public static void main(final String[] args) {
    final Holder holder = new Holder();
    System.out.println("deferring heavy creation...");
    System.out.println(holder.getHeavy());
    System.out.println(holder.getHeavy());
  }
}

package fpij;

public class Heavy {
  public Heavy() { System.out.println("Heavy created"); }

  public String toString() { return "quite heavy"; }
}
</code>```

答:
If you are really concerned on the cost of synchronized, there a simple way to make it work correctly while keeping the initialization lazy.

It use the property that the classloader ensure synchronization when the class is loaded. It garentee that no other thread will be able to access the class until it is fully loaded. And the class load is actually lazy: it load the class only when the class is actually used from the first time.

If the only feature of class HeavyFactory is to provide the singleton instance, it will be loaded only when the getInstance is called and all will play nicely.

```<code>class HeavyFactory {

private static final Heavy heavyInstance = initInstance();

  public static Heavy getHeavyInstance() {
    return heavyInstance;
  }

  private static Heavy initInstance() {
      heavyInstance = new HeavyInstance();
      [...] // Other init stuff
      return heavyInstance;
  }
}
</code>```

Edit: The init of complex objects and wiring of dependencies is so common that frameworks like JEE or Spring have implemented ways to do simplify it.

If you use spring for example, you would be able to just declare a given service as a singleton and then declare a dependency on it where you need it. The init would be done when the spring framework initialize in proper order:

```<code>// We instruct spring to create a shared instance of heavy
// with @Component annotation
// The instance would be created eagerly at the start of the app.
@Component
public class Heavy {
  public Heavy() { System.out.println("Heavy created"); }

  public String toString() { return "quite heavy"; }
}

// For the example another service using the Heavy shared instance
@Component
public class ClientDependingOnHeavy {

  // We ask spring to fill it automatically the shared instance for us.
  @Autowired
  private Heavy heavy;

  public String foo() {
    //So we can use the instance like any object.
    System.out.println(heavy.toString());
  }
}
</code>```

Well spring or JEE are quite complex advanced frameworks. For a single case they would not be worth it at all. For a whole application it would make sense. You'd need quite some reading/tutorials to make the second example work if you don't already know them. But in the long run, it may be worth the effort.

Body:
After reading the lazy initialization of expensive resources in the book around Page 106-108 - functional programming in Java by Venkat Subramaniam, it is found hard to understand the tricks with this code snippet

my understandings:
variable heavy in class Holder is of type Supplier<Heavy>

vs

local class HeavyFactory inside the method createAndCacheHeavy is a sub class extends Supplier

It seems only run once to execute that lambda method and then alter the outer member variable of class Holder.heavy

I am confused about below code the heavy is then later assigned with new reference pointing to the sub class extends Supplier

please if anyone could share hints the tricks here to gain the advantages of author proposed to save performance penalty from synchronized keyword and also taking care of thread safety. It also mentioned virtual proxy pattern. Did I miss out any key info to understand it?

package fpij;

import java.util.function.Supplier;

public class Holder {
//only run once here? before heavy get reassigned to HeavyFactory, the local class to that lambda method?
  private Supplier<Heavy> heavy = () -> createAndCacheHeavy();

  public Holder() {
    System.out.println("Holder created");
  }

  public Heavy getHeavy() {
//the 2nd time it will call always the HeavyFactory.heavyInstance?
    return heavy.get();
  }

  private synchronized Heavy createAndCacheHeavy() {
//create a local class inside method? Is the real trick/hack here I missed out so it will avoid 2nd time the synchronized penalty?
    class HeavyFactory implements Supplier<Heavy> {
      private final Heavy heavyInstance = new Heavy();

      public Heavy get() { return heavyInstance; }
    }

    if(!HeavyFactory.class.isInstance(heavy)) {
      heavy = new HeavyFactory();
    }

    return heavy.get();
  }

  public static void main(final String[] args) {
    final Holder holder = new Holder();
    System.out.println("deferring heavy creation...");
    System.out.println(holder.getHeavy());
    System.out.println(holder.getHeavy());
  }
}

package fpij;

public class Heavy {
  public Heavy() { System.out.println("Heavy created"); }

  public String toString() { return "quite heavy"; }
}

Body:
If you are really concerned on the cost of synchronized, there a simple way to make it work correctly while keeping the initialization lazy.

It use the property that the classloader ensure synchronization when the class is loaded. It garentee that no other thread will be able to access the class until it is fully loaded. And the class load is actually lazy: it load the class only when the class is actually used from the first time.

If the only feature of class HeavyFactory is to provide the singleton instance, it will be loaded only when the getInstance is called and all will play nicely.

class HeavyFactory {

private static final Heavy heavyInstance = initInstance();

  public static Heavy getHeavyInstance() {
    return heavyInstance;
  }

  private static Heavy initInstance() {
      heavyInstance = new HeavyInstance();
      [...] // Other init stuff
      return heavyInstance;
  }
}

Edit: The init of complex objects and wiring of dependencies is so common that frameworks like JEE or Spring have implemented ways to do simplify it.

If you use spring for example, you would be able to just declare a given service as a singleton and then declare a dependency on it where you need it. The init would be done when the spring framework initialize in proper order:

// We instruct spring to create a shared instance of heavy
// with @Component annotation
// The instance would be created eagerly at the start of the app.
@Component
public class Heavy {
  public Heavy() { System.out.println("Heavy created"); }

  public String toString() { return "quite heavy"; }
}

// For the example another service using the Heavy shared instance
@Component
public class ClientDependingOnHeavy {

  // We ask spring to fill it automatically the shared instance for us.
  @Autowired
  private Heavy heavy;

  public String foo() {
    //So we can use the instance like any object.
    System.out.println(heavy.toString());
  }
}

Well spring or JEE are quite complex advanced frameworks. For a single case they would not be worth it at all. For a whole application it would make sense. You'd need quite some reading/tutorials to make the second example work if you don't already know them. But in the long run, it may be worth the effort.


问:
Python Dictionary - Invalid Syntax
Why does the following code throw an invalid syntax error?

```<code>grads = {"dW1": dW1,
         "db1": db1,
         "dW2": dW2,
         "db2": db2}
</code>```

It gives the following error

```<code>File "<ipython-input-27-f129b09e7ac8>", line 40
    grads = {"dW1": dW1,
        ^
SyntaxError: invalid syntax
</code>```

答: There is nothing wrong with the scope you are sharing. You have a syntax error above / before declaring grads

Title: Python Dictionary - Invalid Syntax

Body:
Why does the following code throw an invalid syntax error?

grads = {"dW1": dW1,
         "db1": db1,
         "dW2": dW2,
         "db2": db2}

It gives the following error

File "<ipython-input-27-f129b09e7ac8>", line 40
    grads = {"dW1": dW1,
        ^
SyntaxError: invalid syntax


问:
ModuleNotFoundError - Cannot import a python file even though python file exists
I have a project structure like this:

```<code>.
├── .venv
|     └── bin
|          └── python
├── config
│     └── conf.py
├── utils
│   └── test.py
└── requirements.txt
</code>```

Each of the directories above have an __init__.py file so they should be picked up as a Python package.

I am unable to import config into the utils.test.py script.

The error I encounter is:

```<code>File "./utils/test.py", line 2, in <module>
import config.conf
ModuleNotFoundError: No module named 'config'
</code>```

My Python path is "./.venv/bin/python".

Can someone help me resolve this issue so I can import files from different sub-directories?

Thanks!

答:
Add an empty  __init__.py file in the config folder.

Then you can do the following in your test.py

```<code>import config.conf as conf

conf.your_config_function()
</code>```

Body:
I have a project structure like this:

.
├── .venv
|     └── bin
|          └── python
├── config
│     └── conf.py
├── utils
│   └── test.py
└── requirements.txt

Each of the directories above have an __init__.py file so they should be picked up as a Python package.

I am unable to import config into the utils.test.py script.

The error I encounter is:

File "./utils/test.py", line 2, in <module>
import config.conf
ModuleNotFoundError: No module named 'config'

My Python path is "./.venv/bin/python".

Can someone help me resolve this issue so I can import files from different sub-directories?

Thanks!

Body:
Add an empty  __init__.py file in the config folder.

Then you can do the following in your test.py

import config.conf as conf

conf.your_config_function()


问:
Is there a way to run SQL statements on parquet files using dask?
Spark has a functionality that allows users to run SQL statements on a Spark dataframe. What about Dask? If it is not available now, is it something being considered?</p>

答: Presto / AWS Athena may be an answer to your question.</p>


问:
Is there any better way to send information to child view?
I have a view controller which has a child view. I want to convey information from the view to the child view. To do so, I did this :

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "visualize", sender: self)
    invoiceNumber = indexPath.row
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let vc = segue.destination as! PreviewViewController
    vc.invoiceNumber = invoiceNumber
}
</code>```

But the problem is that the value of invoiceNumber is not updated on the first iteration but on the second. I tried to see what the problem was and found that "invoiceNumber = indexPath.row" runs after "vc.invoiceNumber = invoiceNumber". Please help ! Thanks

Here is the code of printing :

```<code>import UIKit

class ViewController: UIViewController {
    var invoiceNumber: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print(invoiceNumber)
    }
}
</code>```

Sorry I have mistaken :

```<code>    var customerData: [[customerInformation]] = []
    var itemsData: [[Item]] = []
    var totalData: [TotalInformation] = []

    var invoiceNumber = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.reloadData()
    }

    override func viewDidAppear(_ animated: Bool) {
        let tabBar = tabBarController as! baseTabBarController
        customerData = tabBar.customerData
        itemsData = tabBar.itemsData
        totalData = tabBar.totalData
        tableView.reloadData()

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return customerData.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let invoiceCell = tableView.dequeueReusableCell(withIdentifier: "invoice", for: indexPath) as! invoiceTableViewCell
        invoiceCell.textLabel?.text = (customerData[indexPath.row][0]).input
        invoiceCell.detailTextLabel?.text = "Invoice n°" + String(indexPath.row)
        invoiceCell.totalLabel.text = (totalData[indexPath.row]).total
        return invoiceCell
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            let tabBar = tabBarController as! baseTabBarController
            tabBar.customerData.remove(at: indexPath.row)
            //itemData.remove(at: indexPath.row)
            tabBar.totalData.remove(at: indexPath.row)
            customerData = tabBar.customerData
            itemsData = tabBar.itemsData
            totalData = tabBar.totalData
            tableView.deleteRows(at: [indexPath], with: .fade)

        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        invoiceNumber = indexPath.row
        print(invoiceNumber, "yes")
        performSegue(withIdentifier: "visualize", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destination as! PreviewViewController
        vc.invoiceNumber = invoiceNumber
    }
}
</code>```

It is the "vc.invoiceNumber = invoiceNumber" which comes before the "invoiceNumber = indexPath.row" as I tried to change the value of invoiceNumber a variable in the view and print out the value in the child view and if showed its value first (I tested -1).

I added the Preview view controller which receives the invoiceNumber :

```<code>import UIKit
import WebKit

class PreviewViewController: UIViewController {

    @IBOutlet var webPreview: UIWebView!

    var invoiceComposer: InvoiceComposer!
    var HTMLContent: String!

    var invoiceNumber: Int = -1

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print(invoiceNumber)
        createInvoiceAsHTML()
    }

    func createInvoiceAsHTML() {
        invoiceComposer = InvoiceComposer()
        if let tabBar = tabBarController as? baseTabBarController {
            if let invoiceHTML = invoiceComposer.renderInvoice(invoiceNumber: String(invoiceNumber), invoiceDate: "", recipientInfo: tabBar.customerData[invoiceNumber][0].input, items: tabBar.itemsData[invoiceNumber], totalAmount: tabBar.totalData[invoiceNumber].total) {

                   webPreview.loadHTMLString(invoiceHTML, baseURL: NSURL(string: invoiceComposer.pathToInvoiceHTMLTemplate!)! as URL)
                   HTMLContent = invoiceHTML
            }
        }
        else {
            print("tabBarController is not of type baseTabBarController or either nil ")
        }

    }

}
</code>```

答: I should have connected the segue from the view controller to the child view and not from the cell to the child view.</p>

Body:
I have a view controller which has a child view. I want to convey information from the view to the child view. To do so, I did this :

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "visualize", sender: self)
    invoiceNumber = indexPath.row
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let vc = segue.destination as! PreviewViewController
    vc.invoiceNumber = invoiceNumber
}

But the problem is that the value of invoiceNumber is not updated on the first iteration but on the second. I tried to see what the problem was and found that "invoiceNumber = indexPath.row" runs after "vc.invoiceNumber = invoiceNumber". Please help ! Thanks

Here is the code of printing :

import UIKit

class ViewController: UIViewController {
    var invoiceNumber: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print(invoiceNumber)
    }
}

Sorry I have mistaken :

    var customerData: [[customerInformation]] = []
    var itemsData: [[Item]] = []
    var totalData: [TotalInformation] = []

    var invoiceNumber = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.reloadData()
    }

    override func viewDidAppear(_ animated: Bool) {
        let tabBar = tabBarController as! baseTabBarController
        customerData = tabBar.customerData
        itemsData = tabBar.itemsData
        totalData = tabBar.totalData
        tableView.reloadData()

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return customerData.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let invoiceCell = tableView.dequeueReusableCell(withIdentifier: "invoice", for: indexPath) as! invoiceTableViewCell
        invoiceCell.textLabel?.text = (customerData[indexPath.row][0]).input
        invoiceCell.detailTextLabel?.text = "Invoice n°" + String(indexPath.row)
        invoiceCell.totalLabel.text = (totalData[indexPath.row]).total
        return invoiceCell
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            let tabBar = tabBarController as! baseTabBarController
            tabBar.customerData.remove(at: indexPath.row)
            //itemData.remove(at: indexPath.row)
            tabBar.totalData.remove(at: indexPath.row)
            customerData = tabBar.customerData
            itemsData = tabBar.itemsData
            totalData = tabBar.totalData
            tableView.deleteRows(at: [indexPath], with: .fade)

        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        invoiceNumber = indexPath.row
        print(invoiceNumber, "yes")
        performSegue(withIdentifier: "visualize", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destination as! PreviewViewController
        vc.invoiceNumber = invoiceNumber
    }
}

It is the "vc.invoiceNumber = invoiceNumber" which comes before the "invoiceNumber = indexPath.row" as I tried to change the value of invoiceNumber a variable in the view and print out the value in the child view and if showed its value first (I tested -1).

I added the Preview view controller which receives the invoiceNumber :

import UIKit
import WebKit

class PreviewViewController: UIViewController {

    @IBOutlet var webPreview: UIWebView!

    var invoiceComposer: InvoiceComposer!
    var HTMLContent: String!

    var invoiceNumber: Int = -1

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print(invoiceNumber)
        createInvoiceAsHTML()
    }

    func createInvoiceAsHTML() {
        invoiceComposer = InvoiceComposer()
        if let tabBar = tabBarController as? baseTabBarController {
            if let invoiceHTML = invoiceComposer.renderInvoice(invoiceNumber: String(invoiceNumber), invoiceDate: "", recipientInfo: tabBar.customerData[invoiceNumber][0].input, items: tabBar.itemsData[invoiceNumber], totalAmount: tabBar.totalData[invoiceNumber].total) {

                   webPreview.loadHTMLString(invoiceHTML, baseURL: NSURL(string: invoiceComposer.pathToInvoiceHTMLTemplate!)! as URL)
                   HTMLContent = invoiceHTML
            }
        }
        else {
            print("tabBarController is not of type baseTabBarController or either nil ")
        }

    }

}


问:
Normalize columns of a dataframe
I have a dataframe in pandas where each column has different value range. For example:

df:

```<code>A     B   C
1000  10  0.5
765   5   0.35
800   7   0.09
</code>```

Any idea how I can normalize the columns of this dataframe where each value is between 0 and 1?

My desired output is:

```<code>A     B    C
1     1    1
0.765 0.5  0.7
0.8   0.7  0.18(which is 0.09/0.5)
</code>```

答:
```<code>df_normalized = df / df.max(axis=0)
</code>```

Title: Normalize columns of a dataframe

Body:
I have a dataframe in pandas where each column has different value range. For example:

df:

A     B   C
1000  10  0.5
765   5   0.35
800   7   0.09

Any idea how I can normalize the columns of this dataframe where each value is between 0 and 1?

My desired output is:

A     B    C
1     1    1
0.765 0.5  0.7
0.8   0.7  0.18(which is 0.09/0.5)

Body: df_normalized = df / df.max(axis=0)


问:
How to determine the language of a piece of text?
I want to get this:

Input text: "ру́сский язы́к"
Output text: "Russian"

Input text: "中文"
Output text: "Chinese"

Input text: "にほんご"
Output text: "Japanese"

Input text: "العَرَبِيَّة"
Output text: "Arabic"
```

How can I do it in python?

答:
If you are looking for a library that is fast with long texts, polyglot and fastext are doing the best job here.

I sampled 10000 documents from a collection of dirty and random HTMLs, and here are the results:

```<code>+------------+----------+
| Library    | Time     |
+------------+----------+
| polyglot   | 3.67 s   |
+------------+----------+
| fasttext   | 6.41     |
+------------+----------+
| cld3       | 14 s     |
+------------+----------+
| langid     | 1min 8s  |
+------------+----------+
| langdetect | 2min 53s |
+------------+----------+
| chardet    | 4min 36s |
+------------+----------+
</code>```

I have noticed that a lot of the methods focus on short texts, probably because it is the hard problem to solve: if you have a lot of text, it is really easy to detect languages (e.g. one could just use a dictionary!). However, this makes it difficult to find for an easy and suitable method for long texts.

Body:
I want to get this:

Input text: "ру́сский язы́к"
Output text: "Russian"

Input text: "中文"
Output text: "Chinese"

Input text: "にほんご"
Output text: "Japanese"

Input text: "العَرَبِيَّة"
Output text: "Arabic"

How can I do it in python?

Body:
If you are looking for a library that is fast with long texts, polyglot and fastext are doing the best job here.

I sampled 10000 documents from a collection of dirty and random HTMLs, and here are the results:

+------------+----------+
| Library    | Time     |
+------------+----------+
| polyglot   | 3.67 s   |
+------------+----------+
| fasttext   | 6.41     |
+------------+----------+
| cld3       | 14 s     |
+------------+----------+
| langid     | 1min 8s  |
+------------+----------+
| langdetect | 2min 53s |
+------------+----------+
| chardet    | 4min 36s |
+------------+----------+

I have noticed that a lot of the methods focus on short texts, probably because it is the hard problem to solve: if you have a lot of text, it is really easy to detect languages (e.g. one could just use a dictionary!). However, this makes it difficult to find for an easy and suitable method for long texts.


问:
Problem setting unique meta keywords for each page
I am currently in the process of trying to add unique page titles and keywords to the pages on a website.  Previously I had set the title, keywords and description in the application layout but ideally i would like to be able to set these individually for each page.

Looking at previous questions, I found it was possible to set the title using the code below:

[In application layout]

```<code><title><%=h yield(:title) %></title>
</code>```

[In page view]

```<code><% content_for :title, "Content here..." %>
</code>```

This worked just as hoped.  However, I then tried to apply the same logic to the meta keywords:

```<code><meta name="keywords" content=<%=h yield(:keywords) %> >

<% content_for :keywords, "word1, word2, word3" %>
</code>```

This doesn't give an error, however, when I view the page source there are " missing, i.e. it appears as:

```<code><meta name="keywords" content=word1, word2, word3 >
</code>```

rather than

```<code><meta name="keywords" content="word1, word2, word3">
</code>```

Is there an easy way to remedy this, or am I barking up the wrong tree trying to do it this way?

答:
Just add quotes to your code:</p>

```<code><meta name="keywords" content="<%=h yield(:keywords) %>">
</code>```

Body:
I am currently in the process of trying to add unique page titles and keywords to the pages on a website.  Previously I had set the title, keywords and description in the application layout but ideally i would like to be able to set these individually for each page.

Looking at previous questions, I found it was possible to set the title using the code below:

[In application layout]

<title><%=h yield(:title) %></title>

[In page view]

<% content_for :title, "Content here..." %>

This worked just as hoped.  However, I then tried to apply the same logic to the meta keywords:

<meta name="keywords" content=<%=h yield(:keywords) %> >

<% content_for :keywords, "word1, word2, word3" %>

This doesn't give an error, however, when I view the page source there are " missing, i.e. it appears as:

<meta name="keywords" content=word1, word2, word3 >

rather than

<meta name="keywords" content="word1, word2, word3">

Is there an easy way to remedy this, or am I barking up the wrong tree trying to do it this way?

Body:
Just add quotes to your code:

<meta name="keywords" content="<%=h yield(:keywords) %>">


问:
Conditional update of vector
I want to update a vector depending on its value:

If f < 50, then x = f - 1

If f > 50, then  y = f + 1

If f == 50, then set the value to zero

```<code>f <- seq(0, 100, by = 5)
</code>```

I was trying to solve it with if, but the result wasn't good.

```<code>if (f<50)
{
  f = z
  x= z-1
  x
}
</code>```

```<code>if (f>50)
{
  f = c
  y= c+1
  y
}
</code>```

答:
You can use nested ifelse :

```<code>ifelse(f < 50, f - 1, ifelse(f > 50, f + 1, 0))
</code>```

Or probably using case_when in which you can add multiple conditions.

```<code>dplyr::case_when(f < 50 ~ f - 1,
                 f > 50 ~ f + 1,
                 f == 50 ~ 0)
</code>```

Title: Conditional update of vector

Body:
I want to update a vector depending on its value:

If f < 50, then x = f - 1

If f > 50, then  y = f + 1

If f == 50, then set the value to zero

f <- seq(0, 100, by = 5)

I was trying to solve it with if, but the result wasn't good.

if (f<50)
{
  f = z
  x= z-1
  x
}

if (f>50)
{
  f = c
  y= c+1
  y
}

Body:
You can use nested ifelse :

ifelse(f < 50, f - 1, ifelse(f > 50, f + 1, 0))

Or probably using case_when in which you can add multiple conditions.

dplyr::case_when(f < 50 ~ f - 1,
                 f > 50 ~ f + 1,
                 f == 50 ~ 0)


问:
How does the use of `static` affect the speed of my code?
I was solving an exercise online, and at one point i needed to delete the "" from a the beginning and end of a string. This was my code:

void static inline process_value(std::string &value) {
    if (value.back() !='>') {
        value = value.substr(1, value.size()-2);
    }
}
```

<p>Called from this benchmark loop:</p>

```static void UsingStatic(benchmark::State& state) {
  // Code inside this loop is measured repeatedly
  for (auto _ : state) {
      std::string valor("\"Hola\"");
      process_valueS(valor);
    // Make sure the variable is not optimized away by compiler
    benchmark::DoNotOptimize(valor);
  }
}
```

Just because of curiosity I did a benchmark.

Compiler: Clang-9.0

std: c++20

optim: O3

STL: libstdc++(GNU)

While I was at it I decided to remove static from process_value, making void inline process_value that was otherwise the same.  To my surprise it was slower.

I thought that static only meant that the function was just for a file. But here it says that " 'static' means that the function should be inlined by the compiler if possible". But in that case when i removed static I think that the result should not have changed. Now I'm am confused, what other things does static do other than delimiting the function to a single .cpp, how does that affect performance?

The disassembly on QuickBench shows that the NoUsingStatic loop actually calls process_value instead of inlining it, despite the inline keyword making it legal for the compiler to do so.  But UsingStatic does inline the call to process_valueS.  That difference in compiler decision-making presumably explains the difference in performance, but why would clang choose not to inline a simple function declared void inline process_value(std::string &value){ ... }?

EDIT: Beacuse the question was closed because it was not clear enough, i deleted parts that where not related to the question. But if im missing some information please tell me in the comments

答:
inline is just an advise to the compiler, which may or may not really inline that your particular code.

Regarding to the static keyword, if it's applied to a global variable, then it has the file-scope (as you've mentioned) if you compile your code as a separate compilation-unit. So it's even possible to have your static global variables accessible from other files if you compile them as a single compilation unit. This means that in reality, the scope of the global static variables is not the file but the compilation unit (which may or may not be one single file).

But, since you have a global static function, not a variable, it is accessible from everywhere as a global static function.

EDIT:
As suggested by @Peter Cordes in comments below, it may be a real mess with inline and static at the same time, so the official doc ( https://en.cppreference.com/w/cpp/language/inline ) says that the redefinition of inline functions (and variables since C++17) must be non-static.

Body:
I was solving an exercise online, and at one point i needed to delete the "" from a the beginning and end of a string. This was my code:

void static inline process_value(std::string &value) {
    if (value.back() !='>') {
        value = value.substr(1, value.size()-2);
    }
}

Called from this benchmark loop:

static void UsingStatic(benchmark::State& state) {
  // Code inside this loop is measured repeatedly
  for (auto _ : state) {
      std::string valor("\"Hola\"");
      process_valueS(valor);
    // Make sure the variable is not optimized away by compiler
    benchmark::DoNotOptimize(valor);
  }
}

Just because of curiosity I did a benchmark.

Compiler: Clang-9.0

std: c++20

optim: O3

STL: libstdc++(GNU)

While I was at it I decided to remove static from process_value, making void inline process_value that was otherwise the same.  To my surprise it was slower.

I thought that static only meant that the function was just for a file. But here it says that " 'static' means that the function should be inlined by the compiler if possible". But in that case when i removed static I think that the result should not have changed. Now I'm am confused, what other things does static do other than delimiting the function to a single .cpp, how does that affect performance?

The disassembly on QuickBench shows that the NoUsingStatic loop actually calls process_value instead of inlining it, despite the inline keyword making it legal for the compiler to do so.  But UsingStatic does inline the call to process_valueS.  That difference in compiler decision-making presumably explains the difference in performance, but why would clang choose not to inline a simple function declared void inline process_value(std::string &value){ ... }?

EDIT: Beacuse the question was closed because it was not clear enough, i deleted parts that where not related to the question. But if im missing some information please tell me in the comments