问:
Send GCM notification to an offline device
If I am sending a notification to a device, and that device is offline I get something like:

Error: Unavailable

And I have to resend.

My question is:

Will the GCM server keep these notifications in a queue and automatically resend when the device is online? Or it must be completely handled by me.

Because if the GCM server is going to send them automatically(once the device is online), until it actually sends the notifications, my server assumes they are already sent. How to track the time when the notifications are resent successfully?

I might mark on my server side that the notifications are not sent by looking at the Unavailable error message but cannot make out how to mark them as sent once the GCM successfully sends the notifications.

Thank You

答:
What I did was to separate the push indication from the payload. In my GCM message I only include a URI to the payload, and I store the payload in a database table accessible through the URI in the message.

When the client receives a message, it could e.g. look like this, with HATEOAS style links:

```<code>{
  _links: {
    message: {
      rel: 'message',
      href: 'https://my-server.com/push/<messageId>'
    }
  }
}
</code>```

The client then goes to GET the message payload from the URI, at which point the server knows that it's been delivered and can update accordingly. Fetching the payload also deletes it.

If GCM re-delivery is not robust enough this also means that the client can choose to manually fetch all pending messages, e.g. when network connectivity is resumed after being offline, by having an endpoint that returns all messages for a given ANDROID_ID or similar. If then later the GCM message is delivered, the client would get a 404 for the URI in that message and treat that as a no-op, i.e., message already handled.

If this is overkill, a light-weight approach to just achieve server awareness of message delivery is to have an endpoint that simply ACKs the reception of a message with a given ID, such as

```<code>POST https://my-server.com/push/notifyReceived

{
  messageId: <messageId>
}
</code>```

Body:
What I did was to separate the push indication from the payload. In my GCM message I only include a URI to the payload, and I store the payload in a database table accessible through the URI in the message.

When the client receives a message, it could e.g. look like this, with HATEOAS style links:

{
  _links: {
    message: {
      rel: 'message',
      href: 'https://my-server.com/push/<messageId>'
    }
  }
}

The client then goes to GET the message payload from the URI, at which point the server knows that it's been delivered and can update accordingly. Fetching the payload also deletes it.

If GCM re-delivery is not robust enough this also means that the client can choose to manually fetch all pending messages, e.g. when network connectivity is resumed after being offline, by having an endpoint that returns all messages for a given ANDROID_ID or similar. If then later the GCM message is delivered, the client would get a 404 for the URI in that message and treat that as a no-op, i.e., message already handled.

If this is overkill, a light-weight approach to just achieve server awareness of message delivery is to have an endpoint that simply ACKs the reception of a message with a given ID, such as

POST https://my-server.com/push/notifyReceived

{
  messageId: <messageId>
}


来源: stackexchange

问:
phpmail always go to spam
how to optimize php_mail() w/o sending the email to a spam?
everything that my webpage is doing sends the email into spam?how to make it not go to spam??</p>

答: This depends on the spam engine that you have. There is no way you can optimize a PHP function for this. Just try to create the email using correct headers and to be sent from a real email address. If you are doing a newsletter always have a mechanism to unsubscribe, this is a requisite for not entering spam list.</p>

ContentLicense: CC BY-SA 2.5

Title: phpmail always go to spam


问:
Convert value number key to string php?
Here is my code :

```<code> foreach($urlImages as $key => $u){

        $nameImg = $id_product.'_'.$key.'_'.md5(uniqid(rand(), true)).'.png';

    }
</code>```

The key value is incremented, I want to change the key number to a string like:

```<code>if $key=1 i want $key=white
if $key=2 i want $key=black
</code>```

答:
You can use  Comparison Operators if the choice is only a few

```<code>$result = ($value == $condition?)valTrue : valFalse;
</code>```

this an example for your case 1 for white, 2 for black and 3 for grey.

```<code> <?php
        $urlImages = array(  "1" => "test.png","2" => "test2.png", "3" => "test3.png");
        foreach($urlImages as $key => $u){
          $nameImg[] = $id_product.'_'.($key == 1?'white':($key == 2?'black':'grey')).'_'.md5(uniqid(rand(0,1000), true)).'.png';
        }
        print_r($nameImg);
        ?>
</code>```

/result/

```<code>Array
(
    [0] => _white_6c4f456490be5893166478b2d35912ad.png
    [1] => _black_eb4c071837bf74ce6b9c1c445ff230f7.png
    [2] => _grey_80615be519a0d7db22a8241dc365acb9.png
)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Convert value number key to string php?

Body:
Here is my code :

 foreach($urlImages as $key => $u){

        $nameImg = $id_product.'_'.$key.'_'.md5(uniqid(rand(), true)).'.png';

    }

The key value is incremented, I want to change the key number to a string like:

if $key=1 i want $key=white
if $key=2 i want $key=black

Body:
You can use  Comparison Operators if the choice is only a few

$result = ($value == $condition?)valTrue : valFalse;

this an example for your case 1 for white, 2 for black and 3 for grey.

 <?php
        $urlImages = array(  "1" => "test.png","2" => "test2.png", "3" => "test3.png");
        foreach($urlImages as $key => $u){
          $nameImg[] = $id_product.'_'.($key == 1?'white':($key == 2?'black':'grey')).'_'.md5(uniqid(rand(0,1000), true)).'.png';
        }
        print_r($nameImg);
        ?>

/result/

Array
(
    [0] => _white_6c4f456490be5893166478b2d35912ad.png
    [1] => _black_eb4c071837bf74ce6b9c1c445ff230f7.png
    [2] => _grey_80615be519a0d7db22a8241dc365acb9.png
)


问:
How to use replaceFirst() to get a series of sequential strings in my case?
My input string uid contains 6 characters, and there are 0~6 '?' at random position like "00??00", "0?00?0", "0??00?". For example, if the input is "00?0?0", I want to replace two '?' with 0~9. So the results should be "000000","000010","000020"..."000090","001000","001010"..."001090"..."009090"

Well, my following code can only get "000000","001010","002020"..."009090", I got to know that replace() will replace all '?', and using replaceFirst() might solve it. So how to use replaceFirst() to get the results I want?

```<code>List<Get> gets = new ArrayList<>();

for (int i =0; i<10; i++){
    get = new Get((uid.replace(uid.charAt(2), (char) (i + '0'))).getBytes());

    // get = new Get((uid.replaceFirst("\\?", "0+i")).getBytes());

    gets.add(get);
}
</code>```

答:
It's a lengthy solution. But it works,</p>

```<code>public static void main(String[] args) {

        String patt = "0?0?00";
        List<String> a = new ArrayList<>();
        a.add(patt);
        while (true) {
            List<String> b = generateAndGet(a);
            if (b.size() == 0) {
                break;
            }
            a = b;
        }
        for (String item : a) {
            System.out.println(item);
        }
        return;
    }

    private static List<String> generateAndGet(List<String> val) {
        List<String> result = new ArrayList<String>();
        for (String item : val) {
            final char[] itemArray = item.toCharArray();
            for (int i = 0; i < itemArray.length; i++) {
                if (itemArray[i] == '?') {
                    for (int j = 0; j < 10; j++) {
                        itemArray[i] = (char) (j + '0');
                        result.add(String.copyValueOf(itemArray));
                    }
                }
            }
        }
        return result;
    }
</code>```

Body:
My input string uid contains 6 characters, and there are 0~6 '?' at random position like "00??00", "0?00?0", "0??00?". For example, if the input is "00?0?0", I want to replace two '?' with 0~9. So the results should be "000000","000010","000020"..."000090","001000","001010"..."001090"..."009090"

Well, my following code can only get "000000","001010","002020"..."009090", I got to know that replace() will replace all '?', and using replaceFirst() might solve it. So how to use replaceFirst() to get the results I want?

List<Get> gets = new ArrayList<>();

for (int i =0; i<10; i++){
    get = new Get((uid.replace(uid.charAt(2), (char) (i + '0'))).getBytes());

    // get = new Get((uid.replaceFirst("\\?", "0+i")).getBytes());

    gets.add(get);
}

Body:
It's a lengthy solution. But it works,

public static void main(String[] args) {

        String patt = "0?0?00";
        List<String> a = new ArrayList<>();
        a.add(patt);
        while (true) {
            List<String> b = generateAndGet(a);
            if (b.size() == 0) {
                break;
            }
            a = b;
        }
        for (String item : a) {
            System.out.println(item);
        }
        return;
    }

    private static List<String> generateAndGet(List<String> val) {
        List<String> result = new ArrayList<String>();
        for (String item : val) {
            final char[] itemArray = item.toCharArray();
            for (int i = 0; i < itemArray.length; i++) {
                if (itemArray[i] == '?') {
                    for (int j = 0; j < 10; j++) {
                        itemArray[i] = (char) (j + '0');
                        result.add(String.copyValueOf(itemArray));
                    }
                }
            }
        }
        return result;
    }


问:
Pythonic way to switch object "behind the scenes"
I know about the nature of python object names being nothing but "labels" that can be attached to any object and that variables are always passed by reference. But what if I need a different behavior?

To illustrate this, I made a Short example:

```<code>class car:
    def __init__(self, brand):
        self.brand = brand

