问:
How to cancel all pending alarms
In my app I want to enable the user to delete the alarms that they have set.

Here is how I set the alarms:

```<code>    ArrayList<Long> alarmDates = DateAndTimeAssistant.turnReminderTimesIntoActualDates(reminderHolder);
    alarms = new ArrayList<Alarm>();
    for (long alarmDate : alarmDates) {
        Alarm alarm = new Alarm();
        alarm.setTimeInMiliseconds(alarmDate);
        alarm.setReminderHolderId(reminderHolder);
        alarm.setTitle("title");
        alarm.setDescription("description");
        alarms .add(alarm);
    }
</code>```

Then I insert them into DB and onSuccess, I do this:

```<code>DateAndTimeAssistant.addAlarmsToPushNotificationService(alarms);
</code>```

Here is what happens there:

```<code>for (Alarm alarm : alarms) {
        Calendar alarmCalendar = Calendar.getInstance();
        alarmCalendar.setTimeInMillis(alarm.getTimeInMiliseconds());

        Intent intent = new Intent(context, PushNotificationReceiver.class);
        intent.putExtra("notificationTitle", alarm.getTitle());
        intent.putExtra("notificationText", alarm.getDescription());

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, (int) alarmCalendar.getTimeInMillis(), intent, 0); // The second arg is unique id

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // Service.ALARM_SERVICE
        alarmManager.set(AlarmManager.RTC_WAKEUP, alarmCalendar.getTimeInMillis(), pendingIntent);
    }
</code>```

Now, in a completely different activity from the one that started all this, I want to delete the alarms.

I found the following piece of code in an article :

```<code>        for (long alarmTime : alarms) { // This is the unique ID of the pendingIntent I created earlier
            PendingIntent pIntent = PendingIntent.getBroadcast(a, (int) alarmTime, intent, PendingIntent.FLAG_CANCEL_CURRENT);
</code>```

But I dont know what to pass as "intent" here?

EDIT: Following the first answer I got, I changed the code like so:

```<code>Intent intent = new Intent(context, PushNotificationReceiver.class);

        for (long alarmTime : alarms) { // This is the unique ID of the pendingIntent I created earlier
            PendingIntent pIntent = PendingIntent.getBroadcast(a, (int) alarmTime, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}
</code>```

But alarms still keep going off after the supposed deletion. What else could have gone wrong?
I now realize that I dont do anything with this PendingIntent Im creating. What should I do with it?

EDIT 2:

Now I added an alarm manager and Im passing the pending intents to it, then cancelling them, but still it doesnt work

```<code>        AlarmManager alarmManager = (AlarmManager) a.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(a, PushNotificationReceiver.class);
        for (long alarmTime : alarms) {
            PendingIntent pIntent = PendingIntent.getBroadcast(a, (int) alarmTime, intent, PendingIntent.FLAG_CANCEL_CURRENT);
            // Cancel alarms
            try {
                alarmManager.cancel(pIntent);
            } catch (Exception e) {
               // Cant do anything about it.
            }
        }
</code>```

答:
you can use below method do cancel alarm</p>

```<code> public void cancelAlarm(Context context, int ID) {
        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        // Cancel Alarm using Reminder ID
        mPendingIntent = PendingIntent.getBroadcast(context, ID, new Intent(context, AlarmReceiver.class), 0);
        mAlarmManager.cancel(mPendingIntent);

        // Disable alarm
        ComponentName receiver = new ComponentName(context, BootReceiver.class);
        PackageManager pm = context.getPackageManager();
        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
    }
</code>```

Title: How to cancel all pending alarms

Body:
In my app I want to enable the user to delete the alarms that they have set.

Here is how I set the alarms:

    ArrayList<Long> alarmDates = DateAndTimeAssistant.turnReminderTimesIntoActualDates(reminderHolder);
    alarms = new ArrayList<Alarm>();
    for (long alarmDate : alarmDates) {
        Alarm alarm = new Alarm();
        alarm.setTimeInMiliseconds(alarmDate);
        alarm.setReminderHolderId(reminderHolder);
        alarm.setTitle("title");
        alarm.setDescription("description");
        alarms .add(alarm);
    }

Then I insert them into DB and onSuccess, I do this:

DateAndTimeAssistant.addAlarmsToPushNotificationService(alarms);

Here is what happens there:

for (Alarm alarm : alarms) {
        Calendar alarmCalendar = Calendar.getInstance();
        alarmCalendar.setTimeInMillis(alarm.getTimeInMiliseconds());

        Intent intent = new Intent(context, PushNotificationReceiver.class);
        intent.putExtra("notificationTitle", alarm.getTitle());
        intent.putExtra("notificationText", alarm.getDescription());

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, (int) alarmCalendar.getTimeInMillis(), intent, 0); // The second arg is unique id

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // Service.ALARM_SERVICE
        alarmManager.set(AlarmManager.RTC_WAKEUP, alarmCalendar.getTimeInMillis(), pendingIntent);
    }

Now, in a completely different activity from the one that started all this, I want to delete the alarms.

