问:
Why linking and calling a C function with variadic arguments in Rust causes random functions to be called?
I was playing with Rust FFI and I was trying to link printf C function, which has variadic arguments, with my Rust executable. After I ran the executable I witnessed some strange behavior.

This is my Rust code:

use cty::{c_char, c_int};

extern "C" {
    fn printf(format: *const c_char, ...) -> c_int;
}

fn main() {
    unsafe {
        printf("One number: %d\n".as_ptr() as *const i8, 69);
        printf("Two numbers: %d %d\n".as_ptr() as *const i8, 11, 12);
        printf(
            "Three numbers: %d %d %d\n".as_ptr() as *const i8,
            30,
            31,
            32,
        );
    }
}
```
<p>This is the output after running <code>cargo run</code>:</p>
```cargo run
   Compiling c-bindings v0.1.0 (/home/costin/Rust/c-bindings)
    Finished dev [unoptimized + debuginfo] target(s) in 0.20s
     Running `target/debug/c-bindings`
One number: 1
Two numbers: 1 11376
Three numbers: 0 0 0
Two numbers: 11 12
Three numbers: 0 0 56
Three numbers: 30 31 32
```
<p>I looks like the first <code>printf</code> calls the second and the third with random parameters, then the second <code>printf</code> calls the third one with random parameters because the expected output should have been:</p>
```One number: 1
Two numbers: 11 12
Three numbers: 30 31 32
```

Can anyone explain to me why is this strange behavior happening?

答:
Rust strings are not null-terminated like printf expects. You'll need to either manually include \0 at the end of your format strings or use CString:

```<code>printf("One number: %d\n\0".as_ptr() as *const i8, 69);
</code>```
```<code>use std::ffi::CString;
let s = CString::new("One number: %d\n").unwrap();
printf(s.as_ptr(), 69);
</code>```

Body:
I was playing with Rust FFI and I was trying to link printf C function, which has variadic arguments, with my Rust executable. After I ran the executable I witnessed some strange behavior.

This is my Rust code:

use cty::{c_char, c_int};

extern "C" {
    fn printf(format: *const c_char, ...) -> c_int;
}

fn main() {
    unsafe {
        printf("One number: %d\n".as_ptr() as *const i8, 69);
        printf("Two numbers: %d %d\n".as_ptr() as *const i8, 11, 12);
        printf(
            "Three numbers: %d %d %d\n".as_ptr() as *const i8,
            30,
            31,
            32,
        );
    }
}

This is the output after running cargo run:

cargo run
   Compiling c-bindings v0.1.0 (/home/costin/Rust/c-bindings)
    Finished dev [unoptimized + debuginfo] target(s) in 0.20s
     Running `target/debug/c-bindings`
One number: 1
Two numbers: 1 11376
Three numbers: 0 0 0
Two numbers: 11 12
Three numbers: 0 0 56
Three numbers: 30 31 32

I looks like the first printf calls the second and the third with random parameters, then the second printf calls the third one with random parameters because the expected output should have been:

One number: 1
Two numbers: 11 12
Three numbers: 30 31 32

Can anyone explain to me why is this strange behavior happening?

Body:
Rust strings are not null-terminated like printf expects. You'll need to either manually include \0 at the end of your format strings or use CString:

printf("One number: %d\n\0".as_ptr() as *const i8, 69);

use std::ffi::CString;
let s = CString::new("One number: %d\n").unwrap();
printf(s.as_ptr(), 69);


来源: stackexchange

问:
Deselect selected rows from ag grid angular
Is there any grid api to deselect ag-grid selected rows programatically?
I'm trying to perform some operation on the selected row, basically an async operation , after which I need to deselect this row from the grid .</p>

答:
I believe it is weird but setting rowDeselection to true didn't work for me. What I wanted was simple: Being able to deselect a row when it was selected already. So I checked the Row Selection section of AG Grid's documentation and I find this:

rowMultiSelectWithClick: ... Clicking a selected row in this mode will deselect the row.

Huh! Yeah that sounds like what I need! But I don't want multiple selection...! I want single selection ONLY. So I thought maybe setting rowSelection to single will fix it and the selection will be single and deselectable. And... yes it works! The reason I was in doubt initially when doing this is using "rowMultiSelectWithClick" together with "single rowSelection" sounds contradictory, but it works anyways and this is the thing that matters really! :)
So e.g., if you're using it in React (quite similar in Angular or Vanilla JavaScript), just add:

<AgGridReact
    rowSelection="single"
    rowMultiSelectWithClick={true}
    //...
>
```

ContentLicense: CC BY-SA 4.0


问:
Getting status callback on twilio voice calls and call in-progress duration
Im creating an andoid app with twilio calling capability. I have a python backend to handle incoming and outgoing requests. I've created a Twiml app to handle outgoing calls, including the call status.

Also I've configured the phone numbers to handle incoming calls including call status as below:

So the way it works is:

outgoing:
Android app call -> twilio -> python backend -> twilio -> callee

inbound:
caller -> twilio -> python backend -> twilio -> android app

On android, I'm using the following method to initiate the voice call:

```<code>params.put("to", dialledNumber);
ConnectOptions connectOptions = new ConnectOptions.Builder(callingLCNToken).params(params).build();
activeCall = Voice.connect(VoiceActivity.this, connectOptions, callListener);
</code>```

On the python side, I have the following sample code to handle outgoing calls:

```<code>resp = VoiceResponse()
_to = request.values.get("to")
_from = request.values['From'].split(":")[1]
resp.dial(callerId=_from).number(_to)
return str(resp)
</code>```