subaru = car("subaru")
toyota = car("toyota")

current_car = subaru
current_brand = current_car.brand

print (current_brand)

current_car = toyota

print (current_brand)
</code>```

The Output I get is:

```<code>subaru
subaru
</code>```

This doesn't surprise me. However in the project I'm working on right now, I would like to express a selection by making current_car the selected car. Also I would like the object current_brand to always hold the brand of the current car without explicitly doing:

```<code>current_brand = current_car.brand
</code>```

every time I switch the current car. I thought about using a property decorator for this, but I am not shure, that that's the right way. Is there a pythonic way to do this or am I thinking in the wrong direction all-together?

答:
I can only think of a __repr__ trick: when you display, print or convert an object to a string, you use its __repr__ method to do the conversion. Here, you could try:

```<code>class CurrentBrand:
    def __repr__(self):
        return current_car.brand
current_brand = CurrentBrand()
</code>```

Now if you do:

```<code>subaru = car("subaru")
toyota = car("toyota")

current_car = subaru
print (current_brand)

current_car = toyota
print (current_brand)
</code>```

The output will be as expected:

```<code>subaru
toyota
</code>```

The limits of the trick are that any direct assignement to current_car will break the magic, and that it is not a string...

Body:
I know about the nature of python object names being nothing but "labels" that can be attached to any object and that variables are always passed by reference. But what if I need a different behavior?

To illustrate this, I made a Short example:

class car:
    def __init__(self, brand):
        self.brand = brand

subaru = car("subaru")
toyota = car("toyota")

current_car = subaru
current_brand = current_car.brand

print (current_brand)

current_car = toyota

print (current_brand)

The Output I get is:

subaru
subaru

This doesn't surprise me. However in the project I'm working on right now, I would like to express a selection by making current_car the selected car. Also I would like the object current_brand to always hold the brand of the current car without explicitly doing:

current_brand = current_car.brand

every time I switch the current car. I thought about using a property decorator for this, but I am not shure, that that's the right way. Is there a pythonic way to do this or am I thinking in the wrong direction all-together?

Body:
I can only think of a __repr__ trick: when you display, print or convert an object to a string, you use its __repr__ method to do the conversion. Here, you could try:

class CurrentBrand:
    def __repr__(self):
        return current_car.brand
current_brand = CurrentBrand()

Now if you do:

subaru = car("subaru")
toyota = car("toyota")

current_car = subaru
print (current_brand)

current_car = toyota
print (current_brand)

The output will be as expected:

subaru
toyota

The limits of the trick are that any direct assignement to current_car will break the magic, and that it is not a string...


问:
Is it possible to have 2 repos on GitHub forked from the same repo and show it so on GitHub?
Is there a way to do it?

The reason is, there is a starter template for React / Redux https://github.com/StephenGrider/ReduxSimpleStarter , and there are 2 or 3 sample apps that can be built from it.

So naturally you would fork it and git clone to your hard drive and then go on with the project. After you are done with project 1, then for project 2, fork it again and repeat.

But GitHub doesn't allow forking it twice per account.

So what I did was git clone that repo, and then did

```<code>git remote remove origin
git remote add origin git@github.com:myusername/ReactReduxAppOne.git
git remote set-url upstream https://github.com/StephenGrider/ReduxSimpleStarter
</code>```

but my GitHub repo still will not show that it is forked from the original repo (on the GitHub webpage). Is there a way to make it so?

答:
Do you really want to fork a template? Forks are intended to be used when you want to make changes that are then submitted back to the original as a Pull Request.

On the other hand, a template project is intended to be used as a starting point for your own unique projects. Instead of forking on GitHub, you should just clone the template to your local machine. Then create a brand new GitHub repo and add it as a remote to your cloned project. Now you can push your project to GitHub and get on with development.

Body:
Is there a way to do it?

The reason is, there is a starter template for React / Redux https://github.com/StephenGrider/ReduxSimpleStarter , and there are 2 or 3 sample apps that can be built from it.

So naturally you would fork it and git clone to your hard drive and then go on with the project. After you are done with project 1, then for project 2, fork it again and repeat.

But GitHub doesn't allow forking it twice per account.

So what I did was git clone that repo, and then did

git remote remove origin
git remote add origin git@github.com:myusername/ReactReduxAppOne.git
git remote set-url upstream https://github.com/StephenGrider/ReduxSimpleStarter

but my GitHub repo still will not show that it is forked from the original repo (on the GitHub webpage). Is there a way to make it so?


问:
Keras 2DConvolution produces unlogical output tensor - 32x32 image becomes 32xN feature maps, instead of 32x32xN
According to my understanding, a 2D-Convolution applies N filters to an input image, producing N new "images" (=feature maps).

If we neglect stride/subsampling, a 32x32 image becomes a Nx32x32 tensor after 2D-Convolution with N channels:

However, in Keras, a 32x32 input produces a 32xN output. So, my question is, how is the dimensional reduction applied? Is there another hidden layer involved in this step?

And if so, isn't the network losing its ability to view the image as it is - namely a 2D-entity?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This code can reproduce my above claims:

```<code>inputs = Input(shape=(1, 32, 32,))
shared = Convolution2D(nb_filter=10, nb_row=8, nb_col=8, subsample=(1, 1), border_mode='same', activation='relu')(inputs)
print("1 => ", inputs.shape)
print("2 => ", shared.shape)
</code>```

It produces - as we apply 10 filters (==N) to a 32x32 grayscale image

1 =>  (?, 1, 32, 32)

2 =>  (?, 1, 32, 10)

Where ? is the unspecified batch size and 1 is the amount of input-channels (would be 3 for RGB, is 1 for Grayscale).

The input has a shape of 32x32, as expected.
But then, the output of the convolution has 32xN dimensions instead of 32x32xN

Body:
According to my understanding, a 2D-Convolution applies N filters to an input image, producing N new "images" (=feature maps).

If we neglect stride/subsampling, a 32x32 image becomes a Nx32x32 tensor after 2D-Convolution with N channels:

However, in Keras, a 32x32 input produces a 32xN output. So, my question is, how is the dimensional reduction applied? Is there another hidden layer involved in this step?

And if so, isn't the network losing its ability to view the image as it is - namely a 2D-entity?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This code can reproduce my above claims:

inputs = Input(shape=(1, 32, 32,))
shared = Convolution2D(nb_filter=10, nb_row=8, nb_col=8, subsample=(1, 1), border_mode='same', activation='relu')(inputs)
print("1 => ", inputs.shape)
print("2 => ", shared.shape)

It produces - as we apply 10 filters (==N) to a 32x32 grayscale image

1 =>  (?, 1, 32, 32)

2 =>  (?, 1, 32, 10)

Where ? is the unspecified batch size and 1 is the amount of input-channels (would be 3 for RGB, is 1 for Grayscale).

The input has a shape of 32x32, as expected.
But then, the output of the convolution has 32xN dimensions instead of 32x32xN

Body:
No, you are doing something wrong. The following code:

 import keras
 from keras.layers import Input, Convolution2D
 from keras.models import Model
 inputs = Input(shape=(1, 32, 32,))
 shared = Convolution2D(nb_filter=10, nb_row=8, nb_col=8,
 subsample=(1, 1), border_mode='same', activation='relu')(inputs)

 model = Model(inputs, shared)

 model.summary()

Prints the following:

____________________________________________________________________________________________________
Layer (type)                       Output Shape        Param #     Connected to
====================================================================================================
input_1 (InputLayer)               (None, 1, 32, 32)   0
____________________________________________________________________________________________________
convolution2d_1 (Convolution2D)    (None, 10, 32, 32)  650         input_1[0][0]
====================================================================================================
Total params: 650
____________________________________________________________________________________________________

And you can see that the output shape of Convolution2D indeed has 10 channels. If you area getting different results, check that the image_ordering is correct (and makes sense).


问:
from NSFetchedResults objectAtIndex:0 returning 0
I've been banging my head on this one specific issue for about 2 hours now, reading through documentation and examples and I just can't wrap my head around it. I have core data models Person and Photo, and they're linked. I'm trying to display a UITableView with the contents and

```<code>-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
</code>```

keeps returning 0. Here is the relevant code.
I know there is data in my core data because I can look at it with sqlite in terminal.

AppDelegate.h

```<code>@interface PaparazziAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;

    UITabBarController *tabController;
    UINavigationController *mainNavController;
    UINavigationController *recentsNavController;
    PersonListViewController  *personListView;
    PhotoListViewController *recentsList;
    PhotoDetailViewController *photoDetail;

    FlickrFetcher *fetcher;
    NSManagedObjectContext *currentContext;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@property (nonatomic, retain) IBOutlet UITabBarController *tabController;