I found the following piece of code in an article :

        for (long alarmTime : alarms) { // This is the unique ID of the pendingIntent I created earlier
            PendingIntent pIntent = PendingIntent.getBroadcast(a, (int) alarmTime, intent, PendingIntent.FLAG_CANCEL_CURRENT);

But I dont know what to pass as "intent" here?

EDIT: Following the first answer I got, I changed the code like so:

Intent intent = new Intent(context, PushNotificationReceiver.class);

        for (long alarmTime : alarms) { // This is the unique ID of the pendingIntent I created earlier
            PendingIntent pIntent = PendingIntent.getBroadcast(a, (int) alarmTime, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}

But alarms still keep going off after the supposed deletion. What else could have gone wrong?
I now realize that I dont do anything with this PendingIntent Im creating. What should I do with it?

EDIT 2:

Now I added an alarm manager and Im passing the pending intents to it, then cancelling them, but still it doesnt work

        AlarmManager alarmManager = (AlarmManager) a.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(a, PushNotificationReceiver.class);
        for (long alarmTime : alarms) {
            PendingIntent pIntent = PendingIntent.getBroadcast(a, (int) alarmTime, intent, PendingIntent.FLAG_CANCEL_CURRENT);
            // Cancel alarms
            try {
                alarmManager.cancel(pIntent);
            } catch (Exception e) {
               // Cant do anything about it.
            }
        }

Body:
you can use below method do cancel alarm

 public void cancelAlarm(Context context, int ID) {
        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        // Cancel Alarm using Reminder ID
        mPendingIntent = PendingIntent.getBroadcast(context, ID, new Intent(context, AlarmReceiver.class), 0);
        mAlarmManager.cancel(mPendingIntent);

        // Disable alarm
        ComponentName receiver = new ComponentName(context, BootReceiver.class);
        PackageManager pm = context.getPackageManager();
        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
    }


来源: stackexchange

问:
Ionic v2 : FCM open application in background
I build an Ionic 2 and I have to integrate push notification.
First, I try to send my notification with firebase interface :
https://console.firebase.google.com/
All works well.

But now, I want to send notification with a php server. So I found this code :

```<code><?php
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'my-key' );
$registrationIds = array( $_GET['id'] );
// prep the bundle
$msg = array
(
'message'=> 'here is a message. message',
'title'=> 'This is a title. title',
'subtitle'=> 'This is a subtitle. subtitle',
'tickerText'=> 'Ticker text here...Ticker text here...Ticker text here',
'vibrate'=>1,
'sound'=>1,
'largeIcon'=>'large_icon',
'smallIcon'=>'small_icon',
'content-available'=>1
);
$fields = array
('registration_ids'=>$registrationIds,
'data'=>$msg
);

$headers = array
('Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;
?>
</code>```

It works. But when my app is in background (onpause), I received a notification but touch it don't open my app in foreground.
It works well when my app is closed
To resume :

-If my App is close, I received notification. When I touch the notification my app is open.

-If my App is open and in foreground, I received notification.

-If my app is on pause, open but in background, I received notification but touch it doesn't open the app. But I want to.

I don't understand because it works with firebase console...
What I have to do to resolve that ?

My call back code in app.component.ts :

```<code>this.push.rx.notification()
          .subscribe((msg) => {
            console.log('I received awesome push: ' + msg);
          });
</code>```

UPDATE :

When I touch my notification, if my app is "onpause", she goes into forground and back directly into background again. I don't know why and I don't know what I have to do...

答:
In the PHP code, you're sending a data-only message payload, while when using the Firebase Console, the message(s) you sent are considered as a notification message payload (see Message Types).

Try editing your PHP code to send a notification message payload instead. Like so:

```<code> // prep the bundle
$msg = array
(
    'title'=> 'This is a title',
    'body'=> 'This is a body'
);
$fields = array
('registration_ids'=>$registrationIds,
    'notification'=>$msg
);
</code>```

However, do note that notification message payload only have specific parameters available. See the HTTP Protocol Reference as a guide for the parameters.

ContentLicense: CC BY-SA 3.0

Body:
I build an Ionic 2 and I have to integrate push notification.
First, I try to send my notification with firebase interface :
https://console.firebase.google.com/
All works well.

But now, I want to send notification with a php server. So I found this code :

<?php
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'my-key' );
$registrationIds = array( $_GET['id'] );
// prep the bundle
$msg = array
(
'message'=> 'here is a message. message',
'title'=> 'This is a title. title',
'subtitle'=> 'This is a subtitle. subtitle',
'tickerText'=> 'Ticker text here...Ticker text here...Ticker text here',
'vibrate'=>1,
'sound'=>1,
'largeIcon'=>'large_icon',
'smallIcon'=>'small_icon',
'content-available'=>1
);
$fields = array
('registration_ids'=>$registrationIds,
'data'=>$msg
);

$headers = array
('Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;
?>

It works. But when my app is in background (onpause), I received a notification but touch it don't open my app in foreground.
It works well when my app is closed
To resume :

-If my App is close, I received notification. When I touch the notification my app is open.

-If my App is open and in foreground, I received notification.

-If my app is on pause, open but in background, I received notification but touch it doesn't open the app. But I want to.

I don't understand because it works with firebase console...
What I have to do to resolve that ?

My call back code in app.component.ts :

this.push.rx.notification()
          .subscribe((msg) => {
            console.log('I received awesome push: ' + msg);
          });

UPDATE :

When I touch my notification, if my app is "onpause", she goes into forground and back directly into background again. I don't know why and I don't know what I have to do...

Body:
In the PHP code, you're sending a data-only message payload, while when using the Firebase Console, the message(s) you sent are considered as a notification message payload (see Message Types).

Try editing your PHP code to send a notification message payload instead. Like so:

 // prep the bundle
$msg = array
(
    'title'=> 'This is a title',
    'body'=> 'This is a body'
);
$fields = array
('registration_ids'=>$registrationIds,
    'notification'=>$msg
);

However, do note that notification message payload only have specific parameters available. See the HTTP Protocol Reference as a guide for the parameters.


问:
Pass TextInput props between different screens in React Navigation
I am totally lost on how to grab two parameters from a form screen and pass them via React Navigator and display them on the previous screen.

The app section in question works like this:

1. touchablehighlight to form screen.

2. input title and description and press submit onpress

3. the onpress runs a function that dispatches the parameters to the previous page via a key.

4. then returns back to the origin page, with the props on display.

I am having multiple issues with the process:

1. if I am understanding the docs correctly, each page has a unique key and i tried to find it via this.props.navigation.state.key, however unknown to me, on refresh the id number would change.

2. that leads to problem 2 where the function will run, but it will not redirect back to the original page.

3. i have tried .navigate line after .dispatch but it would open a new copy of the original page and not display the new props that supposively were passed down.

import React from 'react';
import styles from '../styling/style.js';
import { Text, View, Image, TouchableHighlight, TextInput, Alert } from 'react-native';
import { StackNavigator, NavigationActions } from 'react-navigation';
import Forms from './formGenerator';

export default class Workout extends React.Component {
constructor(props) {
  super(props);
  this.state = {
     programTitle: '',
     programDescription: ''
  }
}

render() {
  const {navigate} = this.props.navigation;
  return (
    <Image style={styles.workoutContainer, { flex: 1}} source={require("../images/HomepageBackground.jpg")}>
      <View style={styles.workoutBody}>
          <Text style={styles.workoutTextBody}> {this.state.programTitle}</Text>
          <Text style={styles.workoutTextBody}>{this.state.programDescription}</Text>
      </View>
        <View style={styles.createButton}>
        <TouchableHighlight onPress={Alert.alert(this.props.navigation.state.key)} style={styles.addButtonTouch} title='test' >
         <Text style={styles.addButtonText}>+</Text>
        </TouchableHighlight>
        </View>
    </Image>
    );
  }

// End of the render
}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React from 'react';
import styles from '../styling/style.js';
import { Text, View, Image, TouchableHighlight, TextInput, Button, Alert } from 'react-native';
import Workout from './workouts';
import { NavigationActions } from 'react-navigation';

export default class Forms extends React.Component {
constructor(props) {
  super(props);
  this.state = {
     programTitle: '',
     programDescription: ''
  }
}

render() {
  const {goBack} = this.props.navigation;
  const {params} = this.props.navigation.state;
  return (
    <Image style={styles.workoutContainer, { flex: 1}} source={require("../images/HomepageBackground.jpg")}>
      <View style={styles.workoutBody}>
        <Text style={styles.formHeader}>Program Title</Text>
          <TextInput
            autoFocus={true}
            style={styles.formBody}
            onChangeText={(programTitle) => this.setState({programTitle})}
            placeholder='Title'
            value={this.state.programTitle} />
        <Text style={styles.formHeader}>Description (Ex. 4sets x 10reps)</Text>
          <TextInput
            autoFocus={true}
            style={styles.formBody}
            placeholder='Description'
            onChangeText={(programDescription) => this.setState({programDescription})}
            value={this.state.programDescription} />
        <TouchableHighlight onPress={this.addProgram} style={styles.buttonBody} title="Add Program" >
          <Text>Add Program</Text>
        </TouchableHighlight>
      </View>
    </Image>
    );
  }

addProgram = () => {
  Alert.alert(this.props.navigation.state.key);
  this.setState({programTitle: ''});
  this.setState({programDescription: ''});
  const setParamsAction = NavigationActions.setParams({
  params: { programTitle: this.state.programTitle, programDescription: this.state.programDescription },
  key: ,
})
this.props.navigation.dispatch(setParamsAction)
};

}</code>```

答:
You are just trying to display information from the Forms class on the Workout class, correct??

From your Workout class, create a function that update's it's state.

```<code>updateWorkoutState = (programTitle,programDescription) => this.setState(programTitle,programDescription)
</code>```

Pass that function through to the Forms class when you push that route.

```<code> this.props.navigation.navigate('Forms',{updateWorkoutState: this.updateWorkoutState}
</code>```

Once your conditions are met on the Forms class and you want to update the Workout component, call it with this.props.navigation.state.params.updateWorkoutState(val1,val2)

Do not use AsyncStorage for this.

Body:
I am totally lost on how to grab two parameters from a form screen and pass them via React Navigator and display them on the previous screen.

The app section in question works like this:

1. touchablehighlight to form screen.

2. input title and description and press submit onpress

3. the onpress runs a function that dispatches the parameters to the previous page via a key.

4. then returns back to the origin page, with the props on display.

I am having multiple issues with the process:

1. if I am understanding the docs correctly, each page has a unique key and i tried to find it via this.props.navigation.state.key, however unknown to me, on refresh the id number would change.

2. that leads to problem 2 where the function will run, but it will not redirect back to the original page.

3. i have tried .navigate line after .dispatch but it would open a new copy of the original page and not display the new props that supposively were passed down.

import React from 'react';
import styles from '../styling/style.js';
import { Text, View, Image, TouchableHighlight, TextInput, Alert } from 'react-native';
import { StackNavigator, NavigationActions } from 'react-navigation';
import Forms from './formGenerator';

export default class Workout extends React.Component {
constructor(props) {
  super(props);
  this.state = {
     programTitle: '',
     programDescription: ''
  }
}

render() {
  const {navigate} = this.props.navigation;
  return (
    <Image style={styles.workoutContainer, { flex: 1}} source={require("../images/HomepageBackground.jpg")}>
      <View style={styles.workoutBody}>
          <Text style={styles.workoutTextBody}> {this.state.programTitle}</Text>
          <Text style={styles.workoutTextBody}>{this.state.programDescription}</Text>
      </View>
        <View style={styles.createButton}>
        <TouchableHighlight onPress={Alert.alert(this.props.navigation.state.key)} style={styles.addButtonTouch} title='test' >
         <Text style={styles.addButtonText}>+</Text>
        </TouchableHighlight>
        </View>
    </Image>
    );
  }

// End of the render
}

import React from 'react';
import styles from '../styling/style.js';
import { Text, View, Image, TouchableHighlight, TextInput, Button, Alert } from 'react-native';
import Workout from './workouts';
import { NavigationActions } from 'react-navigation';

export default class Forms extends React.Component {
constructor(props) {
  super(props);
  this.state = {
     programTitle: '',
     programDescription: ''
  }
}

render() {
  const {goBack} = this.props.navigation;
  const {params} = this.props.navigation.state;
  return (
    <Image style={styles.workoutContainer, { flex: 1}} source={require("../images/HomepageBackground.jpg")}>
      <View style={styles.workoutBody}>
        <Text style={styles.formHeader}>Program Title</Text>
          <TextInput
            autoFocus={true}
            style={styles.formBody}
            onChangeText={(programTitle) => this.setState({programTitle})}
            placeholder='Title'
            value={this.state.programTitle} />
        <Text style={styles.formHeader}>Description (Ex. 4sets x 10reps)</Text>
          <TextInput
            autoFocus={true}
            style={styles.formBody}
            placeholder='Description'
            onChangeText={(programDescription) => this.setState({programDescription})}
            value={this.state.programDescription} />
        <TouchableHighlight onPress={this.addProgram} style={styles.buttonBody} title="Add Program" >
          <Text>Add Program</Text>
        </TouchableHighlight>
      </View>
    </Image>
    );
  }

addProgram = () => {
  Alert.alert(this.props.navigation.state.key);
  this.setState({programTitle: ''});
  this.setState({programDescription: ''});
  const setParamsAction = NavigationActions.setParams({
  params: { programTitle: this.state.programTitle, programDescription: this.state.programDescription },
  key: ,
})
this.props.navigation.dispatch(setParamsAction)
};

}

Body:
You are just trying to display information from the Forms class on the Workout class, correct??

From your Workout class, create a function that update's it's state.

updateWorkoutState = (programTitle,programDescription) => this.setState(programTitle,programDescription)

Pass that function through to the Forms class when you push that route.

 this.props.navigation.navigate('Forms',{updateWorkoutState: this.updateWorkoutState}

Once your conditions are met on the Forms class and you want to update the Workout component, call it with this.props.navigation.state.params.updateWorkoutState(val1,val2)

Do not use AsyncStorage for this.


问:
400 error - The given location is invalid
I am trying to retrieve JSON data via an API and parsing it into my Android. I am trying to log the JSON data retrieved but I keep getting a "400 error - given location is invalid." The parameters to access the API seem correct but I am not sure why I can't retrieve the data.

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    temperatureLabel = (TextView) findViewById(R.id.temperatureLabel);
    timeLabel = (TextView) findViewById(R.id.timeLabel);
    refreshButton = (ImageView) findViewById(R.id.refreshImage);

    final double latitude = -104.8319;
    final double longtitude = 39.7294;

    refreshButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getWeatherForecast(latitude, longtitude);
        }
    });

    getWeatherForecast(latitude, longtitude);
}

    public void getWeatherForecast(double latitude, double longtitude) {

    String apiKey = "SECRET-KEY;
    String forecastURL = "https://api.darksky.net/forecast/" + apiKey + "/" + latitude + ","
            + longtitude;

    if (isNetworkAvailable()) {

        //Build and HTTP request
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(forecastURL).build();

        //Make an Api call
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        alertUserError();
                    }
                });
            }
            @Override
            public void onResponse(Response response) throws IOException {
            try {

                String jsonData = response.body().string();
                Log.e(TAG, "JASON DATA" + jsonData);

                if (response.isSuccessful()) {
                    mcurrentWeather = getCurrentWeatherDetails(jsonData);
                    // You want to update the display In the UI.
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updateDisplay();
                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "API call failed", Toast.LENGTH_LONG).show();
                        }
                    });
                }
            } catch (IOException e) {
               Log.e(TAG, "Exception Caught");
            } catch (JSONException e) {
               Log.e(TAG, "JSONexception Caught");
            }
        }
    });
} else {
    alertUserError();
    }
}
</code>```

答: If you are trying to check what request you send to the API and what the API sends to you, then you should implement OkHttp logging interceptor. It's simple and easy to work with it.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to retrieve JSON data via an API and parsing it into my Android. I am trying to log the JSON data retrieved but I keep getting a "400 error - given location is invalid." The parameters to access the API seem correct but I am not sure why I can't retrieve the data.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    temperatureLabel = (TextView) findViewById(R.id.temperatureLabel);
    timeLabel = (TextView) findViewById(R.id.timeLabel);
    refreshButton = (ImageView) findViewById(R.id.refreshImage);

    final double latitude = -104.8319;
    final double longtitude = 39.7294;

    refreshButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getWeatherForecast(latitude, longtitude);
        }
    });

    getWeatherForecast(latitude, longtitude);
}

    public void getWeatherForecast(double latitude, double longtitude) {

    String apiKey = "SECRET-KEY;
    String forecastURL = "https://api.darksky.net/forecast/" + apiKey + "/" + latitude + ","
            + longtitude;

    if (isNetworkAvailable()) {

        //Build and HTTP request
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(forecastURL).build();

        //Make an Api call
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        alertUserError();
                    }
                });
            }
            @Override
            public void onResponse(Response response) throws IOException {
            try {

                String jsonData = response.body().string();
                Log.e(TAG, "JASON DATA" + jsonData);

                if (response.isSuccessful()) {
                    mcurrentWeather = getCurrentWeatherDetails(jsonData);
                    // You want to update the display In the UI.
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updateDisplay();
                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "API call failed", Toast.LENGTH_LONG).show();
                        }
                    });
                }
            } catch (IOException e) {
               Log.e(TAG, "Exception Caught");
            } catch (JSONException e) {
               Log.e(TAG, "JSONexception Caught");
            }
        }
    });
} else {
    alertUserError();
    }
}