But I can't still capture the statuses: busy, no-answer, cancelled, failed as mentioned in this doc: https://support.twilio.com/hc/en-us/articles/223132547-What-are-the-Possible-Call-Statuses-and-What-do-They-Mean-

Also I want to get the during of call in-progress. But with the current status callback, it seems i'm getting the total time from call initialisation and completion.

I tried using StatusCallbackEvent and the callback URL there, but it didn't work either.

What should I do to get the correct call statuses and the call in-progress duration?

答:
Twilio developer evangelist here.

I think the status callback URL you set up in the number admin is for inbound calls. You should set status callback URLs for outbound calls on the <Number> TwiML like this:

resp = VoiceResponse()
_to = request.values.get("to")
_from = request.values['From'].split(":")[1]
dial = resp.dial(callerId=_from)
dial.number(
  _to,
  status_callback_event='initiated ringing answered completed',
  status_callback='https://example.com/callStatus'
)
return str(resp)
```

Body:
Im creating an andoid app with twilio calling capability. I have a python backend to handle incoming and outgoing requests. I've created a Twiml app to handle outgoing calls, including the call status.

Also I've configured the phone numbers to handle incoming calls including call status as below:

So the way it works is:

outgoing:
Android app call -> twilio -> python backend -> twilio -> callee

inbound:
caller -> twilio -> python backend -> twilio -> android app

On android, I'm using the following method to initiate the voice call:

params.put("to", dialledNumber);
ConnectOptions connectOptions = new ConnectOptions.Builder(callingLCNToken).params(params).build();
activeCall = Voice.connect(VoiceActivity.this, connectOptions, callListener);

On the python side, I have the following sample code to handle outgoing calls:

resp = VoiceResponse()
_to = request.values.get("to")
_from = request.values['From'].split(":")[1]
resp.dial(callerId=_from).number(_to)
return str(resp)

But I can't still capture the statuses: busy, no-answer, cancelled, failed as mentioned in this doc: https://support.twilio.com/hc/en-us/articles/223132547-What-are-the-Possible-Call-Statuses-and-What-do-They-Mean-

Also I want to get the during of call in-progress. But with the current status callback, it seems i'm getting the total time from call initialisation and completion.

I tried using StatusCallbackEvent and the callback URL there, but it didn't work either.

What should I do to get the correct call statuses and the call in-progress duration?


问:
Help Rounding division
I need the end result to be a whole number.  If the division is a whole number fine but if it ends up with a decimal, I need to round up (midpoint).

Example if the division is 85.5, round up and result should be 86
If the division is 85.4, it would naturally round down ...basic rounding rules
If it's a whole number 85, then we're all good but should I store the result regardless of these 3 situations as type double?

```<code>double totalFoundPercent = Math.Round(
        (double) (totalNumbersDeleted / (totalNumbers - totalNumbersApproved)),
                  MidpointRounding.AwayFromZero);