@property (nonatomic, retain) IBOutlet UINavigationController *mainNavController, *recentsNavController;

@end
</code>```

AppDelegate.m

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

@implementation PaparazziAppDelegate

@synthesize window;
@synthesize tabController, mainNavController, recentsNavController;

#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Setup the database instances for access.
    fetcher = [FlickrFetcher sharedInstance];

    // Check to see if the database exists, if not, load the plist and populate.
    if ([fetcher databaseExists])
        NSLog(@"I'm here!");
    else {
        NSLog(@"No database yet!");

        currentContext = [fetcher managedObjectContext];

        /* -- REMOVED FOR READABILITY --
        A chunk of code for creating fresh data from a plist if the database doesn't yet exist.
        I know this part works because I can see the data using the terminal */

        [currentContext release];
    }
    // End of the plist loading and database creation.

    personListView = [[PersonListViewController alloc] initWithStyle:UITableViewStylePlain];
    personListView.title = @"Contacts";
    [mainNavController pushViewController:personListView animated:NO];
    [personListView release];

    recentsList = [[PhotoListViewController alloc] initWithNibName:@"PhotoListViewController" bundle:[NSBundle mainBundle]];
    recentsList.title = @"Recents";
    [recentsNavController pushViewController:recentsList animated:NO];
    [recentsList release];

    // setting up view icons
    UITabBarItem *contactsIcon = [[UITabBarItem alloc]
                          initWithTabBarSystemItem:UITabBarSystemItemContacts tag:0];
    mainNavController.tabBarItem = contactsIcon;
    [contactsIcon release];
    UITabBarItem *recentsIcon = [[UITabBarItem alloc]
                                  initWithTabBarSystemItem:UITabBarSystemItemRecents tag:0];
    recentsNavController.tabBarItem = recentsIcon;
    [recentsIcon release];

    [self.window addSubview:tabController.view];

    // Override point for customization after application launch.

    [self.window makeKeyAndVisible];

    return YES;
}

- (void)dealloc {
    [window release];
    [tabController release];
    [mainNavController release];
    [recentsNavController release];

    [fetcher release];

    [super dealloc];
}

@end
</code>```

PersonListViewController.h

```<code>#import <UIKit/UIKit.h>
#import "FlickrFetcher.h"
#import "Person.h"
#import "Photo.h"

@interface PersonListViewController : UITableViewController {
    NSArray *listOfPeople;

    FlickrFetcher *fetcher;
    NSManagedObjectContext *currentContext;
    NSFetchedResultsController *fetchedResultsController;
}

@property (nonatomic, retain) NSArray *listOfPeople;
@property (nonatomic, retain) NSManagedObjectContext *currentContext;
@property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;

@end
</code>```

And the trouble file, PersonListViewController.m

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

@implementation PersonListViewController

@synthesize listOfPeople, currentContext, fetchedResultsController;

#pragma mark -
#pragma mark Initialization

- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization.
        fetcher = [FlickrFetcher sharedInstance];
        currentContext = [fetcher managedObjectContext];

        fetchedResultsController = [fetcher fetchedResultsControllerForEntity:@"Person" withPredicate:nil];
    }
    return self;
}

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"Contacts";
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    Person *person = [fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = [person name];

    // Configure the cell...

    return cell;
}

#pragma mark -
#pragma mark Memory management

- (void)dealloc {
    [super dealloc];
}

@end
</code>```

I have a feeling I'm missing something simple or 1 off, but I just can't seem to find it.
[FlickrFetcher sharedInstance] returns a singleton, if I toss a few breakpoints into each .m file, I can see that the object id of *fetcher in each area is the same.

答:
It looks like you haven't used performFetch: to execute the fetched results controller's request. viewWillAppear: is usually a good place to do it:

```<code> - (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    NSError *error = nil;
    if (![fetchedResultsController performFetch:&error]) {
        NSLog(@"fetch error: %@", error);
    }
 }
</code>```

Body:
I've been banging my head on this one specific issue for about 2 hours now, reading through documentation and examples and I just can't wrap my head around it. I have core data models Person and Photo, and they're linked. I'm trying to display a UITableView with the contents and

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

keeps returning 0. Here is the relevant code.
I know there is data in my core data because I can look at it with sqlite in terminal.

AppDelegate.h

@interface PaparazziAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;

    UITabBarController *tabController;
    UINavigationController *mainNavController;
    UINavigationController *recentsNavController;
    PersonListViewController  *personListView;
    PhotoListViewController *recentsList;
    PhotoDetailViewController *photoDetail;

    FlickrFetcher *fetcher;
    NSManagedObjectContext *currentContext;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@property (nonatomic, retain) IBOutlet UITabBarController *tabController;
@property (nonatomic, retain) IBOutlet UINavigationController *mainNavController, *recentsNavController;

@end

AppDelegate.m

#import "PaparazziAppDelegate.h"

@implementation PaparazziAppDelegate

@synthesize window;
@synthesize tabController, mainNavController, recentsNavController;

#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Setup the database instances for access.
    fetcher = [FlickrFetcher sharedInstance];

    // Check to see if the database exists, if not, load the plist and populate.
    if ([fetcher databaseExists])
        NSLog(@"I'm here!");
    else {
        NSLog(@"No database yet!");

        currentContext = [fetcher managedObjectContext];

        /* -- REMOVED FOR READABILITY --
        A chunk of code for creating fresh data from a plist if the database doesn't yet exist.
        I know this part works because I can see the data using the terminal */

        [currentContext release];
    }
    // End of the plist loading and database creation.

    personListView = [[PersonListViewController alloc] initWithStyle:UITableViewStylePlain];
    personListView.title = @"Contacts";
    [mainNavController pushViewController:personListView animated:NO];
    [personListView release];

    recentsList = [[PhotoListViewController alloc] initWithNibName:@"PhotoListViewController" bundle:[NSBundle mainBundle]];
    recentsList.title = @"Recents";
    [recentsNavController pushViewController:recentsList animated:NO];
    [recentsList release];

    // setting up view icons
    UITabBarItem *contactsIcon = [[UITabBarItem alloc]
                          initWithTabBarSystemItem:UITabBarSystemItemContacts tag:0];
    mainNavController.tabBarItem = contactsIcon;
    [contactsIcon release];
    UITabBarItem *recentsIcon = [[UITabBarItem alloc]
                                  initWithTabBarSystemItem:UITabBarSystemItemRecents tag:0];
    recentsNavController.tabBarItem = recentsIcon;
    [recentsIcon release];

    [self.window addSubview:tabController.view];

    // Override point for customization after application launch.

    [self.window makeKeyAndVisible];

    return YES;
}

- (void)dealloc {
    [window release];
    [tabController release];
    [mainNavController release];
    [recentsNavController release];

    [fetcher release];

    [super dealloc];
}

@end

PersonListViewController.h

#import <UIKit/UIKit.h>
#import "FlickrFetcher.h"
#import "Person.h"
#import "Photo.h"

@interface PersonListViewController : UITableViewController {
    NSArray *listOfPeople;

    FlickrFetcher *fetcher;
    NSManagedObjectContext *currentContext;
    NSFetchedResultsController *fetchedResultsController;
}

@property (nonatomic, retain) NSArray *listOfPeople;
@property (nonatomic, retain) NSManagedObjectContext *currentContext;
@property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;

@end

And the trouble file, PersonListViewController.m

#import "PersonListViewController.h"

@implementation PersonListViewController

@synthesize listOfPeople, currentContext, fetchedResultsController;

#pragma mark -
#pragma mark Initialization

- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization.
        fetcher = [FlickrFetcher sharedInstance];
        currentContext = [fetcher managedObjectContext];

        fetchedResultsController = [fetcher fetchedResultsControllerForEntity:@"Person" withPredicate:nil];
    }
    return self;
}

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"Contacts";
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    Person *person = [fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = [person name];

    // Configure the cell...

    return cell;
}

#pragma mark -
#pragma mark Memory management

- (void)dealloc {
    [super dealloc];
}

@end

I have a feeling I'm missing something simple or 1 off, but I just can't seem to find it.
[FlickrFetcher sharedInstance] returns a singleton, if I toss a few breakpoints into each .m file, I can see that the object id of *fetcher in each area is the same.

Body:
It looks like you haven't used performFetch: to execute the fetched results controller's request. viewWillAppear: is usually a good place to do it:

 - (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    NSError *error = nil;
    if (![fetchedResultsController performFetch:&error]) {
        NSLog(@"fetch error: %@", error);
    }
 }


问:
Internal links still point to development subdomain?
I moved a wordpress site from a subdirectory http://www.development.example.com to the root public_html directory.
I have updated the site & home urls to http://www.example.com and verified in phpMyAdmin in the control panel. The header links to other pages work as expected but my internal jump links on the home page such as http://www.example.com/#about still point to the subdomain link http://www.development.example.com/#about. Is there another place in the admin dashboard or directly in the database that I can check for necessary url changes to resolve this?

答:
Please update query in your database

```<code>UPDATE wp_options SET option_value = replace(option_value, 'http://olddomain.com', 'http://newdomain.com') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE wp_posts SET guid = replace(guid, 'http://olddomain.com','http://newdomain.com');
UPDATE wp_posts SET post_content = replace(post_content, 'http://olddomain.com', 'http://newdomain.com');
UPDATE wp_postmeta SET meta_value = replace(meta_value, 'http://olddomain.com', 'http://newdomain.com');
</code>```

Change you oldomain link and newdomain link

I hope this help of you

Body:
Please update query in your database

UPDATE wp_options SET option_value = replace(option_value, 'http://olddomain.com', 'http://newdomain.com') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE wp_posts SET guid = replace(guid, 'http://olddomain.com','http://newdomain.com');
UPDATE wp_posts SET post_content = replace(post_content, 'http://olddomain.com', 'http://newdomain.com');
UPDATE wp_postmeta SET meta_value = replace(meta_value, 'http://olddomain.com', 'http://newdomain.com');

Change you oldomain link and newdomain link

I hope this help of you


问:
Start activity crashes app else the app is minimazin
My app receives data from the database for authorization and registration.When startActivity(new Intent(this, Main.class));
line is commented out the app just minimize, and when uncommented it crashes.

Manifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.littledev.test_v2">
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".Login">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Main">

        </activity>
    </application>

</manifest>
</code>```