问:
How to check if Notepad++ is installed using Powershell
I am writing some powershell script to check if notepad++ is installed on my laptop. Though I'm having some issues with this.

Here's the code:

```<code># Variable(s)

$regkey = "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Notepad++"
#
# Check if Notepad ++ is already installed.

If($regkey)
{
    Write-output "Notepad++ is already installed on your machine."
}
Else
{
    Write-Output "Notepad++ is not installed on your machine."
}
</code>```

I uninstalled notepad++ manually. I then executed the script and the output message that was displayed was that notepad++ is installed, when it isn't. Why is this?

Any help will be much appreciated.

答:
You never test if registry path exists.

If($regkey){} always returns True because the variable is not null so Notepad++ is always installed.

Try this, it checks if a registry path exists :

```<code>if(Test-Path "hklm:\SOFTWARE\Wow6432Node\Notepad++"){
    Write-output "Notepad++ is already installed on your machine."
}
Else{
    Write-Output "Notepad++ is not installed on your machine."
}
</code>```

Body:
I am writing some powershell script to check if notepad++ is installed on my laptop. Though I'm having some issues with this.

Here's the code:

# Variable(s)

$regkey = "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Notepad++"
#
# Check if Notepad ++ is already installed.

If($regkey)
{
    Write-output "Notepad++ is already installed on your machine."
}
Else
{
    Write-Output "Notepad++ is not installed on your machine."
}

I uninstalled notepad++ manually. I then executed the script and the output message that was displayed was that notepad++ is installed, when it isn't. Why is this?

Any help will be much appreciated.

Body:
You never test if registry path exists.

If($regkey){} always returns True because the variable is not null so Notepad++ is always installed.

Try this, it checks if a registry path exists :

if(Test-Path "hklm:\SOFTWARE\Wow6432Node\Notepad++"){
    Write-output "Notepad++ is already installed on your machine."
}
Else{
    Write-Output "Notepad++ is not installed on your machine."
}


问:
How can i keep my data of mariadb on docker after migrate it to another machine?
I was using a dockerized mariadb container (connected to mediawiki) with default setting(docker run --name some-mariadb -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mariadb:tag). And now i need to migrate it to another machine. But don't know how to keep it's data together.