</code>```

This is giving me an error of:

The call is ambiguous between the following methods or properties:
  'System.Math.Round(double, System.MidpointRounding)'  and
  'System.Math.Round(decimal, System.MidpointRounding)'

So I am not sure if this should be stored as a type double in the end or not plus the problem with the error.

答:
Get rid of the second parameter. Based on your description, you shouldn't need it.</p>

```<code>double totalFoundPercent = Math.Round((double) (totalNumbersDeleted / (totalNumbers - totalNumbersApproved)));
</code>```

ContentLicense: CC BY-SA 3.0

Title: Help Rounding division

Body:
I need the end result to be a whole number.  If the division is a whole number fine but if it ends up with a decimal, I need to round up (midpoint).

Example if the division is 85.5, round up and result should be 86
If the division is 85.4, it would naturally round down ...basic rounding rules
If it's a whole number 85, then we're all good but should I store the result regardless of these 3 situations as type double?

double totalFoundPercent = Math.Round(
        (double) (totalNumbersDeleted / (totalNumbers - totalNumbersApproved)),
                  MidpointRounding.AwayFromZero);

This is giving me an error of:

The call is ambiguous between the following methods or properties:
  'System.Math.Round(double, System.MidpointRounding)'  and
  'System.Math.Round(decimal, System.MidpointRounding)'

So I am not sure if this should be stored as a type double in the end or not plus the problem with the error.

Body:
Get rid of the second parameter. Based on your description, you shouldn't need it.

double totalFoundPercent = Math.Round((double) (totalNumbersDeleted / (totalNumbers - totalNumbersApproved)));


问:
How to expose data to watch face manually triggered
I'm new to Android Wear OS. I would like to expose numeric data (0,1,2,3,...,9) to an Android Smartwatch's data field (triggered manually without tapping on the data field).

As described here,

https://developer.android.com/codelabs/data-providers#0

I already implemented the onReceive() / onComplicationUpdate() methods:

```<code>public class ComplicationTapBroadcastReceiver extends BroadcastReceiver {

private static final String EXTRA_PROVIDER_COMPONENT =
        "com.example.android.wearable.watchface.provider.action.PROVIDER_COMPONENT";
private static final String EXTRA_COMPLICATION_ID =
        "com.example.android.wearable.watchface.provider.action.COMPLICATION_ID";

static final int MAX_NUMBER = 20;
static final String COMPLICATION_PROVIDER_PREFERENCES_FILE_KEY =
        "com.example.android.wearable.watchface.COMPLICATION_PROVIDER_PREFERENCES_FILE_KEY";

@Override
public void onReceive(Context context, Intent intent) {
    Bundle extras = intent.getExtras();
    ComponentName provider = extras.getParcelable(EXTRA_PROVIDER_COMPONENT);
    int complicationId = extras.getInt(EXTRA_COMPLICATION_ID);

    // Retrieve data via SharedPreferences.
    String preferenceKey = getPreferenceKey(provider, complicationId);
    SharedPreferences sharedPreferences =
            context.getSharedPreferences(COMPLICATION_PROVIDER_PREFERENCES_FILE_KEY, 0);

    int value = sharedPreferences.getInt(preferenceKey, 0);

    // Update data for complication.
    value = (value + 1) % MAX_NUMBER;

    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt(preferenceKey, value);
    editor.apply();

    // Request an update for the complication that has just been tapped.
    ProviderUpdateRequester requester = new ProviderUpdateRequester(context, provider);
    requester.requestUpdate(complicationId);
}

/**
 * Returns a pending intent, suitable for use as a tap intent, that causes a complication to be
 * toggled and updated.
 */
static PendingIntent getToggleIntent(
        Context context, ComponentName provider, int complicationId) {
    Intent intent = new Intent(context, ComplicationTapBroadcastReceiver.class);
    intent.putExtra(EXTRA_PROVIDER_COMPONENT, provider);
    intent.putExtra(EXTRA_COMPLICATION_ID, complicationId);

    // Pass complicationId as the requestCode to ensure that different complications get
    // different intents.
    return PendingIntent.getBroadcast(
            context, complicationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

/**
 * Returns the key for the shared preference used to hold the current state of a given
 * complication.
 */
static String getPreferenceKey(ComponentName provider, int complicationId) {
    return provider.getClassName() + complicationId;
}
}
</code>```

```<code>public class CustomComplicationProviderService extends ComplicationProviderService {

private static final String TAG = "ComplicationProvider";

/*
 * Called when a complication has been activated. The method is for any one-time
 * (per complication) set-up.
 *
 * You can continue sending data for the active complicationId until onComplicationDeactivated()
 * is called.
 */
@Override
public void onComplicationActivated(
        int complicationId, int dataType, ComplicationManager complicationManager) {
    Log.d(TAG, "onComplicationActivated(): " + complicationId);
}

/*
 * Called when the complication needs updated data from your provider. There are four scenarios
 * when this will happen:
 *
 *   1. An active watch face complication is changed to use this provider
 *   2. A complication using this provider becomes active
 *   3. The period of time you specified in the manifest has elapsed (UPDATE_PERIOD_SECONDS)
 *   4. You triggered an update from your own class via the
 *       ProviderUpdateRequester.requestUpdate() method.
 */
@Override
public void onComplicationUpdate(
        int complicationId, int dataType, ComplicationManager complicationManager) {
    Log.d(TAG, "onComplicationUpdate() id: " + complicationId);

    // Create Tap Action so that the user can trigger an update by tapping the complication.
    ComponentName thisProvider = new ComponentName(this, getClass());
    // We pass the complication id, so we can only update the specific complication tapped.
    PendingIntent complicationPendingIntent =
            ComplicationTapBroadcastReceiver.getToggleIntent(
                    this, thisProvider, complicationId);

    // Retrieves your data, in this case, we grab an incrementing number from SharedPrefs.
    SharedPreferences preferences =
            getSharedPreferences(
                    ComplicationTapBroadcastReceiver.COMPLICATION_PROVIDER_PREFERENCES_FILE_KEY,
                    0);
    int number =
            preferences.getInt(
                    ComplicationTapBroadcastReceiver.getPreferenceKey(
                            thisProvider, complicationId),
                    0);
    String numberText = String.format(Locale.getDefault(), "%d!", number);

    ComplicationData complicationData = null;

    switch (dataType) {
        case ComplicationData.TYPE_SHORT_TEXT:
            complicationData =
                    new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
                            .setShortText(ComplicationText.plainText(numberText))
                            .setTapAction(complicationPendingIntent)
                            .build();
            break;
        case ComplicationData.TYPE_LONG_TEXT:
            complicationData =
                    new ComplicationData.Builder(ComplicationData.TYPE_LONG_TEXT)
                            .setLongText(ComplicationText.plainText("Number: " + numberText))
                            .setTapAction(complicationPendingIntent)
                            .build();
            break;
        case ComplicationData.TYPE_RANGED_VALUE:
            complicationData =
                    new ComplicationData.Builder(ComplicationData.TYPE_RANGED_VALUE)
                            .setValue(number)
                            .setMinValue(0)
                            .setMaxValue(ComplicationTapBroadcastReceiver.MAX_NUMBER)
                            .setShortText(ComplicationText.plainText(numberText))
                            .setTapAction(complicationPendingIntent)
                            .build();
            break;
        default:
            if (Log.isLoggable(TAG, Log.WARN)) {
                Log.w(TAG, "Unexpected complication type " + dataType);
            }
    }

    if (complicationData != null) {
        complicationManager.updateComplicationData(complicationId, complicationData);

    } else {
        // If no data is sent, we still need to inform the ComplicationManager, so the update
        // job can finish and the wake lock isn't held any longer than necessary.
        complicationManager.noUpdateRequired(complicationId);
    }
}

/*
 * Called when the complication has been deactivated.
 */
@Override
public void onComplicationDeactivated(int complicationId) {
    Log.d(TAG, "onComplicationDeactivated(): " + complicationId);
}
}
</code>```

The code is running, but...

a) How is it possible to update the display of my Smartwatch's data field with my sensor's information, without tapping on the data field of my Smartwatch? Is it even possible?

b) How do I have to configure AndroidManifest.xml, and how do I need to implement the ProviderUpdateRequester method requestUpdateAll() in my Java application to trigger the display update manually?

```<code>new ProviderUpdateRequester(context, new ComponentName(context, "myComplicationClass"))
        .requestUpdateAll();
</code>```

What is "context" in my case, and what is "myComplicationClass"?

Unfortunately, I haven't found any good code example yet...

答:
To update your complication with your sensor value, you have to store it using shared preferences. Do this inside onSensorChanged of your SensorEventListener.

    @Override
    public void onSensorChanged(SensorEvent event) {
        String heartrate = Integer.toString(Math.round(event.values[0]));

        getSharedPreferences("callItWhatEverYouWant", 0).edit().putString("heartrate", heartrate).apply();

        ComponentName providerComponentName = new ComponentName(this, CustomComplicationProviderService.class);
        ProviderUpdateRequester providerUpdateRequester = new ProviderUpdateRequester(this, providerComponentName);
        providerUpdateRequester.requestUpdateAll();
    }
```
<p>Currently you are getting a number from shared preferences and convert it into numberText. Replace this with your sensor value shared preference defined earlier.</p>
<pre class="lang-java prettyprint-override"><code>@Override
public void onComplicationUpdate(
        int complicationId, int dataType, ComplicationManager complicationManager) {
    Log.d(TAG, "onComplicationUpdate() id: " + complicationId);

    // Create Tap Action so that the user can trigger an update by tapping the complication.
    ComponentName thisProvider = new ComponentName(this, getClass());
    // We pass the complication id, so we can only update the specific complication tapped.
    PendingIntent complicationPendingIntent =
            ComplicationTapBroadcastReceiver.getToggleIntent(
                    this, thisProvider, complicationId);

    // Retrieve your sensor value
    String heartrate = getSharedPreferences("callItWhatEverYouWant", 0).getString("heartrate", "--");

    ComplicationData complicationData = null;

    switch (dataType) {
        case ComplicationData.TYPE_SHORT_TEXT:
            complicationData =
                    new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
                            .setShortText(ComplicationText.plainText(heartrate))
                            .setTapAction(complicationPendingIntent)
                            .build();
            break;
        case ComplicationData.TYPE_LONG_TEXT:
            complicationData =
                    new ComplicationData.Builder(ComplicationData.TYPE_LONG_TEXT)
                            .setLongText(ComplicationText.plainText("Heart Rate: " + heartrate))
                            .setTapAction(complicationPendingIntent)
                            .build();
            break;
        case ComplicationData.TYPE_RANGED_VALUE:
            complicationData =
                    new ComplicationData.Builder(ComplicationData.TYPE_RANGED_VALUE)
                            .setValue(Integer.parseInt(heartrate))
                            .setMinValue(0)
                            .setMaxValue(ComplicationTapBroadcastReceiver.MAX_NUMBER)
                            .setShortText(ComplicationText.plainText(heartrate))
                            .setTapAction(complicationPendingIntent)
                            .build();
            break;
        default:
            if (Log.isLoggable(TAG, Log.WARN)) {
                Log.w(TAG, "Unexpected complication type " + dataType);
            }
    }

    if (complicationData != null) {
        complicationManager.updateComplicationData(complicationId, complicationData);

    } else {
        // If no data is sent, we still need to inform the ComplicationManager, so the update
        // job can finish and the wake lock isn't held any longer than necessary.
        complicationManager.noUpdateRequired(complicationId);
    }
}
</code>```

Manifest...

        <service
            android:name=".CustomComplicationProviderService"
            android:exported="true"
            android:icon="@drawable/ic_heart"
            android:label="Current Heartrate"
            android:permission="com.google.android.wearable.permission.BIND_COMPLICATION_PROVIDER">
            <intent-filter>
                <action
                    android:name="android.support.wearable.complications.ACTION_COMPLICATION_UPDATE_REQUEST"/>
            </intent-filter>

            <meta-data
                android:name="android.support.wearable.complications.SUPPORTED_TYPES"
                android:value="RANGED_VALUE,SHORT_TEXT,LONG_TEXT"/>

            <meta-data
                android:name="android.support.wearable.complications.UPDATE_PERIOD_SECONDS"
                android:value="0" />
        </service>
```

Body:
I'm new to Android Wear OS. I would like to expose numeric data (0,1,2,3,...,9) to an Android Smartwatch's data field (triggered manually without tapping on the data field).

As described here,

https://developer.android.com/codelabs/data-providers#0

I already implemented the onReceive() / onComplicationUpdate() methods:

public class ComplicationTapBroadcastReceiver extends BroadcastReceiver {

private static final String EXTRA_PROVIDER_COMPONENT =
        "com.example.android.wearable.watchface.provider.action.PROVIDER_COMPONENT";
private static final String EXTRA_COMPLICATION_ID =
        "com.example.android.wearable.watchface.provider.action.COMPLICATION_ID";

static final int MAX_NUMBER = 20;
static final String COMPLICATION_PROVIDER_PREFERENCES_FILE_KEY =
        "com.example.android.wearable.watchface.COMPLICATION_PROVIDER_PREFERENCES_FILE_KEY";

@Override
public void onReceive(Context context, Intent intent) {
    Bundle extras = intent.getExtras();
    ComponentName provider = extras.getParcelable(EXTRA_PROVIDER_COMPONENT);
    int complicationId = extras.getInt(EXTRA_COMPLICATION_ID);

    // Retrieve data via SharedPreferences.
    String preferenceKey = getPreferenceKey(provider, complicationId);
    SharedPreferences sharedPreferences =
            context.getSharedPreferences(COMPLICATION_PROVIDER_PREFERENCES_FILE_KEY, 0);

    int value = sharedPreferences.getInt(preferenceKey, 0);

    // Update data for complication.
    value = (value + 1) % MAX_NUMBER;

    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt(preferenceKey, value);
    editor.apply();

    // Request an update for the complication that has just been tapped.
    ProviderUpdateRequester requester = new ProviderUpdateRequester(context, provider);
    requester.requestUpdate(complicationId);
}

/**
 * Returns a pending intent, suitable for use as a tap intent, that causes a complication to be
 * toggled and updated.
 */
static PendingIntent getToggleIntent(
        Context context, ComponentName provider, int complicationId) {
    Intent intent = new Intent(context, ComplicationTapBroadcastReceiver.class);
    intent.putExtra(EXTRA_PROVIDER_COMPONENT, provider);
    intent.putExtra(EXTRA_COMPLICATION_ID, complicationId);

    // Pass complicationId as the requestCode to ensure that different complications get
    // different intents.
    return PendingIntent.getBroadcast(
            context, complicationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

/**
 * Returns the key for the shared preference used to hold the current state of a given
 * complication.
 */
static String getPreferenceKey(ComponentName provider, int complicationId) {
    return provider.getClassName() + complicationId;
}
}

public class CustomComplicationProviderService extends ComplicationProviderService {

private static final String TAG = "ComplicationProvider";

/*
 * Called when a complication has been activated. The method is for any one-time
 * (per complication) set-up.
 *
 * You can continue sending data for the active complicationId until onComplicationDeactivated()
 * is called.
 */
@Override
public void onComplicationActivated(
        int complicationId, int dataType, ComplicationManager complicationManager) {
    Log.d(TAG, "onComplicationActivated(): " + complicationId);
}

/*
 * Called when the complication needs updated data from your provider. There are four scenarios
 * when this will happen:
 *
 *   1. An active watch face complication is changed to use this provider
 *   2. A complication using this provider becomes active
 *   3. The period of time you specified in the manifest has elapsed (UPDATE_PERIOD_SECONDS)
 *   4. You triggered an update from your own class via the
 *       ProviderUpdateRequester.requestUpdate() method.
 */
@Override
public void onComplicationUpdate(
        int complicationId, int dataType, ComplicationManager complicationManager) {
    Log.d(TAG, "onComplicationUpdate() id: " + complicationId);

    // Create Tap Action so that the user can trigger an update by tapping the complication.
    ComponentName thisProvider = new ComponentName(this, getClass());
    // We pass the complication id, so we can only update the specific complication tapped.
    PendingIntent complicationPendingIntent =
            ComplicationTapBroadcastReceiver.getToggleIntent(
                    this, thisProvider, complicationId);

    // Retrieves your data, in this case, we grab an incrementing number from SharedPrefs.
    SharedPreferences preferences =
            getSharedPreferences(
                    ComplicationTapBroadcastReceiver.COMPLICATION_PROVIDER_PREFERENCES_FILE_KEY,
                    0);
    int number =
            preferences.getInt(
                    ComplicationTapBroadcastReceiver.getPreferenceKey(
                            thisProvider, complicationId),
                    0);
    String numberText = String.format(Locale.getDefault(), "%d!", number);

    ComplicationData complicationData = null;

    switch (dataType) {
        case ComplicationData.TYPE_SHORT_TEXT:
            complicationData =
                    new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
                            .setShortText(ComplicationText.plainText(numberText))
                            .setTapAction(complicationPendingIntent)
                            .build();
            break;
        case ComplicationData.TYPE_LONG_TEXT:
            complicationData =
                    new ComplicationData.Builder(ComplicationData.TYPE_LONG_TEXT)
                            .setLongText(ComplicationText.plainText("Number: " + numberText))
                            .setTapAction(complicationPendingIntent)
                            .build();
            break;
        case ComplicationData.TYPE_RANGED_VALUE:
            complicationData =
                    new ComplicationData.Builder(ComplicationData.TYPE_RANGED_VALUE)
                            .setValue(number)
                            .setMinValue(0)
                            .setMaxValue(ComplicationTapBroadcastReceiver.MAX_NUMBER)
                            .setShortText(ComplicationText.plainText(numberText))
                            .setTapAction(complicationPendingIntent)
                            .build();
            break;
        default:
            if (Log.isLoggable(TAG, Log.WARN)) {
                Log.w(TAG, "Unexpected complication type " + dataType);
            }
    }

    if (complicationData != null) {
        complicationManager.updateComplicationData(complicationId, complicationData);

    } else {
        // If no data is sent, we still need to inform the ComplicationManager, so the update
        // job can finish and the wake lock isn't held any longer than necessary.
        complicationManager.noUpdateRequired(complicationId);
    }
}

/*
 * Called when the complication has been deactivated.
 */
@Override
public void onComplicationDeactivated(int complicationId) {
    Log.d(TAG, "onComplicationDeactivated(): " + complicationId);
}
}

The code is running, but...

a) How is it possible to update the display of my Smartwatch's data field with my sensor's information, without tapping on the data field of my Smartwatch? Is it even possible?

b) How do I have to configure AndroidManifest.xml, and how do I need to implement the ProviderUpdateRequester method requestUpdateAll() in my Java application to trigger the display update manually?

new ProviderUpdateRequester(context, new ComponentName(context, "myComplicationClass"))
        .requestUpdateAll();

What is "context" in my case, and what is "myComplicationClass"?

Unfortunately, I haven't found any good code example yet...

Body:
To update your complication with your sensor value, you have to store it using shared preferences. Do this inside onSensorChanged of your SensorEventListener.

    @Override
    public void onSensorChanged(SensorEvent event) {
        String heartrate = Integer.toString(Math.round(event.values[0]));

        getSharedPreferences("callItWhatEverYouWant", 0).edit().putString("heartrate", heartrate).apply();

        ComponentName providerComponentName = new ComponentName(this, CustomComplicationProviderService.class);
        ProviderUpdateRequester providerUpdateRequester = new ProviderUpdateRequester(this, providerComponentName);
        providerUpdateRequester.requestUpdateAll();
    }

Currently you are getting a number from shared preferences and convert it into numberText. Replace this with your sensor value shared preference defined earlier.

@Override
public void onComplicationUpdate(
        int complicationId, int dataType, ComplicationManager complicationManager) {
    Log.d(TAG, "onComplicationUpdate() id: " + complicationId);

    // Create Tap Action so that the user can trigger an update by tapping the complication.
    ComponentName thisProvider = new ComponentName(this, getClass());
    // We pass the complication id, so we can only update the specific complication tapped.
    PendingIntent complicationPendingIntent =
            ComplicationTapBroadcastReceiver.getToggleIntent(
                    this, thisProvider, complicationId);

    // Retrieve your sensor value
    String heartrate = getSharedPreferences("callItWhatEverYouWant", 0).getString("heartrate", "--");

    ComplicationData complicationData = null;

    switch (dataType) {
        case ComplicationData.TYPE_SHORT_TEXT:
            complicationData =
                    new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
                            .setShortText(ComplicationText.plainText(heartrate))
                            .setTapAction(complicationPendingIntent)
                            .build();
            break;
        case ComplicationData.TYPE_LONG_TEXT:
            complicationData =
                    new ComplicationData.Builder(ComplicationData.TYPE_LONG_TEXT)
                            .setLongText(ComplicationText.plainText("Heart Rate: " + heartrate))
                            .setTapAction(complicationPendingIntent)
                            .build();
            break;
        case ComplicationData.TYPE_RANGED_VALUE:
            complicationData =
                    new ComplicationData.Builder(ComplicationData.TYPE_RANGED_VALUE)
                            .setValue(Integer.parseInt(heartrate))
                            .setMinValue(0)
                            .setMaxValue(ComplicationTapBroadcastReceiver.MAX_NUMBER)
                            .setShortText(ComplicationText.plainText(heartrate))
                            .setTapAction(complicationPendingIntent)
                            .build();
            break;
        default:
            if (Log.isLoggable(TAG, Log.WARN)) {
                Log.w(TAG, "Unexpected complication type " + dataType);
            }
    }

    if (complicationData != null) {
        complicationManager.updateComplicationData(complicationId, complicationData);

    } else {
        // If no data is sent, we still need to inform the ComplicationManager, so the update
        // job can finish and the wake lock isn't held any longer than necessary.
        complicationManager.noUpdateRequired(complicationId);
    }
}

Manifest...

        <service
            android:name=".CustomComplicationProviderService"
            android:exported="true"
            android:icon="@drawable/ic_heart"
            android:label="Current Heartrate"
            android:permission="com.google.android.wearable.permission.BIND_COMPLICATION_PROVIDER">
            <intent-filter>
                <action
                    android:name="android.support.wearable.complications.ACTION_COMPLICATION_UPDATE_REQUEST"/>
            </intent-filter>

            <meta-data
                android:name="android.support.wearable.complications.SUPPORTED_TYPES"
                android:value="RANGED_VALUE,SHORT_TEXT,LONG_TEXT"/>

            <meta-data
                android:name="android.support.wearable.complications.UPDATE_PERIOD_SECONDS"
                android:value="0" />
        </service>


问:
Python: remove brackets of list elements while printing pandas dataframe
I have a pandas dataframe of this kind

```<code>d = {'col1': [1, [2,3]], 'col2': [[3,4,5], 4]}
d = pd.DataFrame(d)
print(d)
</code>```

output:

```<code>     col1       col2
0       1  [3, 4, 5]
1  [2, 3]          4
</code>```

what is the best way to remove the brackets of all the list elements while printing this dataframe?

答:
The very same idea as @adhg’s answer but we could also do:</p>
```<code>df = d.astype(str).apply(lambda col: col.str.strip('[]'))
</code>```

Body:
I have a pandas dataframe of this kind

d = {'col1': [1, [2,3]], 'col2': [[3,4,5], 4]}
d = pd.DataFrame(d)
print(d)

output:

     col1       col2
0       1  [3, 4, 5]
1  [2, 3]          4

what is the best way to remove the brackets of all the list elements while printing this dataframe?

Body:
The very same idea as @adhg’s answer but we could also do:

df = d.astype(str).apply(lambda col: col.str.strip('[]'))


问:
script run from IDE, but not from git-bash terminal
I am running a python script from the IDE and it works well, however when calling it from the git-bash terminal the following errors showed.

```<code>./main.py: line 2: import: command not found
./main.py: line 3: import: command not found
./main.py: line 5: syntax error near unexpected token `'I am in main 1''
./main.py: line 5: `print('I am in main 1')'
</code>```

In git-bash I run the chmod u+x main.py and chmod +x main.py lines, but it still does not work.

I am using VScode as my IDE with python3.7.9 as the interpreter, I am calling the script from the direction where it is placed in the terminal, and the script that I am testing is the following:

```<code>#!/bin/bash
import os
import sys

print('I am in main 1')
</code>```

I have changed the first line for #!/bin/bash/python and #!/bin/bash/env python3... didn't work. I would appreciate it if someone could tell me what I miss or what I am doing wrong. I am new in git or using the terminal, any tip would be appreciated.

Thanks in advance.

答:
Not sure if you made the error in typing this question or if it's also like this in your script, but you should have #!/usr/bin/python3 or #!/bin/python3 for your system to know to execute it as a python script.

As it stands, your system is trying to execute it as a shell script with bash, which would explain why the import statements aren't being recognized.

Body:
I am running a python script from the IDE and it works well, however when calling it from the git-bash terminal the following errors showed.

./main.py: line 2: import: command not found
./main.py: line 3: import: command not found
./main.py: line 5: syntax error near unexpected token `'I am in main 1''
./main.py: line 5: `print('I am in main 1')'

In git-bash I run the chmod u+x main.py and chmod +x main.py lines, but it still does not work.

I am using VScode as my IDE with python3.7.9 as the interpreter, I am calling the script from the direction where it is placed in the terminal, and the script that I am testing is the following:

#!/bin/bash
import os
import sys

print('I am in main 1')

I have changed the first line for #!/bin/bash/python and #!/bin/bash/env python3... didn't work. I would appreciate it if someone could tell me what I miss or what I am doing wrong. I am new in git or using the terminal, any tip would be appreciated.

Thanks in advance.


问:
Count with conditional in pandas
i'm having a problem trying to count diferents variables for the same Name. The thing is: i have a sheet with the Name of all my workers and i need to count how many trainings they had, but thoses trainings have different classifications: "Comercial", "Funcional" and others...

One of my columns is "Name" and the other is "Trainings". How can i filter those trainings and aggregate per name

```<code>   import pandas as pd
   import numpy as np

   xls = pd.ExcelFile('BASE_Indicadores_treinamento_2021 - V3.xlsx')

   df = pd.read_excel(xls, 'Base')
   display(df)

   df2 = df.groupby("Nome").agg({'Eixo':'count'}).reset_index()
   display(df2)
</code>```

What im getting is the TOTAL of trainings per Name, but i need the count of all categories i have in trainings (there are 5 of them). Does anyone know what i need to do?

Thankss

答:
df.groupby("Nome").agg('count') should give you the total number of training for each person.
df.groupby(["Nome","Eixo"]).agg({'Eixo':'count'}) should give you the count per each person per each training.

Title: Count with conditional in pandas

Body:
i'm having a problem trying to count diferents variables for the same Name. The thing is: i have a sheet with the Name of all my workers and i need to count how many trainings they had, but thoses trainings have different classifications: "Comercial", "Funcional" and others...

One of my columns is "Name" and the other is "Trainings". How can i filter those trainings and aggregate per name

   import pandas as pd
   import numpy as np

   xls = pd.ExcelFile('BASE_Indicadores_treinamento_2021 - V3.xlsx')

   df = pd.read_excel(xls, 'Base')
   display(df)

   df2 = df.groupby("Nome").agg({'Eixo':'count'}).reset_index()
   display(df2)

What im getting is the TOTAL of trainings per Name, but i need the count of all categories i have in trainings (there are 5 of them). Does anyone know what i need to do?

Thankss


问:
Testing a custom Wordpress theme with a different, existing database
I'm designing a blog test theme for a client, and before switching over to this theme, I need to tweak the design to accomodate his current content (spacing, sizing, etc.). I'm trying to import their database into my test theme's database to test, but I'm getting an error: "Cannot establish database connection". I am testing from my own domain/server, and I used HostGator's Fantastico Deluxe and PhpMyAdmin to create the blog and upload the databases. All materials have been backed up.

Here's my process:

Dropped all tables from the test theme's db

Imported client's existing db into the test theme's db

Replaced the test theme's wp-config.php file with existing db's wp-config.php info (mainly db_user and db_password)

What am I missing in order to make the client's existing database display correctly with this test theme?

Thanks for your time.

答:
Make sure that in your cPanel / Plesk account, you have added  the name of Database, the User and Password. Furthermore, you should connect the user with the database you have already created and give to this user all the privilages. So for example, inside your client's wp-config.php file if you have:

```<code>define('DB_NAME', 'database_name');
define('DB_USER', 'database_user_name');
define('DB_PASSWORD', 'user_password');
</code>```

youu should have all these created in your server account

Thus if your are in cPanel account go to "MySQL® Databases" create all the above and you will be ready to go!

Careful though, sometimes Mysql has already a prefix at the database name. Thus, you may need to change the define variables inside wp-config.php file

Body:
Make sure that in your cPanel / Plesk account, you have added  the name of Database, the User and Password. Furthermore, you should connect the user with the database you have already created and give to this user all the privilages. So for example, inside your client's wp-config.php file if you have:

define('DB_NAME', 'database_name');
define('DB_USER', 'database_user_name');
define('DB_PASSWORD', 'user_password');

youu should have all these created in your server account

Thus if your are in cPanel account go to "MySQL® Databases" create all the above and you will be ready to go!

Careful though, sometimes Mysql has already a prefix at the database name. Thus, you may need to change the define variables inside wp-config.php file


问:
Lucene highlighter hits all terms
Here is the situation.

There is a field named "content" in the Lucene index document, and the "content" in each document has two values. For example:

document1 - content: "gas and oil", "energy"

document2 - content: "gas", "oil"

When I search "content:(+gas +oil)", both document1 and document2 are returned, that is expected.

The next step, I want to loop each content values for the hits,

"gas and oil"

"energy"

"gas"

"oil"

I used the highlighter, the purpose is to get "gas and oil" be returned because only this one "gas and oil" hit this query "(+gas +oil)".

But I actually get

"gas and oil"

"gas"

"oil"

It seems that the query does not work on the highlighter, so when I use the query "(+gas +oil)" or the query "(gas oil)" to highlight, there is not much difference.

Did I use highlighter wrong? Is there a way to only get  "gas and oil"?

Code example I used

```<code>for (final String value : values) {
    final QueryScorer scorer = new QueryScorer(query);
    final Highlighter highlighter = new Highlighter(scorer);
    highlighter.setTextFragmenter(new SimpleFragmenter(2000));
    final TokenStream tokenStream = analyzer.tokenStream(field, new StringReader(value));
    final CachingTokenFilter filter = new CachingTokenFilter(tokenStream);
    final String highlightedText = highlighter.getBestFragment(filter, value);
    if (StringUtils.isNotBlank(highlightedText)) {
      //TODO
    }
}
</code>```

Thanks in advance

答:
Highlighter is based on term, so the best way to solve this problem is to rebuild the index and organize it in a different way, that is:

```<code>document1 - content: "gas and oil"
document2 - content: "energy"
document3 - content: "gas"
document4 - content: "oil"
</code>```

Therefore, when searching for "content:(+gas +oil)", only document1 will be hit.

Title: Lucene highlighter hits all terms

Body:
Here is the situation.

There is a field named "content" in the Lucene index document, and the "content" in each document has two values. For example:

document1 - content: "gas and oil", "energy"

document2 - content: "gas", "oil"

When I search "content:(+gas +oil)", both document1 and document2 are returned, that is expected.

The next step, I want to loop each content values for the hits,

"gas and oil"

"energy"

"gas"

"oil"

I used the highlighter, the purpose is to get "gas and oil" be returned because only this one "gas and oil" hit this query "(+gas +oil)".

But I actually get

"gas and oil"

"gas"

"oil"

It seems that the query does not work on the highlighter, so when I use the query "(+gas +oil)" or the query "(gas oil)" to highlight, there is not much difference.

Did I use highlighter wrong? Is there a way to only get  "gas and oil"?

Code example I used

for (final String value : values) {
    final QueryScorer scorer = new QueryScorer(query);
    final Highlighter highlighter = new Highlighter(scorer);
    highlighter.setTextFragmenter(new SimpleFragmenter(2000));
    final TokenStream tokenStream = analyzer.tokenStream(field, new StringReader(value));
    final CachingTokenFilter filter = new CachingTokenFilter(tokenStream);
    final String highlightedText = highlighter.getBestFragment(filter, value);
    if (StringUtils.isNotBlank(highlightedText)) {
      //TODO
    }
}

Thanks in advance

Body:
Highlighter is based on term, so the best way to solve this problem is to rebuild the index and organize it in a different way, that is:

document1 - content: "gas and oil"
document2 - content: "energy"
document3 - content: "gas"
document4 - content: "oil"

Therefore, when searching for "content:(+gas +oil)", only document1 will be hit.


问:
SwiftUI getby UUID
I'm pretty new to SwiftUI so I'm hoping someone can help me out here.
I have a UUID and I am trying to save content into that specific object, but I do not know how to call the object, like with a getbyid or something.

```<code>struct Game: Identifiable, Codable {
    let id: UUID
    var title: String
    var players: [Player]
}
extension Game {
    struct Player: Identifiable, Codable {
        let id: UUID
        var name: String
        var score: [Int32]
    }
}
</code>```

used this code in my program

```<code>@Binding var game: Game
saveScoreToPlayer(game: $game, playerID: player.id, score: Int32)

func saveScoreToPlayer(game: Game, playerID: Game.Player.ID, score: Int32) {
    //save score to player obviously doesn't work
    game.playerID.insert(score at:0)
}
</code>```

答:
You can use the firstIndex(of:) method to get the position of the first element of the array that matches playerID.

You can try this:

```<code>func saveScoreToPlayer(game: Game, playerID: Game.Player.ID, score: Int32) {
    if let index = game.players.firstIndex(where: { $0.id == playerID }) {
        game.players[index].score.insert(score, at: 0)
    } else {
        // handle error here
    }
}
</code>```

Documentation

Title: SwiftUI getby UUID

Body:
I'm pretty new to SwiftUI so I'm hoping someone can help me out here.
I have a UUID and I am trying to save content into that specific object, but I do not know how to call the object, like with a getbyid or something.

struct Game: Identifiable, Codable {
    let id: UUID
    var title: String
    var players: [Player]
}
extension Game {
    struct Player: Identifiable, Codable {
        let id: UUID
        var name: String
        var score: [Int32]
    }
}

used this code in my program

@Binding var game: Game
saveScoreToPlayer(game: $game, playerID: player.id, score: Int32)

func saveScoreToPlayer(game: Game, playerID: Game.Player.ID, score: Int32) {
    //save score to player obviously doesn't work
    game.playerID.insert(score at:0)
}

Body:
You can use the firstIndex(of:) method to get the position of the first element of the array that matches playerID.

You can try this:

func saveScoreToPlayer(game: Game, playerID: Game.Player.ID, score: Int32) {
    if let index = game.players.firstIndex(where: { $0.id == playerID }) {
        game.players[index].score.insert(score, at: 0)
    } else {
        // handle error here
    }
}

Documentation


问:
How is relation between question and answer in CosmosDB
I am trying to do a basic question-answer web app without authentication by using ASP.Net5 MVC and Cosmos DB. I am able to do CRUD on question model. I guess I should do with 2 containers and Join operation but I can't include the other container. Here is my appsetting.json

"CosmosDb": {
  "Account": "",
  "Key": "",
  "DatabaseName": "ToDoList",
  "ContainerName": "Items"
}
```

答:
There is no possibility to do joins between containers in CosmosDB

Read here

Azure Cosmos DB’s JOIN supports intra-document and self-joins. Azure Cosmos DB does not support JOINs across documents or containers.

If you want to join data you have to eighter store both types of data in one container with a good partitioning strategy.

Second option is to read data from one and read from the other collection and then do joins in memory.