Login.java

```<code>package com.example.littledev.test_v2;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

public class Login extends AppCompatActivity {

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

    public void onLoginSuccess() {
        startActivity(new Intent(this, Main.class));
    }

    public void onLogin(View view){
        EditText eLogin = (EditText) findViewById(R.id.username);
        EditText ePass = (EditText) findViewById(R.id.password);
        String login = eLogin.getText().toString();
        String pass = ePass.getText().toString();
        Sql_bridge bridge = new Sql_bridge(this);
        bridge.execute("login",login,pass);
        finish();
    }

    public void onRegister(View view) {
        //startActivity(new Intent(this, Register.class));
    }
}
</code>```

Sql_bridge.java

```<code>package com.example.littledev.test_v2;

import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by LittleDev on 3/30/2017.
 */

public class Sql_bridge extends AsyncTask<String,Void,String> {
    private Context ctx;
    Sql_bridge (Context ctx)
    {
        this.ctx =ctx;
    }
    @Override
    protected void onPreExecute() {
        AlertDialog alertDialog;
        alertDialog = new AlertDialog.Builder(ctx).create();
        alertDialog.setTitle("Main Information....");
    }

    @Override
    protected String doInBackground(String... params) {
        String reg_url = "http://e-shops.hol.es/app_register";
        String log_url = "http://e-shops.hol.es/app_login";
        String method = params[0];
        if (method.equals("register")) {
            String name = params[1];
            String surname = params[2];
            String email = params[3];
            String password = params[4];
            try {
                URL url = new URL(reg_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream OS = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
                String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
                        URLEncoder.encode("surname", "UTF-8") + "=" + URLEncoder.encode(surname, "UTF-8") + "&" +
                        URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8") + "&" +
                        URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                OS.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String response = "";
                String line;
                while ((line = bufferedReader.readLine())!=null)
                {
                    response+= line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return response;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if (method.equals("login")){
            String login_name = params[1];
            String login_pass = params[2];
            try {
                URL url = new URL(log_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
                String data = URLEncoder.encode("login","UTF-8")+"="+URLEncoder.encode(login_name,"UTF-8")+"&"+
                        URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(login_pass,"UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String response = "";
                String line;
                while ((line = bufferedReader.readLine())!=null)
                {
                    response+= line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return response;

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        Login login = new Login();
        switch (result) {
            case "Registered":
                Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
                break;
            case "Login":
                Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
                login.onLoginSuccess();

                break;
            default:
                Toast.makeText(ctx, "Failed", Toast.LENGTH_LONG).show();
                break;
        }

    }
}
</code>```

Logcat

```<code>03-30 15:11:48.323 9997-9997/com.example.littledev.test_v2 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.littledev.test_v2, PID: 9997
                                                                             java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
                                                                                at android.app.Activity.startActivityForResult(Activity.java:4298)
                                                                                at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
                                                                                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:4245)
                                                                                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
                                                                                at android.app.Activity.startActivity(Activity.java:4582)
                                                                                at android.app.Activity.startActivity(Activity.java:4550)
                                                                                at com.example.littledev.test_v2.Login.onLoginSuccess(Login.java:19)
                                                                                at com.example.littledev.test_v2.Sql_bridge.onPostExecute(Sql_bridge.java:131)
                                                                                at com.example.littledev.test_v2.Sql_bridge.onPostExecute(Sql_bridge.java:23)
                                                                                at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                                                at android.os.AsyncTask.access$500(AsyncTask.java:180)
                                                                                at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7329)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
</code>```

I realy don`t have a clue why it crashes.

答:
You can't new an Activity.

```<code>package com.example.littledev.test_v2;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class Sql_bridge extends AsyncTask<String,Void,String> {
private Activity ctx;
Sql_bridge (Activity ctx)
{
    this.ctx =ctx;
}

@Override
protected void onPostExecute(String result) {

    switch (result) {
        case "Registered":
            Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
            break;
        case "Login":
            Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
            if(ctx instanceof Login){
                ((Login)ctx).onLoginSuccess();
            }
            break;
        default:
            Toast.makeText(ctx, "Failed", Toast.LENGTH_LONG).show();
            break;
    }

}
}
</code>```

and remove finish():

```<code>public void onLogin(View view){
    EditText eLogin = (EditText) findViewById(R.id.username);
    EditText ePass = (EditText) findViewById(R.id.password);
    String login = eLogin.getText().toString();
    String pass = ePass.getText().toString();
    Sql_bridge bridge = new Sql_bridge(this);
    bridge.execute("login",login,pass);
}
</code>```

and invoke finish on login success:

```<code>public void onLoginSuccess() {
    startActivity(new Intent(this, Main.class));
    finish();
}
</code>```

Body:
My app receives data from the database for authorization and registration.When startActivity(new Intent(this, Main.class));
line is commented out the app just minimize, and when uncommented it crashes.

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.littledev.test_v2">
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".Login">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Main">

        </activity>
    </application>

</manifest>

Login.java

package com.example.littledev.test_v2;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

public class Login extends AppCompatActivity {

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

    public void onLoginSuccess() {
        startActivity(new Intent(this, Main.class));
    }

    public void onLogin(View view){
        EditText eLogin = (EditText) findViewById(R.id.username);
        EditText ePass = (EditText) findViewById(R.id.password);
        String login = eLogin.getText().toString();
        String pass = ePass.getText().toString();
        Sql_bridge bridge = new Sql_bridge(this);
        bridge.execute("login",login,pass);
        finish();
    }

    public void onRegister(View view) {
        //startActivity(new Intent(this, Register.class));
    }
}

Sql_bridge.java

package com.example.littledev.test_v2;

import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by LittleDev on 3/30/2017.
 */

public class Sql_bridge extends AsyncTask<String,Void,String> {
    private Context ctx;
    Sql_bridge (Context ctx)
    {
        this.ctx =ctx;
    }
    @Override
    protected void onPreExecute() {
        AlertDialog alertDialog;
        alertDialog = new AlertDialog.Builder(ctx).create();
        alertDialog.setTitle("Main Information....");
    }

    @Override
    protected String doInBackground(String... params) {
        String reg_url = "http://e-shops.hol.es/app_register";
        String log_url = "http://e-shops.hol.es/app_login";
        String method = params[0];
        if (method.equals("register")) {
            String name = params[1];
            String surname = params[2];
            String email = params[3];
            String password = params[4];
            try {
                URL url = new URL(reg_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream OS = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
                String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
                        URLEncoder.encode("surname", "UTF-8") + "=" + URLEncoder.encode(surname, "UTF-8") + "&" +
                        URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8") + "&" +
                        URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                OS.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String response = "";
                String line;
                while ((line = bufferedReader.readLine())!=null)
                {
                    response+= line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return response;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if (method.equals("login")){
            String login_name = params[1];
            String login_pass = params[2];
            try {
                URL url = new URL(log_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
                String data = URLEncoder.encode("login","UTF-8")+"="+URLEncoder.encode(login_name,"UTF-8")+"&"+
                        URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(login_pass,"UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String response = "";
                String line;
                while ((line = bufferedReader.readLine())!=null)
                {
                    response+= line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return response;

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        Login login = new Login();
        switch (result) {
            case "Registered":
                Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
                break;
            case "Login":
                Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
                login.onLoginSuccess();

                break;
            default:
                Toast.makeText(ctx, "Failed", Toast.LENGTH_LONG).show();
                break;
        }

    }
}

Logcat

03-30 15:11:48.323 9997-9997/com.example.littledev.test_v2 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.littledev.test_v2, PID: 9997
                                                                             java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
                                                                                at android.app.Activity.startActivityForResult(Activity.java:4298)
                                                                                at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
                                                                                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:4245)
                                                                                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
                                                                                at android.app.Activity.startActivity(Activity.java:4582)
                                                                                at android.app.Activity.startActivity(Activity.java:4550)
                                                                                at com.example.littledev.test_v2.Login.onLoginSuccess(Login.java:19)
                                                                                at com.example.littledev.test_v2.Sql_bridge.onPostExecute(Sql_bridge.java:131)
                                                                                at com.example.littledev.test_v2.Sql_bridge.onPostExecute(Sql_bridge.java:23)
                                                                                at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                                                at android.os.AsyncTask.access$500(AsyncTask.java:180)
                                                                                at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7329)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

I realy don`t have a clue why it crashes.