docker inspect told me that the current data is located in /var/lib/docker/volumes/c27...d02/_data. Do i just need to copy this folder and move to another machine together? Need your help guys :(

答:
Simply keep that directory as a volume. Have you read the documentation? Especially the Where to Store Data part

```<code>-v /var/lib/mysql
</code>```

When you migrate to another machine, simply copy&paste that directory to its counterpart on the another server.

Body:
Simply keep that directory as a volume. Have you read the documentation? Especially the Where to Store Data part

-v /var/lib/mysql

When you migrate to another machine, simply copy&paste that directory to its counterpart on the another server.


问:
React-native create an unsigned apk from app that hasn't run once in an android device/emulator
So when I run this command to create an unsigned apk:

react-native bundle --dev false --platform android --entry-file index.android.js --bundle-output ./android/app/build/intermediates/assets/debug/index.android.bundle --assets-dest ./android/app/build/intermediates/res/merged/debug

The above command works if and and only if I have run before the react-native run-android command. Which I think creates some directories /bundlethat allows the first command to run.

Since we are trying to set up a CI server with Jenkins and we need to generate an unsigned apk. Is there anyway to generate an unsigned apk from repository code without having the default dir generate when you run the react-native run-android command?

答:
Try with command

```<code>$ cd android && ./gradlew assembleRelease
</code>```

For debug app use assembleDebug

For more about generate apk, you can check react native doc on
https://facebook.github.io/react-native/docs/signed-apk-android.html#generating-the-release-apk

Body:
Try with command

$ cd android && ./gradlew assembleRelease

For debug app use assembleDebug

For more about generate apk, you can check react native doc on
https://facebook.github.io/react-native/docs/signed-apk-android.html#generating-the-release-apk


问:
Magento2: error when trying to save data with image in admin
I wrote a custom slider module which includes slide items form. In this form, there is an image field to upload images.

When I create for the first time a slide item with an image everything is working fine and I can retrieve all my data but when I edit it and save it again I got this error:

1 exception(s): Exception #0 (Exception): Notice: Array to string
  conversion in
  /Users/louisserre/Sites/messika/lib/internal/Magento/Framework/Data/Form/Element/Image.php
  on line 51

I got this error even if the image field is not changed.

At ligne 51 of this file the code is:

```<code>public function getElementHtml(){
    $html = '';

    if ((string)$this->getValue()) {
</code>```

I logged $this->getValue() and i got: imagepath/image.jpg when I create the slide item for the first time and Array([value] => http://imagepath/image.jpg) when I edit the slide item.

Here is my form field code:

```<code>    $fieldset->addField('image_url', 'image', [
        'label' => __('Image'),
        'title' => __('Image'),
        'name' => 'image_url',
        'required' => true
    ]);
</code>```

Here is my controller Save.php file:

```<code><?php

namespace Ultranoir\Slider\Controller\Adminhtml\SliderItem;

use Ultranoir\Slider\Model\Slider;
use Magento\Backend\App\Action;
use Magento\TestFramework\ErrorLog\Logger;
use Magento\Framework\App\Filesystem\DirectoryList;

class Save extends \Magento\Backend\App\Action
{

/**
 * Store manager
 *
 * @var \Magento\Store\Model\StoreManagerInterface
 */
protected $storeManager;

/**
 * @var \Magento\Framework\Image\Factory
 */
protected $imageFactory;

/**
 * @var \Magento\Framework\Image\Factory
 */
protected $mediaDirectory;

/**
 * @var \Magento\Framework\View\Asset\Repository
 */
protected $assetRepo;

/**
 * @param \Magento\Store\Model\StoreManagerInterface $storeManager
 * @param \Magento\Framework\Image\Factory $imageFactory
 * @param \Magento\Framework\Filesystem $fileSystem
 * @param \Magento\Framework\View\Asset\Repository $assetRepo
 * @param Action\Context $context
 */
public function __construct(\Magento\Store\Model\StoreManagerInterface $storeManager,
                            \Magento\Framework\Image\Factory $imageFactory,
                            \Magento\Framework\Filesystem $fileSystem,
                            \Magento\Framework\View\Asset\Repository $assetRepo,
                            Action\Context $context)
{
    $this->storeManager = $storeManager;
    $this->imageFactory = $imageFactory;
    /** @var \Magento\Framework\Filesystem\Directory\Read $mediaDirectory */
    $this->mediaDirectory = $fileSystem->getDirectoryRead(DirectoryList::MEDIA);
    parent::__construct($context);
}

/**
 * {@inheritdoc}
 */
protected function _isAllowed()
{
    return $this->_authorization->isAllowed('Ultranoir_Slider::save_slideritem');
}

/**
 * Save action
 *
 * @return \Magento\Framework\Controller\ResultInterface
 */
public function execute()
{
    $data = $this->getRequest()->getPostValue();
    /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
    $resultRedirect = $this->resultRedirectFactory->create();
    if ($data) {
        /** @var \Ultranoir\Slider\Model\SliderItem $model */
        $model = $this->_objectManager->create('\Ultranoir\Slider\Model\SliderItem');

        $id = $this->getRequest()->getParam('slider_item_id');
        if ($id) {
            $model->load($id);
        }
        /** @var \Ultranoir\Slider\Model\Slider $slider */
        $slider = $this->_objectManager->create('\Ultranoir\Slider\Model\Slider');
        $slider->load($model->getSliderId());

        try{
            $data['image_url'] = $this->saveImage();

        } catch (\Exception $e) {
            $result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
            $this->messageManager->addException($e, __('Something went wrong while uploading the file.'));
            $this->_getSession()->setFormData($data);
            return $resultRedirect->setPath('*/*/edit', ['slider_item_id' => $this->getRequest()->getParam
            ('slider_item_id')]);
        }

        $model->setData($data);

        $this->_eventManager->dispatch(
            'ultraslider_slideritem_prepare_save',
            ['slideritem' => $model, 'request' => $this->getRequest()]
        );

        try {
            $model->save();
            $this->messageManager->addSuccess(__('You saved this item.'));
            $this->_objectManager->get('Magento\Backend\Model\Session')->setFormData(false);
            if ($this->getRequest()->getParam('back')) {
                return $resultRedirect->setPath('*/*/edit', ['slider_item_id' => $model->getId(), '_current' =>
                    true]);
            }
            return $resultRedirect->setPath('*/*/');
        } catch (\Magento\Framework\Exception\LocalizedException $e) {
            $this->messageManager->addError($e->getMessage());
        } catch (\RuntimeException $e) {
            $this->messageManager->addError($e->getMessage());
        } catch (\Exception $e) {
            $this->messageManager->addException($e, __('Something went wrong while saving the record.'));
        }

        $this->_getSession()->setFormData($data);
        return $resultRedirect->setPath('*/*/edit', ['slider_item_id' => $this->getRequest()->getParam
        ('slider_item_id')]);
    }
    return $resultRedirect->setPath('*/*/');
}

protected function saveImage(){
    $uploader = $this->_objectManager->create(
        'Magento\MediaStorage\Model\File\Uploader',
        ['fileId' => 'image_url']
    );
    $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
    /** @var \Magento\Framework\Image\Adapter\AdapterInterface $imageAdapter */
    $imageAdapter = $this->_objectManager->get('Magento\Framework\Image\AdapterFactory')->create();
    $uploader->addValidateCallback('ultraslider_slideritem_image', $imageAdapter, 'validateUploadFile');
    $uploader->setAllowRenameFiles(true);
    $uploader->setFilesDispersion(true);

    $result = $uploader->save($this->getBaseMediaPath());
    $this->generateThumbnails($result['file'], $this->getBaseMediaPath());
    $this->_eventManager->dispatch(
        'ultraslider_slideritem_gallery_upload_image_after',
        ['result' => $result, 'action' => $this]
    );

    unset($result['tmp_name']);
    unset($result['path']);

    $result['url'] = $this->getBaseMediaUrl(). $result['file'];
    return $result['url'];

}

protected function getBaseMediaPath(){
    return $this->mediaDirectory->getAbsolutePath('slider/slideritem');
}

protected function getBaseMediaUrl(){
    return $this->storeManager->getStore()->getBaseUrl(
        \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
    ).'slider/slideritem';
}

/**
 * @return string
 */
public function getImageUrl($filePath)
{
    if (!$this->mediaDirectory->isFile($filePath)) {
        $url = $this->assetRepo->getUrl(
            "Ultranoir_Slider::images/slideritem/placeholder/thumbnail.jpg"
        );
    } else {
        $url = $this->storeManager->getStore()->getBaseUrl(
                \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
            ) . $filePath;
    }

    return $url;
}

public function generateThumbnails($fileName, $destinationBaseDir){

    $configs = [
        [
            'width' => 100,
            'height' => 100
        ],
        [
            'width' => 200,
            'height' => 200
        ],
    ];
    // build new filename (most important params)

    foreach($configs as $config){
        $processor = $this->imageFactory->create($destinationBaseDir.$fileName);
        $processor->keepTransparency(true);
        $processor->keepAspectRatio(true);
        $processor->resize($config['width'], $config['height']);
        $path = [
            $destinationBaseDir,
            'cache',
            $this->storeManager->getStore()->getId(),
            'thumbnail'
        ];
        $path[] = "{$config['width']}x{$config['height']}";
        $newFile = implode('/', $path) . $fileName;
        $processor->save($newFile);
    }
}

}
</code>```

Thanks in advance for your answers.

答:
You need to change the image format from array to string before saving data. To solve this issue just insert given below code before '$model->setData($data);' in your 'save.php' file.

Code is:

```<code>if(isset($data['image_url']['value']))
{
    $data['image_url'] = $data['image_url']['value'];
}
</code>```

Body:
I wrote a custom slider module which includes slide items form. In this form, there is an image field to upload images.

When I create for the first time a slide item with an image everything is working fine and I can retrieve all my data but when I edit it and save it again I got this error:

1 exception(s): Exception #0 (Exception): Notice: Array to string
  conversion in
  /Users/louisserre/Sites/messika/lib/internal/Magento/Framework/Data/Form/Element/Image.php
  on line 51

I got this error even if the image field is not changed.

At ligne 51 of this file the code is:

public function getElementHtml(){
    $html = '';

    if ((string)$this->getValue()) {

I logged $this->getValue() and i got: imagepath/image.jpg when I create the slide item for the first time and Array([value] => http://imagepath/image.jpg) when I edit the slide item.

Here is my form field code:

    $fieldset->addField('image_url', 'image', [
        'label' => __('Image'),
        'title' => __('Image'),
        'name' => 'image_url',
        'required' => true
    ]);

Here is my controller Save.php file:

<?php

namespace Ultranoir\Slider\Controller\Adminhtml\SliderItem;

use Ultranoir\Slider\Model\Slider;
use Magento\Backend\App\Action;
use Magento\TestFramework\ErrorLog\Logger;
use Magento\Framework\App\Filesystem\DirectoryList;

class Save extends \Magento\Backend\App\Action
{

/**
 * Store manager
 *
 * @var \Magento\Store\Model\StoreManagerInterface
 */
protected $storeManager;

/**
 * @var \Magento\Framework\Image\Factory
 */
protected $imageFactory;

/**
 * @var \Magento\Framework\Image\Factory
 */
protected $mediaDirectory;

/**
 * @var \Magento\Framework\View\Asset\Repository
 */
protected $assetRepo;

/**
 * @param \Magento\Store\Model\StoreManagerInterface $storeManager
 * @param \Magento\Framework\Image\Factory $imageFactory
 * @param \Magento\Framework\Filesystem $fileSystem
 * @param \Magento\Framework\View\Asset\Repository $assetRepo
 * @param Action\Context $context
 */
public function __construct(\Magento\Store\Model\StoreManagerInterface $storeManager,
                            \Magento\Framework\Image\Factory $imageFactory,
                            \Magento\Framework\Filesystem $fileSystem,
                            \Magento\Framework\View\Asset\Repository $assetRepo,
                            Action\Context $context)
{
    $this->storeManager = $storeManager;
    $this->imageFactory = $imageFactory;
    /** @var \Magento\Framework\Filesystem\Directory\Read $mediaDirectory */
    $this->mediaDirectory = $fileSystem->getDirectoryRead(DirectoryList::MEDIA);
    parent::__construct($context);
}

/**
 * {@inheritdoc}
 */
protected function _isAllowed()
{
    return $this->_authorization->isAllowed('Ultranoir_Slider::save_slideritem');
}

/**
 * Save action
 *
 * @return \Magento\Framework\Controller\ResultInterface
 */
public function execute()
{
    $data = $this->getRequest()->getPostValue();
    /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
    $resultRedirect = $this->resultRedirectFactory->create();
    if ($data) {
        /** @var \Ultranoir\Slider\Model\SliderItem $model */
        $model = $this->_objectManager->create('\Ultranoir\Slider\Model\SliderItem');

        $id = $this->getRequest()->getParam('slider_item_id');
        if ($id) {
            $model->load($id);
        }
        /** @var \Ultranoir\Slider\Model\Slider $slider */
        $slider = $this->_objectManager->create('\Ultranoir\Slider\Model\Slider');
        $slider->load($model->getSliderId());

        try{
            $data['image_url'] = $this->saveImage();

        } catch (\Exception $e) {
            $result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
            $this->messageManager->addException($e, __('Something went wrong while uploading the file.'));
            $this->_getSession()->setFormData($data);
            return $resultRedirect->setPath('*/*/edit', ['slider_item_id' => $this->getRequest()->getParam
            ('slider_item_id')]);
        }

        $model->setData($data);

        $this->_eventManager->dispatch(
            'ultraslider_slideritem_prepare_save',
            ['slideritem' => $model, 'request' => $this->getRequest()]
        );

        try {
            $model->save();
            $this->messageManager->addSuccess(__('You saved this item.'));
            $this->_objectManager->get('Magento\Backend\Model\Session')->setFormData(false);
            if ($this->getRequest()->getParam('back')) {
                return $resultRedirect->setPath('*/*/edit', ['slider_item_id' => $model->getId(), '_current' =>
                    true]);
            }
            return $resultRedirect->setPath('*/*/');
        } catch (\Magento\Framework\Exception\LocalizedException $e) {
            $this->messageManager->addError($e->getMessage());
        } catch (\RuntimeException $e) {
            $this->messageManager->addError($e->getMessage());
        } catch (\Exception $e) {
            $this->messageManager->addException($e, __('Something went wrong while saving the record.'));
        }

        $this->_getSession()->setFormData($data);
        return $resultRedirect->setPath('*/*/edit', ['slider_item_id' => $this->getRequest()->getParam
        ('slider_item_id')]);
    }
    return $resultRedirect->setPath('*/*/');
}

protected function saveImage(){
    $uploader = $this->_objectManager->create(
        'Magento\MediaStorage\Model\File\Uploader',
        ['fileId' => 'image_url']
    );
    $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
    /** @var \Magento\Framework\Image\Adapter\AdapterInterface $imageAdapter */
    $imageAdapter = $this->_objectManager->get('Magento\Framework\Image\AdapterFactory')->create();
    $uploader->addValidateCallback('ultraslider_slideritem_image', $imageAdapter, 'validateUploadFile');
    $uploader->setAllowRenameFiles(true);
    $uploader->setFilesDispersion(true);

    $result = $uploader->save($this->getBaseMediaPath());
    $this->generateThumbnails($result['file'], $this->getBaseMediaPath());
    $this->_eventManager->dispatch(
        'ultraslider_slideritem_gallery_upload_image_after',
        ['result' => $result, 'action' => $this]
    );

    unset($result['tmp_name']);
    unset($result['path']);

    $result['url'] = $this->getBaseMediaUrl(). $result['file'];
    return $result['url'];

}

protected function getBaseMediaPath(){
    return $this->mediaDirectory->getAbsolutePath('slider/slideritem');
}

protected function getBaseMediaUrl(){
    return $this->storeManager->getStore()->getBaseUrl(
        \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
    ).'slider/slideritem';
}

/**
 * @return string
 */
public function getImageUrl($filePath)
{
    if (!$this->mediaDirectory->isFile($filePath)) {
        $url = $this->assetRepo->getUrl(
            "Ultranoir_Slider::images/slideritem/placeholder/thumbnail.jpg"
        );
    } else {
        $url = $this->storeManager->getStore()->getBaseUrl(
                \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
            ) . $filePath;
    }

    return $url;
}

public function generateThumbnails($fileName, $destinationBaseDir){

    $configs = [
        [
            'width' => 100,
            'height' => 100
        ],
        [
            'width' => 200,
            'height' => 200
        ],
    ];
    // build new filename (most important params)

    foreach($configs as $config){
        $processor = $this->imageFactory->create($destinationBaseDir.$fileName);
        $processor->keepTransparency(true);
        $processor->keepAspectRatio(true);
        $processor->resize($config['width'], $config['height']);
        $path = [
            $destinationBaseDir,
            'cache',
            $this->storeManager->getStore()->getId(),
            'thumbnail'
        ];
        $path[] = "{$config['width']}x{$config['height']}";
        $newFile = implode('/', $path) . $fileName;
        $processor->save($newFile);
    }
}

}

Thanks in advance for your answers.

Body:
You need to change the image format from array to string before saving data. To solve this issue just insert given below code before '$model->setData($data);' in your 'save.php' file.

Code is:

if(isset($data['image_url']['value']))
{
    $data['image_url'] = $data['image_url']['value'];
}


问:
OpenpyXL: Runtime Error 6 Overflow
I have a program utilizing openpyxl that opens two existing Excel files.  One is a simple worksheet with data that needs to be copied into the other file, which is a workbook containing many worksheets and with VBA macros that use this copied data.  When the VBA code runs, though, I get a Runtime Error 6 overflow.  The strange thing is that if I manually copy all of the required cells into the workbook, the macros run without a hitch.  But when this process is automated, even though the values in the cells are identical, this error pops up.  Below is the code which transcribes the data from one worksheet to the other.

```<code>def transcribe_client_data_to_workbooks():
    _active_sheet_index = 5
    for client in set(cdict.values()):
        report_path = r'C:\Program Files\Notepad++\reports' + '\\' +
        string.replace(client,'/','-') + '_report.csv'
        wb = openpyxl.load_workbook('Bucket-Asset Allocation Model.xlsm',
             read_only = False, keep_vba = True)
        ws = wb.active
        with open(report_path, 'rU') as f:
            reader = csv.reader(f)
            for row_index, row in enumerate(reader):
                for column_index, cell in enumerate(row):
                    column_letter = get_column_letter((column_index+1))
                    ws[column_letter+str(row_index+1)] = cell
            f.close()
        wb.save('C:\\Program Files\\Notepad++\\workbooks\\' +
        string.replace(client,'/','-') + '_workbook.xlsm')
</code>```

I don't understand why I would receive this error message when this data is automatically copied in, but not when I copy/paste manually. I open the same workbook template each iteration and then save it as a new one after the appropriate data has been copied over.  For reference, here is the section of VBA code where the error occurs.

```<code>Do Until Sheets("Raw Data").Cells(crow, 1).Value = Empty
                aNumber = Sheets("Raw Data").Cells(crow, 1).Value
                ticker = Sheets("Raw Data").Cells(crow, 9).Value
                security = Sheets("Raw Data").Cells(crow, 8).Value
                mValue = Sheets("Raw Data").Cells(crow, 12).Value
                bAmt = Sheets("Raw Data").Cells(crow, 18).Value
                uGain = Sheets("Raw Data").Cells(crow, 20).Value
                    Do Until Sheets("Accounts").Cells(acrow, 1).Value = aNumber
                    acrow = acrow + 1
                    Loop
</code>```

Specifically it occurs on the line that increments acrow:
acrow = acrow + 1
I tried changing acrow from an integer to a long, but that just causes the program to run indefinitely  until I click or cancel it, at which point I receive Run-time error '1004', Application defined or object-defined error, on the line directly preceding the increment of acrow.

Any help would be appreciated, thanks!

答: John Coleman was correct about the location of the overflow.  The issue was that I was writing aNumber as strings and aNumber was declared in the VBA as Variant type, which according to the docs can represent anything other than a fixed length string.  I simply changed my strategy and wrote account numbers as integers which resolved the problem.  </p>

Title: OpenpyXL: Runtime Error 6 Overflow

Body:
I have a program utilizing openpyxl that opens two existing Excel files.  One is a simple worksheet with data that needs to be copied into the other file, which is a workbook containing many worksheets and with VBA macros that use this copied data.  When the VBA code runs, though, I get a Runtime Error 6 overflow.  The strange thing is that if I manually copy all of the required cells into the workbook, the macros run without a hitch.  But when this process is automated, even though the values in the cells are identical, this error pops up.  Below is the code which transcribes the data from one worksheet to the other.

def transcribe_client_data_to_workbooks():
    _active_sheet_index = 5
    for client in set(cdict.values()):
        report_path = r'C:\Program Files\Notepad++\reports' + '\\' +
        string.replace(client,'/','-') + '_report.csv'
        wb = openpyxl.load_workbook('Bucket-Asset Allocation Model.xlsm',
             read_only = False, keep_vba = True)
        ws = wb.active
        with open(report_path, 'rU') as f:
            reader = csv.reader(f)
            for row_index, row in enumerate(reader):
                for column_index, cell in enumerate(row):
                    column_letter = get_column_letter((column_index+1))
                    ws[column_letter+str(row_index+1)] = cell
            f.close()
        wb.save('C:\\Program Files\\Notepad++\\workbooks\\' +
        string.replace(client,'/','-') + '_workbook.xlsm')

I don't understand why I would receive this error message when this data is automatically copied in, but not when I copy/paste manually. I open the same workbook template each iteration and then save it as a new one after the appropriate data has been copied over.  For reference, here is the section of VBA code where the error occurs.

Do Until Sheets("Raw Data").Cells(crow, 1).Value = Empty
                aNumber = Sheets("Raw Data").Cells(crow, 1).Value
                ticker = Sheets("Raw Data").Cells(crow, 9).Value
                security = Sheets("Raw Data").Cells(crow, 8).Value
                mValue = Sheets("Raw Data").Cells(crow, 12).Value
                bAmt = Sheets("Raw Data").Cells(crow, 18).Value
                uGain = Sheets("Raw Data").Cells(crow, 20).Value
                    Do Until Sheets("Accounts").Cells(acrow, 1).Value = aNumber
                    acrow = acrow + 1
                    Loop

Specifically it occurs on the line that increments acrow:
acrow = acrow + 1
I tried changing acrow from an integer to a long, but that just causes the program to run indefinitely  until I click or cancel it, at which point I receive Run-time error '1004', Application defined or object-defined error, on the line directly preceding the increment of acrow.

Any help would be appreciated, thanks!


问:
How do I make site info appear in the address bar of a browser
I saw this :

Some site info appears. I use https and i only see "secure" on this place. How do they do this?

答: Unfortunately, I seems that is a feature of specific browsers. It would seem that you have no control over the content.</p>


问:
Pattern Matching - Regex
User input Format:

[fieldname1] comparator [fieldvalue1,fieldvalue2,value3],[fieldname2]
  comparator [fieldvalue1,value2,..],..

Need to parse this into:

1.[fieldname1] comparator [fieldvalue1,fieldvalue2,value3]

2.[fieldname2] comparator [fieldvalue1,value2,..] and so on

(ie)each field along with its comparator and value has to be separated.
whereas comparator will be any one of the below:

<=|>=|=|is|<|>|startswith|Starts with|Beginswith|Begins with|Ends
  with|Endswith|

contains

Regex used by me :

([(.)+?](\s)(<=|>=|=|is|<|>|startswith|Starts
  with|Beginswith|Begins with|Ends
  with|Endswith|contains)(\s)[(.)+?](\,)*)

Example:
[company] contains [abc,efg],[email] contains [cdf,test]
above is parsed properly no issues.

Problem:
When field name or field value contains symbol "[" or "]" the parsing goes wrong .

example :
[company] contains [ab[]c,efg],[email] contains [siva,test]

Above is valid but since [] is used as delimiter it stops parsing till [company] contains [ab[] but i want it to parse properly as above eg,

1.[company] contains [ab[]c,efg]

2.[email] contains [siva,test]

Thanks.

答:
You can try with this regex:

```<code>,(?=(?:(?:[^\\[\\]]*[\\]\\[]){2})*[^\\[\\]]*$)
</code>```

Splitting your target string should give you list of splitted result set. Over which you can apply your comparator matching easily

```<code>final String regex = ",(?=(?:(?:[^\\[\\]]*[\\]\\[]){2})*[^\\[\\]]*$)";
final String string = "[company] contains [ab[]c,efg],[email] contains [siva,test]";
String[] res=string.split(regex);
System.out.println(Arrays.asList(res).toString());
</code>```

By using this you get the exptected result. All you may need to check is, if each index contains the correct comparator as you have shown. if not, then remove that from the array.

The above code outputs:

```<code>[
  [company] contains [ab[]c,efg],
  [email] contains [siva,test]
]
</code>```

Regex101Demo

Explanation:

Whenever a , is found -->

```<code>,(?=(?:(?:[^\\[\\]]*[\\]\\[]){2})*[^\\[\\]]*$)
</code>```

a positive look ahead runs until the end of string  where the following line

(?:[^\\[\\]]*[\\]\\[]){2})* ensures that - if a bracket is found it is found twice. Then the last * indicates 0 or more repetition of of bracket pair.

Why is that important ? From any comma , and afterwards you count number of [ and ] brackets. And you will see that you only need to split by that comma if only even number of brackets are there afterwards. and you dont want to split for commas for whom odd number of bracket comes afterwards. That is the explanation.

For entire breakdown of the regex you can look into the link where full explanation is given character by character in the right top section.

Title: Pattern Matching - Regex

Body:
You can try with this regex:

,(?=(?:(?:[^\\[\\]]*[\\]\\[]){2})*[^\\[\\]]*$)

Splitting your target string should give you list of splitted result set. Over which you can apply your comparator matching easily

final String regex = ",(?=(?:(?:[^\\[\\]]*[\\]\\[]){2})*[^\\[\\]]*$)";
final String string = "[company] contains [ab[]c,efg],[email] contains [siva,test]";
String[] res=string.split(regex);
System.out.println(Arrays.asList(res).toString());

By using this you get the exptected result. All you may need to check is, if each index contains the correct comparator as you have shown. if not, then remove that from the array.

The above code outputs:

[
  [company] contains [ab[]c,efg],
  [email] contains [siva,test]
]

Regex101Demo

Explanation:

Whenever a , is found -->

,(?=(?:(?:[^\\[\\]]*[\\]\\[]){2})*[^\\[\\]]*$)

a positive look ahead runs until the end of string  where the following line

(?:[^\\[\\]]*[\\]\\[]){2})* ensures that - if a bracket is found it is found twice. Then the last * indicates 0 or more repetition of of bracket pair.

Why is that important ? From any comma , and afterwards you count number of [ and ] brackets. And you will see that you only need to split by that comma if only even number of brackets are there afterwards. and you dont want to split for commas for whom odd number of bracket comes afterwards. That is the explanation.

For entire breakdown of the regex you can look into the link where full explanation is given character by character in the right top section.


问:
Kendo DropDownList not displaying selected item
I am trying to use a pair of Kendo dropdown lists to filter a dataset in AngularJS. One uses a static ObservableArray datasource to filter the dataset by status; the other datasource is a set of distinct values from the "regionID" column of the dataset, also stored as an ObservableArray. When the status dropdown changes, the region dropdown is supposed to reload the list of regions from the newly-filtered data. This works, but the selected value ends up blanked out, even though the model that's supposed to represent the selected value still has the correct value, and the data is still correctly filtered by that same value. Opening the dropdown and then clicking off of it causes it to then display that value as it should.

Here is what the HTML looks like:

```<code><select name="filterByRegion" style="width: 180px;" class="form-control" ng-model="selectedRegion" ng-change="onRegionFilterChange(selectedRegion)" kendo-drop-down-list k-options="regionFilterOptions"></select>
<select name="accountStatus" style="width: 180px;" class="form-control" ng-model="status" ng-change="onAccountStatusChange(status)" kendo-drop-down-list k-options="accountStatusOptions"></select>
</code>```

Here are the two "onChange" methods from the controller:

```<code>        $scope.onAccountStatusChange = function(status) {
            $scope.status = status;
            updateRegionFilterList();
        };
        $scope.onRegionFilterChange = function(selectedRegion) {
            $scope.selectedRegion = selectedRegion;
        };
</code>```

And lastly, here is the updateRegionFilterList method:

```<code>        var updateRegionFilterList = function () {

            $scope.regions.empty();

            angular.forEach($scope.accounts, function(account) {
                if (account.reviewStatus === $scope.status) {
                    if ($scope.regions.indexOf(account.regionID) <= -1) {
                        $scope.regions.push(account.regionID);
                    }
                }
            });

            $scope.regions.sort();
            $scope.regions.unshift("Filter By Region:");

            if ($scope.regions.indexOf(tempRegion) <= -1) {
                $scope.selectedRegion = "Filter By Region";
            }
        };
</code>```

I have tried many ways of working around this, including trying to preserve and reload the selectedRegion value, splicing out unneeded regions instead of emptying the ObservableArray, etc., and I have checked everything in the debugger and all of the values are correct (no obvious race conditions either).

Any ideas?

答: I figured it out. I had mixed kendo and angular configurations with the dropdowns and was relying on an angular process to update the data, which wasn't updating the Kendo MVVM stuff properly. Switching it to pure Kendo did the trick.</p>

Body:
I am trying to use a pair of Kendo dropdown lists to filter a dataset in AngularJS. One uses a static ObservableArray datasource to filter the dataset by status; the other datasource is a set of distinct values from the "regionID" column of the dataset, also stored as an ObservableArray. When the status dropdown changes, the region dropdown is supposed to reload the list of regions from the newly-filtered data. This works, but the selected value ends up blanked out, even though the model that's supposed to represent the selected value still has the correct value, and the data is still correctly filtered by that same value. Opening the dropdown and then clicking off of it causes it to then display that value as it should.

Here is what the HTML looks like:

<select name="filterByRegion" style="width: 180px;" class="form-control" ng-model="selectedRegion" ng-change="onRegionFilterChange(selectedRegion)" kendo-drop-down-list k-options="regionFilterOptions"></select>
<select name="accountStatus" style="width: 180px;" class="form-control" ng-model="status" ng-change="onAccountStatusChange(status)" kendo-drop-down-list k-options="accountStatusOptions"></select>

Here are the two "onChange" methods from the controller:

        $scope.onAccountStatusChange = function(status) {
            $scope.status = status;
            updateRegionFilterList();
        };
        $scope.onRegionFilterChange = function(selectedRegion) {
            $scope.selectedRegion = selectedRegion;
        };

And lastly, here is the updateRegionFilterList method:

        var updateRegionFilterList = function () {

            $scope.regions.empty();

            angular.forEach($scope.accounts, function(account) {
                if (account.reviewStatus === $scope.status) {
                    if ($scope.regions.indexOf(account.regionID) <= -1) {
                        $scope.regions.push(account.regionID);
                    }
                }
            });

            $scope.regions.sort();
            $scope.regions.unshift("Filter By Region:");

            if ($scope.regions.indexOf(tempRegion) <= -1) {
                $scope.selectedRegion = "Filter By Region";
            }
        };

I have tried many ways of working around this, including trying to preserve and reload the selectedRegion value, splicing out unneeded regions instead of emptying the ObservableArray, etc., and I have checked everything in the debugger and all of the values are correct (no obvious race conditions either).

Any ideas?


问:
how to create a rank system
I have a user table with user_score column in view side I want to show every user rank and score and 2 people before/after him.

how can I implement this with MySQL or PHP with minimum execution time?

example

```<code>+-----------+------------+
| User_id   | Score      |
+-----------+------------+
| 1         | 12258      |
| 2         | 112        |
| 3         | 9678       |
| 4         | 689206     |
| 5         | 1868       |
+-----------+------------+
</code>```

for example my user_id = 3. I want to show like this

```<code>                    you
                   9678

 user befor you               user after you
    12258                            1868
</code>```

答:
If you want to use only MySQL:

SELECT usr.user_id, (SELECT usr1.user_score FROM user usr1 WHERE usr.user_score >= usr1.user_score AND usr.user_id != usr1.user_id ORDER BY usr1.user_score DESC LIMIT 1) AS user_before_you, usr.user_score AS you, (SELECT usr1.user_score FROM user usr1 WHERE usr.user_score <= usr1.user_score AND usr.user_id != usr1.user_id ORDER BY usr1.user_score ASC LIMIT 1) AS user_after_you FROM user usr WHERE 1

Title: how to create a rank system

Body:
I have a user table with user_score column in view side I want to show every user rank and score and 2 people before/after him.

how can I implement this with MySQL or PHP with minimum execution time?

example

+-----------+------------+
| User_id   | Score      |
+-----------+------------+
| 1         | 12258      |
| 2         | 112        |
| 3         | 9678       |
| 4         | 689206     |
| 5         | 1868       |
+-----------+------------+

for example my user_id = 3. I want to show like this

                    you
                   9678

 user befor you               user after you
    12258                            1868


问:
EditText is not showing hint as well as text when typing
EditText is not showing hint as well as text when typing.
Here is code:

```<code><EditText
        android:id="@+id/passwordText"
        android:layout_width="135dp"
        android:layout_height="18dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="46dp"
        android:hint="Enter your password."
        android:text="Enter password"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/emailText"
        tools:text="Enter Password"/>
</code>```

I also tried to set color by code but it didn't worked:

final EditText passwordText = (EditText)
  findViewById(R.id.passwordText);
          passwordText.setTextColor(Color.BLACK);
          passwordText.setHint("Enter your Password.");
          passwordText.setHintTextColor(Color.BLACK);

Note: I'm using android studio 2.3.3;

Any help will be appreciated.

答:
Use  android:layout_height="wrap_content"
and use hint only

Body:
EditText is not showing hint as well as text when typing.
Here is code:

<EditText
        android:id="@+id/passwordText"
        android:layout_width="135dp"
        android:layout_height="18dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="46dp"
        android:hint="Enter your password."
        android:text="Enter password"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/emailText"
        tools:text="Enter Password"/>

I also tried to set color by code but it didn't worked:

final EditText passwordText = (EditText)
  findViewById(R.id.passwordText);
          passwordText.setTextColor(Color.BLACK);
          passwordText.setHint("Enter your Password.");
          passwordText.setHintTextColor(Color.BLACK);

Note: I'm using android studio 2.3.3;

Any help will be appreciated.


问:
Can the Java 9 jshell be used to run code in another JVM?
Java 9 has a read-eval-print loop for Java, called jshell. I've seen it work in it's basic mode, from the command line. Can it also be used in a remote process? In other words, can I connect to another Java process and enter code snippets to run within that runtime?  This would be a nice way to change configuration state in an app server without having to write an admin tool with a UI.

答: The simple answer is no, there is no way to attach jshell to a running Java process.  jshell is a standalone app that runs in its own JVM.</p>


问:
Linq extract a count() value from a data object
I have divAssignments that has potential multiple rows by rNI, an official id, according to a compound key of Indictment and booking numbers.

```<code>rNI    Booking  Indictment
12345  954445   10 12345
12345  954445   10 12346
12345  954445   10 12347
</code>```

So ID has a count of 3 for a single booking number for this rni.

I get lost attempting to generate a count and a group by booking Number:

```<code>var moreThen = from dA in divAssignments
    select new { dA.rNI, IndictmentCount = dA.indictmentNumber.Count() };
</code>```

Most of the examples are dealing with static int[] and don't seem to work in my case.

How do I get a group and then a count?  If I could put in a having that would be fantastic.

from a t-sql POV I'd use this:

```<code>Select rni, bookingNumber, count(*) IndictmentCount
from divAssignments
group by rni, bookingNumber
having count(*) > 0
</code>```

TIA

答:
If you use a Grouping operator in Linq you will get what you need.  The code:

```<code>  var count = from a in divAssignments
              group a by new { a.rNI, a.Booking } into b
              select b;
</code>```

will return a collection of IGrouping objects.  This will give you the Key (in my example this will be an anonymous type with an rNI and a Booking property) and a collection of the divAssignments that match the key.

ContentLicense: CC BY-SA 2.5

Body:
I have divAssignments that has potential multiple rows by rNI, an official id, according to a compound key of Indictment and booking numbers.

rNI    Booking  Indictment
12345  954445   10 12345
12345  954445   10 12346
12345  954445   10 12347

So ID has a count of 3 for a single booking number for this rni.

I get lost attempting to generate a count and a group by booking Number:

var moreThen = from dA in divAssignments
    select new { dA.rNI, IndictmentCount = dA.indictmentNumber.Count() };

Most of the examples are dealing with static int[] and don't seem to work in my case.

How do I get a group and then a count?  If I could put in a having that would be fantastic.

from a t-sql POV I'd use this:

Select rni, bookingNumber, count(*) IndictmentCount
from divAssignments
group by rni, bookingNumber
having count(*) > 0

TIA

Body:
If you use a Grouping operator in Linq you will get what you need.  The code:

  var count = from a in divAssignments
              group a by new { a.rNI, a.Booking } into b
              select b;

will return a collection of IGrouping objects.  This will give you the Key (in my example this will be an anonymous type with an rNI and a Booking property) and a collection of the divAssignments that match the key.


问:
Angular 2: Error while accessing JSON from HTTP
I am creating an application in angular 2. I am trying to access the json data via http in a service. But i am getting an error saying that

```<code>**GET http://localhost:4200/data/products.json 404 (Not Found)**
</code>```

I have the data in the specified folder but i am unable to access it.

My service code is as follows.

```<code>import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { Item } from './item';

@Injectable()
export class ItemService {
observableItems: Observable<Item[]>
allItems: Item[] = [];
selectedItems: Item[] = [];
errorMessage: string;
url = "http://localhost:4200/data/products.json";
constructor(private http:Http) {
   this.observableItems = this.http.get(this.url).map((res: Response) => res.json());
   this.observableItems.subscribe(
             data => this.allItems = data,
         error =>  this.errorMessage = <any>error);
}
getItems(): Observable<Item[]> {
   return this.observableItems;
}
getSelectedItems(): Item[] {
   return this.selectedItems;
}
    addItem(id:number): void {
       let item = this.allItems.find(ob => ob.id === id);
       if (this.selectedItems.indexOf(item) < 0) {
      this.selectedItems.push(item);
   }
    }
    removeItem(id:number): void {
   let item = this.selectedItems.find(ob => ob.id === id);
   let itemIndex = this.selectedItems.indexOf(item);
       this.selectedItems.splice(itemIndex, 1);
    }
}
</code>```

答:
Try using direct path to the file from the location of your service file. For example: </p>

```<code>url = "data/products.json";
</code>```

<p>It will work. </p>

Body:
I am creating an application in angular 2. I am trying to access the json data via http in a service. But i am getting an error saying that

**GET http://localhost:4200/data/products.json 404 (Not Found)**

I have the data in the specified folder but i am unable to access it.

My service code is as follows.

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { Item } from './item';

@Injectable()
export class ItemService {
observableItems: Observable<Item[]>
allItems: Item[] = [];
selectedItems: Item[] = [];
errorMessage: string;
url = "http://localhost:4200/data/products.json";
constructor(private http:Http) {
   this.observableItems = this.http.get(this.url).map((res: Response) => res.json());
   this.observableItems.subscribe(
             data => this.allItems = data,
         error =>  this.errorMessage = <any>error);
}
getItems(): Observable<Item[]> {
   return this.observableItems;
}
getSelectedItems(): Item[] {
   return this.selectedItems;
}
    addItem(id:number): void {
       let item = this.allItems.find(ob => ob.id === id);
       if (this.selectedItems.indexOf(item) < 0) {
      this.selectedItems.push(item);
   }
    }
    removeItem(id:number): void {
   let item = this.selectedItems.find(ob => ob.id === id);
   let itemIndex = this.selectedItems.indexOf(item);
       this.selectedItems.splice(itemIndex, 1);
    }
}

Body:
Try using direct path to the file from the location of your service file. For example:

url = "data/products.json";

It will work.


问:
FakeItEasy - faking assignment
I have Some code where I have a fake configuration root. I would like to check that a call is made to set a config value.

```<code>var fakeConfigRoot = A.Fake<IConfigurationRoot>();

//Do something that will set config item

//A call to set the config must have happened
</code>```

It is possible to fake getting a config item using

```<code> A.CallTo(() => fakeConfigRoot["TestConfigItem"]).MustHaveHappened(Repeated.Exactly.Once);
</code>```

I would like to know if it is possible using FakeItEasy to fake the assignment of a config item and if so how. If it is not possible can anyone think of any workarounds.

答:
You want to specify a call to a property setter using A.CallToSet. The examples don't show it, but the syntax works for an indexer as well. Try this:

```<code>var fakeConfigRoot = A.Fake<IConfigurationRoot>();

fakeConfigRoot["animal"] = "hippo";

A.CallToSet(() => fakeConfigRoot["animal"]).MustHaveHappened(Repeated.Exactly.Once);
</code>```

Title: FakeItEasy - faking assignment

Body:
I have Some code where I have a fake configuration root. I would like to check that a call is made to set a config value.

var fakeConfigRoot = A.Fake<IConfigurationRoot>();

//Do something that will set config item

//A call to set the config must have happened

It is possible to fake getting a config item using

 A.CallTo(() => fakeConfigRoot["TestConfigItem"]).MustHaveHappened(Repeated.Exactly.Once);

I would like to know if it is possible using FakeItEasy to fake the assignment of a config item and if so how. If it is not possible can anyone think of any workarounds.

Body:
You want to specify a call to a property setter using A.CallToSet. The examples don't show it, but the syntax works for an indexer as well. Try this:

var fakeConfigRoot = A.Fake<IConfigurationRoot>();

fakeConfigRoot["animal"] = "hippo";

A.CallToSet(() => fakeConfigRoot["animal"]).MustHaveHappened(Repeated.Exactly.Once);


问:
How to integrate Firebase with Glide ('using' method)
I'm trying to use Firebase integration with Glide and for some reason,
Glide.using() cannot resolve this method.
I did add:

```<code>compile 'com.firebaseui:firebase-ui-storage:0.6.0'
</code>```

Into build.gradle and also:

```<code>compile 'com.github.bumptech.glide:glide:4.0.0-RC1'
</code>```

Here is the part which I'm trying to use Glide:

```<code>   mStorageRef = FirebaseStorage.getInstance().getReference();
    mStorageRef.child("images/Puffer-fish-are-pretty-damn-cute.jpg");

// Load the image using Glide
        Glide.with(this)
                .using(new FirebaseImageLoader()) // cannot resolve method using!
                .load(mStorageRef)
                .into(imageView);
</code>```

I hope you can help me with that, didn't find any solutions online.

答:
To solve this, please change this line:

```<code>compile 'com.github.bumptech.glide:glide:4.0.0-RC1'
</code>```

with

```<code>compile 'com.github.bumptech.glide:glide:3.7.0'
</code>```

Body:
I'm trying to use Firebase integration with Glide and for some reason,
Glide.using() cannot resolve this method.
I did add:

compile 'com.firebaseui:firebase-ui-storage:0.6.0'

Into build.gradle and also:

compile 'com.github.bumptech.glide:glide:4.0.0-RC1'

Here is the part which I'm trying to use Glide:

   mStorageRef = FirebaseStorage.getInstance().getReference();
    mStorageRef.child("images/Puffer-fish-are-pretty-damn-cute.jpg");

// Load the image using Glide
        Glide.with(this)
                .using(new FirebaseImageLoader()) // cannot resolve method using!
                .load(mStorageRef)
                .into(imageView);

I hope you can help me with that, didn't find any solutions online.

Body:
To solve this, please change this line:

compile 'com.github.bumptech.glide:glide:4.0.0-RC1'

with

compile 'com.github.bumptech.glide:glide:3.7.0'


问:
NSString sizeWithFont:constrainedToSize: not working as expected
I'm attempting to use sizeWithFont as follows:

```<code>[commentTextLabel.text sizeWithFont:commentTextLabel.font
                  constrainedToSize:CGSizeMake(commentTextLabel.frame.size.width, CGFLOAT_MAX)
                      lineBreakMode:UILineBreakModeWordWrap];
</code>```

When I do this, I would expect the CGSize returned to have the same width as was passed in (commentTextLabel.frame.size.width) However, for some reason, the width is getting reduced despite the fact that the text has plenty of vertical room to grow.

Here are the values I'm seeing:

In: 360.000000, CGFLOAT_MAX

Out: 335.000000, 88.000000

Am I simply misunderstanding the function? If so, how could I implement this to determine the height of the text when constrained to a certain width?

答: After some playing around with it, what I believe is happening is that the text is wrapping in such a way that the longest line is only 335 pixels wide. The solution I'm using is to only use the height returned by this function.

Body:
I'm attempting to use sizeWithFont as follows:

[commentTextLabel.text sizeWithFont:commentTextLabel.font
                  constrainedToSize:CGSizeMake(commentTextLabel.frame.size.width, CGFLOAT_MAX)
                      lineBreakMode:UILineBreakModeWordWrap];

When I do this, I would expect the CGSize returned to have the same width as was passed in (commentTextLabel.frame.size.width) However, for some reason, the width is getting reduced despite the fact that the text has plenty of vertical room to grow.

Here are the values I'm seeing:

In: 360.000000, CGFLOAT_MAX

Out: 335.000000, 88.000000

Am I simply misunderstanding the function? If so, how could I implement this to determine the height of the text when constrained to a certain width?


问:
FusedLocationProviderClient not sending location updates
I try to use new simplified Location APIs on Android (introduced in GPS 11.0). I wrote a Service that implements location APIs. But it only triggers and send location for a few seconds (only 2 times).

```<code>    public class LocationService extends Service {
    public static final String TAG = makeLogTag("LocationService");

    private static final float LOCATION_TRACKING_MIN_DISTANCE = 15f;
    private static final float ACCEPTED_ACCURACY = 50f;

    private final IBinder mBinder = new LocalBinder();

    // fused location api
    private FusedLocationProviderClient mFusedLocationClient;
    private LocationRequest mLocationRequest;
    private LocationCallback mLocationCallback;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate");
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        createLocationCallback();
        createLocationRequest();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand");
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            stopSelf();
            return START_NOT_STICKY;
        }

        getLastKnownLocation();
        startPeriodicLocationUpdate();

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopPeriodicLocationUpdate();
        Log.i(TAG, "onDestroy - Estou sendo destruido ");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    private void getLastKnownLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        mFusedLocationClient.getLastLocation()
                .addOnCompleteListener(task -> {
                    if (task.isSuccessful() && task.getResult() != null) {
                        Location lastLocation = task.getResult();
                        storeLocation(lastLocation);
                    }
                });
    }

    private void createLocationRequest() {
        mLocationRequest = new LocationRequest()
                .setInterval(TimeUnit.SECONDS.toMillis(Params.getAgentLocationTrackingUpdateInterval()))
                .setFastestInterval(TimeUnit.SECONDS.toMillis(Params.getAgentLocationTrackingUpdateInterval()))
                .setExpirationDuration(TimeUnit.SECONDS.toMillis(10))
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    private void createLocationCallback() {
        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                Location location = locationResult.getLastLocation();
                if (location != null) {
                    storeLocation(location);
                }

                Log.i(TAG, "locationResult start");
                for (Location location1 : locationResult.getLocations()) {
                    Log.i(TAG, "locationResult location " + location1.getLatitude() + " " + location1.getLongitude() + " " + location1.getAccuracy() + " " + location1.getProvider());
                }
                Log.i(TAG, "locationResult stop");
            }
        };
    }

    private void startPeriodicLocationUpdate() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        Log.i(TAG, "periodic update");
        mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
    }

    private void stopPeriodicLocationUpdate() {
        mFusedLocationClient.removeLocationUpdates(mLocationCallback)
                .addOnCompleteListener(task -> LOGI(TAG, "removed location updates!"));
    }

    private void storeLocation(Location location) {
        Log.i(TAG, "periodic location " + location.getLatitude() + " " + location.getLongitude() + " " + location.getAccuracy() + " " + location.getProvider());
        if (location.getAccuracy() <= ACCEPTED_ACCURACY) {
            Log.i(TAG, "storeLocation: " + "saved!");
            AgentLocationVo agentLocation = new AgentLocationVo();
            agentLocation.setDate(DateHelper.getDate(location.getTime()));
            agentLocation.setLatitude(location.getLatitude());
            agentLocation.setLongitude(location.getLongitude());
            agentLocation.setAccuracy(location.getAccuracy());
            agentLocation.setSyncState(SyncState.NOTUPLOADED);
            if (!AgentLocationDao.isAgentLocationExist(agentLocation))
                AgentLocationDao.insert(agentLocation);
        }
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Log.i(TAG, "onTaskRemoved: ");
        stopSelf();
        JobDispatcher.stopSendLocationJob(getApplicationContext()); // TODO: 04/07/17 not the best place for it
    }

    public static void start(Context context) {
        context.startService(new Intent(context, LocationService.class));
    }

    public static void stop(Context context) {
        context.stopService(new Intent(context, LocationService.class));
    }

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
        public LocationService getService() {
            // Return this instance of LocationService so clients can call public methods
            return LocationService.this;
        }
    }
}
</code>```

Here are the resource that I used to create the service:
https://android-developers.googleblog.com/2017/06/reduce-friction-with-new-location-apis.html

https://github.com/googlesamples/android-play-location/blob/master/LocationUpdates/app/src/main/java/com/google/android/gms/location/sample/locationupdates/MainActivity.java

https://blog.stylingandroid.com/locationservices/

I have even tried using version of method with Pending intent, but get the same result. Even when app is in foreground.

答:
The reason is this line</p>

```<code>  .setExpirationDuration(TimeUnit.SECONDS.toMillis(10))
</code>```

Body:
I try to use new simplified Location APIs on Android (introduced in GPS 11.0). I wrote a Service that implements location APIs. But it only triggers and send location for a few seconds (only 2 times).

    public class LocationService extends Service {
    public static final String TAG = makeLogTag("LocationService");

    private static final float LOCATION_TRACKING_MIN_DISTANCE = 15f;
    private static final float ACCEPTED_ACCURACY = 50f;

    private final IBinder mBinder = new LocalBinder();

    // fused location api
    private FusedLocationProviderClient mFusedLocationClient;
    private LocationRequest mLocationRequest;
    private LocationCallback mLocationCallback;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate");
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        createLocationCallback();
        createLocationRequest();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand");
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            stopSelf();
            return START_NOT_STICKY;
        }

        getLastKnownLocation();
        startPeriodicLocationUpdate();

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopPeriodicLocationUpdate();
        Log.i(TAG, "onDestroy - Estou sendo destruido ");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    private void getLastKnownLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        mFusedLocationClient.getLastLocation()
                .addOnCompleteListener(task -> {
                    if (task.isSuccessful() && task.getResult() != null) {
                        Location lastLocation = task.getResult();
                        storeLocation(lastLocation);
                    }
                });
    }

    private void createLocationRequest() {
        mLocationRequest = new LocationRequest()
                .setInterval(TimeUnit.SECONDS.toMillis(Params.getAgentLocationTrackingUpdateInterval()))
                .setFastestInterval(TimeUnit.SECONDS.toMillis(Params.getAgentLocationTrackingUpdateInterval()))
                .setExpirationDuration(TimeUnit.SECONDS.toMillis(10))
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    private void createLocationCallback() {
        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                Location location = locationResult.getLastLocation();
                if (location != null) {
                    storeLocation(location);
                }

                Log.i(TAG, "locationResult start");
                for (Location location1 : locationResult.getLocations()) {
                    Log.i(TAG, "locationResult location " + location1.getLatitude() + " " + location1.getLongitude() + " " + location1.getAccuracy() + " " + location1.getProvider());
                }
                Log.i(TAG, "locationResult stop");
            }
        };
    }

    private void startPeriodicLocationUpdate() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        Log.i(TAG, "periodic update");
        mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
    }

    private void stopPeriodicLocationUpdate() {
        mFusedLocationClient.removeLocationUpdates(mLocationCallback)
                .addOnCompleteListener(task -> LOGI(TAG, "removed location updates!"));
    }

    private void storeLocation(Location location) {
        Log.i(TAG, "periodic location " + location.getLatitude() + " " + location.getLongitude() + " " + location.getAccuracy() + " " + location.getProvider());
        if (location.getAccuracy() <= ACCEPTED_ACCURACY) {
            Log.i(TAG, "storeLocation: " + "saved!");
            AgentLocationVo agentLocation = new AgentLocationVo();
            agentLocation.setDate(DateHelper.getDate(location.getTime()));
            agentLocation.setLatitude(location.getLatitude());
            agentLocation.setLongitude(location.getLongitude());
            agentLocation.setAccuracy(location.getAccuracy());
            agentLocation.setSyncState(SyncState.NOTUPLOADED);
            if (!AgentLocationDao.isAgentLocationExist(agentLocation))
                AgentLocationDao.insert(agentLocation);
        }
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Log.i(TAG, "onTaskRemoved: ");
        stopSelf();
        JobDispatcher.stopSendLocationJob(getApplicationContext()); // TODO: 04/07/17 not the best place for it
    }

    public static void start(Context context) {
        context.startService(new Intent(context, LocationService.class));
    }

    public static void stop(Context context) {
        context.stopService(new Intent(context, LocationService.class));
    }

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
        public LocationService getService() {
            // Return this instance of LocationService so clients can call public methods
            return LocationService.this;
        }
    }
}

Here are the resource that I used to create the service:
https://android-developers.googleblog.com/2017/06/reduce-friction-with-new-location-apis.html

https://github.com/googlesamples/android-play-location/blob/master/LocationUpdates/app/src/main/java/com/google/android/gms/location/sample/locationupdates/MainActivity.java

https://blog.stylingandroid.com/locationservices/

I have even tried using version of method with Pending intent, but get the same result. Even when app is in foreground.

Body:
The reason is this line

  .setExpirationDuration(TimeUnit.SECONDS.toMillis(10))