Body:
You can't new an Activity.

package com.example.littledev.test_v2;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class Sql_bridge extends AsyncTask<String,Void,String> {
private Activity ctx;
Sql_bridge (Activity ctx)
{
    this.ctx =ctx;
}

@Override
protected void onPostExecute(String result) {

    switch (result) {
        case "Registered":
            Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
            break;
        case "Login":
            Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
            if(ctx instanceof Login){
                ((Login)ctx).onLoginSuccess();
            }
            break;
        default:
            Toast.makeText(ctx, "Failed", Toast.LENGTH_LONG).show();
            break;
    }

}
}

and remove finish():

public void onLogin(View view){
    EditText eLogin = (EditText) findViewById(R.id.username);
    EditText ePass = (EditText) findViewById(R.id.password);
    String login = eLogin.getText().toString();
    String pass = ePass.getText().toString();
    Sql_bridge bridge = new Sql_bridge(this);
    bridge.execute("login",login,pass);
}

and invoke finish on login success:

public void onLoginSuccess() {
    startActivity(new Intent(this, Main.class));
    finish();
}


答:
```<code>$keyNameMap = [
   1=>'white',
   2=>'black'
];

// some codes
foreach ($urlImages as $key => $name) {
    $nameImg = $id_product.'_'.$keyNameMap[$key].'_'.md5(uniqid(rand(), true)).'.png';
    // come codes
}
</code>```

Title: Convert value number key to string php?


问:
Draw common friends connections of three people using networkx
I have three people (with option of adding more people) and I want to show each person friends list as a circle. So, 1 circle per person. Next, I want to add edges(connections) if two people have same friend.

```<code>Mike_friends = ['Al', 'Niki', 'Silvia', 'Anna', 'Matt', 'Gia', 'Nick', 'Maud', 'Sarah', 'Lisa', 'Kelvin']
Alex_friends = ['Harvey', 'Steve', 'Michael', 'Maud', 'Al', 'Kam', 'Hank']
Stephen_friends = ['Lisa','Rosie','Mango','Kate','Nate','Maud','Kelvin','Elvis','Arstad','Jesus','Johan','Jay','Gia','Niki','Harvey','Paul','Mike','Alex','Anna']
import networkx as nx
import matplotlib.pyplot as plt

def link_networks(N1, N2, N3, N4=None, N5=None, N6=None, N7=None, N8=None, N9=None):
    G = nx.Graph()
    for item1 in N1:
        for item2 in N2:
            for item3 in N3:
                if item1 in N1 == item2 in N2:
                    G.add_edge(item1, item2)
                elif item1 in N1 == item3 in N3:
                    G.add_edge(item1, item3)
                elif item2 in N2 == item3 in N3:
                    G.add_edge(item2, item3)
link_networks(Mike_friends, Alex_friends, Stephen_friends)
plt.figure(figsize = (20, 10))
mytitle = "friend circle connections"
plt.title(mytitle, fontsize=40)
nx.draw_networkx(G, font_size=10, node_size=2000, alpha=0.6)
plt.savefig("friend_circles.pdf")
</code>```

The problem: I get empty figure, 3 circles with connections do not show up. Thanks for help. Removed 'Return G'.

答:
Here is one way of doing it. First you find how many common friends have Mike, Alex and Stephen. I do this by using set; here's the example for Mike and Alex.

```<code>M_A_common = len(set(Mike_friends) & set(Alex_friends))
</code>```

The nodes in my graph are called Mike, Alex and Stephen. Below I set the edge Mike -- Alex so it has the value of M_A_common.

```<code>G.add_edge('Mike', 'Alex', common_friends=M_A_common)
</code>```

Here is the full example with all friends where I draw the network with nx.draw and the edge labels with nx.draw_networkx_edge_labels.

```<code>import networkx as nx
import matplotlib.pyplot as plt

Mike_friends = ['Al', 'Niki', 'Silvia', 'Anna', 'Matt', 'Gia', 'Nick', 'Maud', 'Sarah', 'Lisa', 'Kelvin']
Alex_friends = ['Harvey', 'Steve', 'Michael', 'Maud', 'Al', 'Kam', 'Hank']
Stephen_friends = ['Lisa','Rosie','Mango','Kate','Nate','Maud','Kelvin','Elvis','Arstad','Jesus','Johan','Jay','Gia','Niki','Harvey','Paul','Mike','Alex','Anna']

G = nx.Graph()
G.add_node('Mike')
G.add_node('Alex')
G.add_node('Stephen')

M_A_common = len(set(Mike_friends) & set(Alex_friends))  # number of common friends
M_S_common = len(set(Mike_friends) & set(Stephen_friends))  # number of common friends
S_A_common = len(set(Stephen_friends) & set(Alex_friends))  # number of common friends

G.add_edge('Mike', 'Alex', common_friends=M_A_common)
G.add_edge('Mike', 'Stephen', common_friends=M_S_common)
G.add_edge('Stephen', 'Alex', common_friends=S_A_common)

pos = nx.circular_layout(G)
nx.draw(G, pos, node_size=2000, with_labels=True)
edge_labels = nx.get_edge_attributes(G, 'common_friends')
nx.draw_networkx_edge_labels(G, pos, labels=edge_labels)
plt.show()
</code>```

Instead of writing the number of common friends you could e.g. show the amount of common friends with edge thickness.

Of course, with more friends you will have more combinations so you'll probably want to automate the calculation of common friends.

Also, if you want multiple edges for each common friend you need to use MultiGraph instead of Graph. For drawing multiple edges take a look here.

EDIT:

To add custom node labels (e.g. node name + number of total friends) for the code above you could use nx.draw_networkx_labels like this:

```<code>pos = nx.circular_layout(G)
nx.draw(G, pos, node_size=2000, with_labels=False)
node_labels = {
    'Mike': 'Mike (' + str(len(Mike_friends)) + ' total)',
    'Alex': 'Alex (' + str(len(Alex_friends)) + ' total)',
    'Stephen': 'Stephen (' + str(len(Stephen_friends)) + ' total)'
}
nx.draw_networkx_labels(G, pos, labels=node_labels)
edge_labels = nx.get_edge_attributes(G, 'common_friends')
nx.draw_networkx_edge_labels(G, pos, labels=edge_labels)
plt.show()
</code>```

If you had 20 friends the code above would get really messy. Below is a more elegant approach where I store the nodes and their friends in a dictionary called friends.

To get all possible edges I use itertools.combinations

```<code>import networkx as nx
import matplotlib.pyplot as plt
from itertools import combinations

G = nx.Graph()
friends = {
    'Mike': ['Al', 'Niki', 'Silvia', 'Anna', 'Matt', 'Gia', 'Nick', 'Maud', 'Sarah', 'Lisa', 'Kelvin'],
    'Alex': ['Harvey', 'Steve', 'Michael', 'Maud', 'Al', 'Kam', 'Hank'],
    'Stephen': ['Lisa','Rosie','Mango','Kate','Nate','Maud','Kelvin','Elvis','Arstad','Jesus','Johan','Jay','Gia','Niki','Harvey','Paul','Mike','Alex','Anna']
}

persons = list(friends.keys())  # Mike, Alex, Stephen
G.add_nodes_from(persons)
combos = list(combinations(persons, 2))  # all 2-combinations of `persons`

for edge in combos:
    node_1, node_2 = edge[0], edge[1]
    common = len(set(friends[node_1]) & set(friends[node_2]))  # number of common friends
    G.add_edge(node_1, node_2, common_friends=common)

node_labels = {person: person + ' (' + str(len(friends[person])) + ' total)' for person in persons}
edge_labels = nx.get_edge_attributes(G, 'common_friends')

pos = nx.circular_layout(G)
nx.draw(G, pos, node_size=2000, with_labels=False)
nx.draw_networkx_labels(G, pos, labels=node_labels)
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
plt.show()
</code>```

Output:

EDIT 2:

I corrected a line in my code that now gives different edge labels (only values without keys for edge_labels).

Body:
I have three people (with option of adding more people) and I want to show each person friends list as a circle. So, 1 circle per person. Next, I want to add edges(connections) if two people have same friend.

Mike_friends = ['Al', 'Niki', 'Silvia', 'Anna', 'Matt', 'Gia', 'Nick', 'Maud', 'Sarah', 'Lisa', 'Kelvin']
Alex_friends = ['Harvey', 'Steve', 'Michael', 'Maud', 'Al', 'Kam', 'Hank']
Stephen_friends = ['Lisa','Rosie','Mango','Kate','Nate','Maud','Kelvin','Elvis','Arstad','Jesus','Johan','Jay','Gia','Niki','Harvey','Paul','Mike','Alex','Anna']
import networkx as nx
import matplotlib.pyplot as plt

def link_networks(N1, N2, N3, N4=None, N5=None, N6=None, N7=None, N8=None, N9=None):
    G = nx.Graph()
    for item1 in N1:
        for item2 in N2:
            for item3 in N3:
                if item1 in N1 == item2 in N2:
                    G.add_edge(item1, item2)
                elif item1 in N1 == item3 in N3:
                    G.add_edge(item1, item3)
                elif item2 in N2 == item3 in N3:
                    G.add_edge(item2, item3)
link_networks(Mike_friends, Alex_friends, Stephen_friends)
plt.figure(figsize = (20, 10))
mytitle = "friend circle connections"
plt.title(mytitle, fontsize=40)
nx.draw_networkx(G, font_size=10, node_size=2000, alpha=0.6)
plt.savefig("friend_circles.pdf")

The problem: I get empty figure, 3 circles with connections do not show up. Thanks for help. Removed 'Return G'.

Body:
Here is one way of doing it. First you find how many common friends have Mike, Alex and Stephen. I do this by using set; here's the example for Mike and Alex.

M_A_common = len(set(Mike_friends) & set(Alex_friends))

The nodes in my graph are called Mike, Alex and Stephen. Below I set the edge Mike -- Alex so it has the value of M_A_common.

G.add_edge('Mike', 'Alex', common_friends=M_A_common)

Here is the full example with all friends where I draw the network with nx.draw and the edge labels with nx.draw_networkx_edge_labels.

import networkx as nx
import matplotlib.pyplot as plt

Mike_friends = ['Al', 'Niki', 'Silvia', 'Anna', 'Matt', 'Gia', 'Nick', 'Maud', 'Sarah', 'Lisa', 'Kelvin']
Alex_friends = ['Harvey', 'Steve', 'Michael', 'Maud', 'Al', 'Kam', 'Hank']
Stephen_friends = ['Lisa','Rosie','Mango','Kate','Nate','Maud','Kelvin','Elvis','Arstad','Jesus','Johan','Jay','Gia','Niki','Harvey','Paul','Mike','Alex','Anna']

G = nx.Graph()
G.add_node('Mike')
G.add_node('Alex')
G.add_node('Stephen')

M_A_common = len(set(Mike_friends) & set(Alex_friends))  # number of common friends
M_S_common = len(set(Mike_friends) & set(Stephen_friends))  # number of common friends
S_A_common = len(set(Stephen_friends) & set(Alex_friends))  # number of common friends

G.add_edge('Mike', 'Alex', common_friends=M_A_common)
G.add_edge('Mike', 'Stephen', common_friends=M_S_common)
G.add_edge('Stephen', 'Alex', common_friends=S_A_common)

pos = nx.circular_layout(G)
nx.draw(G, pos, node_size=2000, with_labels=True)
edge_labels = nx.get_edge_attributes(G, 'common_friends')
nx.draw_networkx_edge_labels(G, pos, labels=edge_labels)
plt.show()

Instead of writing the number of common friends you could e.g. show the amount of common friends with edge thickness.

Of course, with more friends you will have more combinations so you'll probably want to automate the calculation of common friends.

Also, if you want multiple edges for each common friend you need to use MultiGraph instead of Graph. For drawing multiple edges take a look here.

EDIT:

To add custom node labels (e.g. node name + number of total friends) for the code above you could use nx.draw_networkx_labels like this:

pos = nx.circular_layout(G)
nx.draw(G, pos, node_size=2000, with_labels=False)
node_labels = {
    'Mike': 'Mike (' + str(len(Mike_friends)) + ' total)',
    'Alex': 'Alex (' + str(len(Alex_friends)) + ' total)',
    'Stephen': 'Stephen (' + str(len(Stephen_friends)) + ' total)'
}
nx.draw_networkx_labels(G, pos, labels=node_labels)
edge_labels = nx.get_edge_attributes(G, 'common_friends')
nx.draw_networkx_edge_labels(G, pos, labels=edge_labels)
plt.show()

If you had 20 friends the code above would get really messy. Below is a more elegant approach where I store the nodes and their friends in a dictionary called friends.

To get all possible edges I use itertools.combinations

import networkx as nx
import matplotlib.pyplot as plt
from itertools import combinations

G = nx.Graph()
friends = {
    'Mike': ['Al', 'Niki', 'Silvia', 'Anna', 'Matt', 'Gia', 'Nick', 'Maud', 'Sarah', 'Lisa', 'Kelvin'],
    'Alex': ['Harvey', 'Steve', 'Michael', 'Maud', 'Al', 'Kam', 'Hank'],
    'Stephen': ['Lisa','Rosie','Mango','Kate','Nate','Maud','Kelvin','Elvis','Arstad','Jesus','Johan','Jay','Gia','Niki','Harvey','Paul','Mike','Alex','Anna']
}

persons = list(friends.keys())  # Mike, Alex, Stephen
G.add_nodes_from(persons)
combos = list(combinations(persons, 2))  # all 2-combinations of `persons`

for edge in combos:
    node_1, node_2 = edge[0], edge[1]
    common = len(set(friends[node_1]) & set(friends[node_2]))  # number of common friends
    G.add_edge(node_1, node_2, common_friends=common)

node_labels = {person: person + ' (' + str(len(friends[person])) + ' total)' for person in persons}
edge_labels = nx.get_edge_attributes(G, 'common_friends')

pos = nx.circular_layout(G)
nx.draw(G, pos, node_size=2000, with_labels=False)
nx.draw_networkx_labels(G, pos, labels=node_labels)
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
plt.show()

Output:

EDIT 2:

I corrected a line in my code that now gives different edge labels (only values without keys for edge_labels).


答:
Have you tested case sensitivity? Javascript is case sensitive so you might have to use

```<code>console.log(body.USD);
</code>```

tested it with some of my json objects and it seems to work like that

Title: Nodejs returns the full JSON of the Blockchain Rates API but I can't access particular objects inside it. Why?

Body:
I have a file that makes a request to blockchain.info/ticker API in order to pull the latest price of bitcoin.

script.js:

let request = require('request');
let url = "https://blockchain.info/ticker"

request.get(url,
function(error, response, body) {
    console.log(body); //first
    console.log(body.USD); //second
});

The first console.log statement inside the request.get returns:

{
  "USD" : {"15m" : 1034.99, "last" : 1034.99, "buy" : 1033.63, "sell" : 1034.99,  "symbol" : "$"},
  "ISK" : {"15m" : 116090.37, "last" : 116090.37, "buy" : 115937.82, "sell" : 116090.37,  "symbol" : "kr"},
  "HKD" : {"15m" : 8043.46, "last" : 8043.46, "buy" : 8032.89, "sell" : 8043.46,  "symbol" : "$"},
  "TWD" : {"15m" : 31374.69, "last" : 31374.69, "buy" : 31333.46, "sell" : 31374.69,  "symbol" : "NT$"},
  "CHF" : {"15m" : 1030.89, "last" : 1030.89, "buy" : 1029.53, "sell" : 1030.89,  "symbol" : "CHF"},
  "EUR" : {"15m" : 963.89, "last" : 963.89, "buy" : 962.63, "sell" : 963.89,  "symbol" : "€"},
  "DKK" : {"15m" : 7170.6, "last" : 7170.6, "buy" : 7161.17, "sell" : 7170.6,  "symbol" : "kr"},
  "CLP" : {"15m" : 685784.37, "last" : 685784.37, "buy" : 684883.24, "sell" : 685784.37,  "symbol" : "$"},
  "CAD" : {"15m" : 1380.41, "last" : 1380.41, "buy" : 1378.6, "sell" : 1380.41,  "symbol" : "$"},
  "CNY" : {"15m" : 7131.48, "last" : 7131.48, "buy" : 7122.11, "sell" : 7131.48,  "symbol" : "¥"},
  "THB" : {"15m" : 35634.71, "last" : 35634.71, "buy" : 35587.88, "sell" : 35634.71,  "symbol" : "฿"},
  "AUD" : {"15m" : 1349.36, "last" : 1349.36, "buy" : 1347.58, "sell" : 1349.36,  "symbol" : "$"},
  "SGD" : {"15m" : 1443.9, "last" : 1443.9, "buy" : 1442.01, "sell" : 1443.9,  "symbol" : "$"},
  "KRW" : {"15m" : 1155773.33, "last" : 1155773.33, "buy" : 1154254.62, "sell" : 1155773.33,  "symbol" : "₩"},
  "JPY" : {"15m" : 115110.38, "last" : 115110.38, "buy" : 114959.12, "sell" : 115110.38,  "symbol" : "¥"},
  "PLN" : {"15m" : 4072.84, "last" : 4072.84, "buy" : 4067.49, "sell" : 4072.84,  "symbol" : "zł"},
  "GBP" : {"15m" : 832.11, "last" : 832.11, "buy" : 831.01, "sell" : 832.11,  "symbol" : "£"},
  "SEK" : {"15m" : 9212.32, "last" : 9212.32, "buy" : 9200.21, "sell" : 9212.32,  "symbol" : "kr"},
  "NZD" : {"15m" : 1474.6, "last" : 1474.6, "buy" : 1472.66, "sell" : 1474.6,  "symbol" : "$"},
  "BRL" : {"15m" : 3232.68, "last" : 3232.68, "buy" : 3228.43, "sell" : 3232.68,  "symbol" : "R$"},
  "RUB" : {"15m" : 58287.38, "last" : 58287.38, "buy" : 58210.79, "sell" : 58287.38,  "symbol" : "RUB"}

}

The second console.log statement returns:

undefined

What have I tried:
I have tried to assign the same output that I get in the terminal to a variable in a chrome inspector and access different objects just to test out if my syntax is correct. Syntax is correct so, I'm really puzzled.

Why is my second console.log statement undefined and how can I fix this in order to get the "15m" price inside of the USD object?

Body:
Have you tested case sensitivity? Javascript is case sensitive so you might have to use

console.log(body.USD);

tested it with some of my json objects and it seems to work like that


问:
Github Pages Pushing Error
I'm using Github Pages to build my portfolio webpage. I've already built part of the website(it is online) and I get an error every time I try to update it.

The main HTML file for the webpage is named index.html. I am trying to add buttons to the website, so I added the buttons in my index.html file and saved it. Then I perform the following commands in my terminal (In the repository, of course):

```<code>git add index.html
git commit -m "Adding buttons"
git push origin master
</code>```

Then I have to enter my username and password. I get the following error:

```<code> To https://mywebsiteurl
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://mywebsiteurl'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
</code>```

How do I solve this error and push the changes to my repo?

答:
You need to do a pull.

You or someone who has access to your repo pushed some changes which you don't have on your local version. Try following,

git pull origin master

It might be possible, you may find some CONFLICTS, just search for <<<< in file specified as conflicted. Read here more on How to resolve merge conflicts in Git?

Title: Github Pages Pushing Error

Body:
I'm using Github Pages to build my portfolio webpage. I've already built part of the website(it is online) and I get an error every time I try to update it.

The main HTML file for the webpage is named index.html. I am trying to add buttons to the website, so I added the buttons in my index.html file and saved it. Then I perform the following commands in my terminal (In the repository, of course):

git add index.html
git commit -m "Adding buttons"
git push origin master

Then I have to enter my username and password. I get the following error:

 To https://mywebsiteurl
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://mywebsiteurl'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

How do I solve this error and push the changes to my repo?


问:
Button aligned to bottom of RelativeLayout is cut off
I have a button in my RelativeLayout that is being cut off when I use android:layout_alignParentBottom="true" but nothing else I try is working correctly either. Any ideas?

Here is my layout:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.cdar.sab.cdar.MainActivity$PlaceholderFragment">

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/diagnostics_title" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:layout_below="@+id/section_label"
        android:layout_alignParentStart="true"
        android:layout_marginTop="42dp"
        android:hint="@string/email_hint"
        android:id="@+id/emailTB" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:layout_below="@+id/emailTB"
        android:layout_alignParentStart="true"
        android:layout_marginTop="45dp"
        android:hint="@string/message_hint"
        android:maxLines="10"
        android:id="@+id/messageTB" />

    <Button
        android:text="Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_alignParentBottom="true" />

</RelativeLayout>
</code>```

答:
Hope this will help:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.cdar.sab.cdar.MainActivity$PlaceholderFragment">

<RelativeLayout
    android:id="@+id/rlContainer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/diagnostics_title" />

    <EditText
        android:id="@+id/emailTB"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/section_label"
        android:layout_marginTop="42dp"
        android:ems="10"
        android:hint="@string/email_hint"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/messageTB"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/emailTB"
        android:layout_marginTop="45dp"
        android:ems="10"
        android:hint="@string/message_hint"
        android:inputType="textMultiLine"
        android:maxLines="10" />

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/rlContainer">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="Button" />
</RelativeLayout>
</code>```

Body:
I have a button in my RelativeLayout that is being cut off when I use android:layout_alignParentBottom="true" but nothing else I try is working correctly either. Any ideas?

Here is my layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.cdar.sab.cdar.MainActivity$PlaceholderFragment">

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/diagnostics_title" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:layout_below="@+id/section_label"
        android:layout_alignParentStart="true"
        android:layout_marginTop="42dp"
        android:hint="@string/email_hint"
        android:id="@+id/emailTB" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:layout_below="@+id/emailTB"
        android:layout_alignParentStart="true"
        android:layout_marginTop="45dp"
        android:hint="@string/message_hint"
        android:maxLines="10"
        android:id="@+id/messageTB" />

    <Button
        android:text="Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_alignParentBottom="true" />

</RelativeLayout>

Body:
Hope this will help:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.cdar.sab.cdar.MainActivity$PlaceholderFragment">

<RelativeLayout
    android:id="@+id/rlContainer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/diagnostics_title" />

    <EditText
        android:id="@+id/emailTB"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/section_label"
        android:layout_marginTop="42dp"
        android:ems="10"
        android:hint="@string/email_hint"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/messageTB"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/emailTB"
        android:layout_marginTop="45dp"
        android:ems="10"
        android:hint="@string/message_hint"
        android:inputType="textMultiLine"
        android:maxLines="10" />

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/rlContainer">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="Button" />
</RelativeLayout>


问:
Which is the best method to perform string concatenation in PHP?
In php we can append strings in many ways.

```<code>            Method 1
            ----------------------------
            $sql  = "SELECT field1, ";
            $sql .= "       field2, ";
            $sql .= "       field3, ";
            $sql .= "       field4, ";
            $sql .= "FROM   table1 ";
            $sql .= "WHERE  condition1 = '".$value."' " ;

            Method 2
            ----------------------------
            $sql  = 'SELECT field1, ';
            $sql .= '       field2, ';
            $sql .= '       field3, ';
            $sql .= '       field4, ';
            $sql .= 'FROM   table1 ';
            $sql .= 'WHERE  condition1 = "'.$value.'" ' ;

            Method 3
            ----------------------------
            $sql  = 'SELECT field1,
                           field2,
                           field3,
                           field4,
                    FROM   table1
                    WHERE  condition1 = "'.$value.'" ' ;

            Method 4
            ----------------------------
            $str = <<<HEREDOC
                    SELECT field1,
                           field2,
                           field3,
                           field4,
                    FROM   table1
                    WHERE  condition1 = "$value"
            HEREDOC;
</code>```

Which of the above is the best approach? Are there any other methods which will result in better performance?

答: None is better. Just select one and stick to it, PHP_CodeSniffer can be used to automate a check on your code style.</p>

Body:
In php we can append strings in many ways.

            Method 1
            ----------------------------
            $sql  = "SELECT field1, ";
            $sql .= "       field2, ";
            $sql .= "       field3, ";
            $sql .= "       field4, ";
            $sql .= "FROM   table1 ";
            $sql .= "WHERE  condition1 = '".$value."' " ;

            Method 2
            ----------------------------
            $sql  = 'SELECT field1, ';
            $sql .= '       field2, ';
            $sql .= '       field3, ';
            $sql .= '       field4, ';
            $sql .= 'FROM   table1 ';
            $sql .= 'WHERE  condition1 = "'.$value.'" ' ;

            Method 3
            ----------------------------
            $sql  = 'SELECT field1,
                           field2,
                           field3,
                           field4,
                    FROM   table1
                    WHERE  condition1 = "'.$value.'" ' ;

            Method 4
            ----------------------------
            $str = <<<HEREDOC
                    SELECT field1,
                           field2,
                           field3,
                           field4,
                    FROM   table1
                    WHERE  condition1 = "$value"
            HEREDOC;

Which of the above is the best approach? Are there any other methods which will result in better performance?


问:
Why do we need a service in android? Music play can be done by background thread also
I was asked this question in an interview. I am not sure if this the right forum to ask this question because it does not involve any code, but an understanding of android concept.

The question is 'Why do we need a service when everything can be done by a background thread in Android?'
Service runs in the main thread, why do we need something that runs in the main thread but in the background?
Examples like music play can be done in the background thread also so why do we need a service.

Please let me know if this should be asked in another forum.

答:
Service:
Service is like Activity. but it doesn't require UI to work with. whereas when the thread created from the activity , thread will run until the activity lives. so, if you play the music in thread it will run. but it will crash when the activity ends, whereas when you implemented the music playing from service it will run entire the life cycle of the service.

See my answer boundservice to communicate between service and activity. when your music player runs you have to maintain the notification on notification panel.

UPDATE

When you are playing the music with background thread, the music will play even the app closed your background thread will become orphanage thread. You cannot control the state of the music player. Whereas when you are working with service ,music will play and it won't become orphanage service when the app exits. When you recreat the app you can communicate with music player whereas background thread cannot.


问:
Android Studio SQLite Insert Data
I am creating a database and then trying to select some data from it. Below is my DBHelper file which successfully creates the database and tries to insert data into it:

```<code> package com.racecoursedatatechnologies.rdtstockmanagement;

 import android.content.Context;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;
 import android.content.ContentValues;
 import android.util.Log;

 public class DBHelper  extends SQLiteOpenHelper {

//Version number
private static final int DATABASE_VERSION = 4;

//Database Name
private static final String DATABASE_NAME = "rdt.db";

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

    //All tables are created here
    String CREATE_TABLE_USERS = "CREATE TABLE IF NOT EXISTS " + dbTables.userTABLE + "("
            + dbTables.uID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
            + dbTables.username + " TEXT, "
            + dbTables.userpassword + " TEXT );";

    String CREATE_TABLE_STOCK = "CREATE TABLE IF NOT EXISTS " + dbTables.stockTABLE + "("
            + dbTables.sID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
            + dbTables.itemname + " TEXT, "
            + dbTables.itemdescription + " TEXT, "
            + dbTables.itemamount + " INTEGER, "
            + dbTables.itemimage + " TEXT );";

    //Create tables using execute function
    db.execSQL(CREATE_TABLE_USERS);
    db.execSQL(CREATE_TABLE_STOCK);

    //Now add our first user automatically which is the administrator.
    ContentValues contentValues = new ContentValues();
    contentValues.put(dbTables.username, "Administrator");
    contentValues.put(dbTables.userpassword, "abc123");
    db.insert(dbTables.userTABLE, null, contentValues);
    db.close();
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    //Drop older table if existed, all data will be gone
    db.execSQL("DROP TABLE IF EXISTS " + dbTables.userTABLE);
    db.execSQL("DROP TABLE IF EXISTS " + dbTables.stockTABLE);

    //Create tables again
    onCreate(db);

}

 }
</code>```

I am then trying to select the uID column that I have inserted into the database table to see if the user exists with the name and password and can login using the following code:

```<code>//Attempt the user login
public void attemptLogin(View v)
{

    EditText et1 = (EditText)findViewById(R.id.txtUsername);
    EditText et2 = (EditText)findViewById(R.id.txtPassword);

    String input_name = et1.getText().toString();
    String input_password = et2.getText().toString();
    dbhelper = new DBHelper(this);
    SQLiteDatabase db = dbhelper.getReadableDatabase();

  String selectQuery = "SELECT " +
            dbTables.uID +
            " FROM " + dbTables.userTABLE +
            " WHERE " + dbTables.username +
            " = " + "'" + input_name + "'" + " AND " +
            dbTables.userpassword + " = " + "'" + input_password + "'";

    Cursor c = db.rawQuery(selectQuery, null);

    if(c.moveToFirst()){

        Integer userID = c.getInt(0);

        Log.d("DATABASE", userID.toString());

    }

    c.close();
    db.close();
</code>```

However the application keeps crashing out when I press the button saying it cannot find the Column 'Administrator' but I am inserting the data upon creating the database??

答:
Surround string values with '' or the database thinks your value is a command.

String selectQuery = "SELECT * FROM Users WHERE username='" + input_name + "'";

Title: Android Studio SQLite Insert Data

Body:
I am creating a database and then trying to select some data from it. Below is my DBHelper file which successfully creates the database and tries to insert data into it:

 package com.racecoursedatatechnologies.rdtstockmanagement;

 import android.content.Context;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;
 import android.content.ContentValues;
 import android.util.Log;

 public class DBHelper  extends SQLiteOpenHelper {

//Version number
private static final int DATABASE_VERSION = 4;

//Database Name
private static final String DATABASE_NAME = "rdt.db";

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

    //All tables are created here
    String CREATE_TABLE_USERS = "CREATE TABLE IF NOT EXISTS " + dbTables.userTABLE + "("
            + dbTables.uID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
            + dbTables.username + " TEXT, "
            + dbTables.userpassword + " TEXT );";

    String CREATE_TABLE_STOCK = "CREATE TABLE IF NOT EXISTS " + dbTables.stockTABLE + "("
            + dbTables.sID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
            + dbTables.itemname + " TEXT, "
            + dbTables.itemdescription + " TEXT, "
            + dbTables.itemamount + " INTEGER, "
            + dbTables.itemimage + " TEXT );";

    //Create tables using execute function
    db.execSQL(CREATE_TABLE_USERS);
    db.execSQL(CREATE_TABLE_STOCK);

    //Now add our first user automatically which is the administrator.
    ContentValues contentValues = new ContentValues();
    contentValues.put(dbTables.username, "Administrator");
    contentValues.put(dbTables.userpassword, "abc123");
    db.insert(dbTables.userTABLE, null, contentValues);
    db.close();
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    //Drop older table if existed, all data will be gone
    db.execSQL("DROP TABLE IF EXISTS " + dbTables.userTABLE);
    db.execSQL("DROP TABLE IF EXISTS " + dbTables.stockTABLE);

    //Create tables again
    onCreate(db);

}

 }

I am then trying to select the uID column that I have inserted into the database table to see if the user exists with the name and password and can login using the following code:

//Attempt the user login
public void attemptLogin(View v)
{

    EditText et1 = (EditText)findViewById(R.id.txtUsername);
    EditText et2 = (EditText)findViewById(R.id.txtPassword);

    String input_name = et1.getText().toString();
    String input_password = et2.getText().toString();
    dbhelper = new DBHelper(this);
    SQLiteDatabase db = dbhelper.getReadableDatabase();

  String selectQuery = "SELECT " +
            dbTables.uID +
            " FROM " + dbTables.userTABLE +
            " WHERE " + dbTables.username +
            " = " + "'" + input_name + "'" + " AND " +
            dbTables.userpassword + " = " + "'" + input_password + "'";

    Cursor c = db.rawQuery(selectQuery, null);

    if(c.moveToFirst()){

        Integer userID = c.getInt(0);

        Log.d("DATABASE", userID.toString());

    }

    c.close();
    db.close();

However the application keeps crashing out when I press the button saying it cannot find the Column 'Administrator' but I am inserting the data upon creating the database??