问:
Backing up my local database on google drive always creates a different file id
I am creating a to-do list app with flutter, and I want my users to be able to back-up their tasks on google drive.
This is the code I'm using:

```<code>// Create the file we want to upload.
ga.File fileToUpload = ga.File();
var file = await _localFile;
fileToUpload.parents = ["appDataFolder"];
fileToUpload.name = path.basename(file.absolute.path);

// Create a new back-up file on google drive.
var response = await drive.files.create(
  fileToUpload,
  uploadMedia: ga.Media(file.openRead(), file.lengthSync()),
);

// Get the file id.
   fileId = response.id;
</code>```

The problem is that every time I get a different file id and I need to retrieve the file
from google drive with the same file id all the time and not with a different id every time.

I've tried using the update method instead of the create method:

```<code>ga.File fileToUpload = ga.File();
var file = await _localFile;
fileToUpload.parents = ["appDataFolder"];
fileToUpload.name = path.basename(file.absolute.path);
drive.files.update(fileToUpload, fileId);
</code>```

But I get Unhandled Exception: DetailedApiRequestError(status: 403, message: The parents field is not directly writable in update requests. Use the addParents and removeParents parameters instead.)

I also tried to set the file id before using the create method:

```<code>fileToUpload.id = fileId;
      await drive.files.create(
        fileToUpload,
        uploadMedia: ga.Media(file.openRead(), file.lengthSync()),
      );
</code>```

But then I get Unhandled Exception: DetailedApiRequestError(status: 400, message: The provided file ID is not usable.)
Or that a file with that id is already exists.

So I've tried to delete the file from google drive and then create it again with the same id:

```<code>fileToUpload.id = fileId;
  drive.files.get(fileId).then((value) {
    if (value != null) {
      drive.files.delete(fileId).then((value) {
        drive.files.create(
          fileToUpload,
          uploadMedia: ga.Media(file.openRead(), file.lengthSync()),
        );
      });
    } else {
      drive.files.create(
        fileToUpload,
        uploadMedia: ga.Media(file.openRead(), file.lengthSync()),
      );
    }
  });
</code>```

But then I also get Unhandled Exception: DetailedApiRequestError(status: 400, message: The provided file ID is not usable.)
Even though I'm using the same file id given by google drive for the original file.

Any solution?

答: If you want to set the id of the file you have to use a generated id from google. That's why you're getting the provided file ID is not usable. Theres's a class you can use called generateIds which you can use to create id's that can be used with create requests as you've done above. The Google Drive API developer website has a tool where you can make requests to the api. It's called "Try it now"(like postman)  For example, create the list of ids(just press execute) here. Pick one of the ids and add it to the request body (in the request body box on the left side , press the plus sign to get the id key and add the generatedId) here . You should get a 200 response with the id you sent with the request. It will also return a specific error message that you can handle if the id already exists (code 409)

Body:
I am creating a to-do list app with flutter, and I want my users to be able to back-up their tasks on google drive.
This is the code I'm using:

// Create the file we want to upload.
ga.File fileToUpload = ga.File();
var file = await _localFile;
fileToUpload.parents = ["appDataFolder"];
fileToUpload.name = path.basename(file.absolute.path);

// Create a new back-up file on google drive.
var response = await drive.files.create(
  fileToUpload,
  uploadMedia: ga.Media(file.openRead(), file.lengthSync()),
);

// Get the file id.
   fileId = response.id;

The problem is that every time I get a different file id and I need to retrieve the file
from google drive with the same file id all the time and not with a different id every time.

I've tried using the update method instead of the create method:

ga.File fileToUpload = ga.File();
var file = await _localFile;
fileToUpload.parents = ["appDataFolder"];
fileToUpload.name = path.basename(file.absolute.path);
drive.files.update(fileToUpload, fileId);

But I get Unhandled Exception: DetailedApiRequestError(status: 403, message: The parents field is not directly writable in update requests. Use the addParents and removeParents parameters instead.)

I also tried to set the file id before using the create method:

fileToUpload.id = fileId;
      await drive.files.create(
        fileToUpload,
        uploadMedia: ga.Media(file.openRead(), file.lengthSync()),
      );

But then I get Unhandled Exception: DetailedApiRequestError(status: 400, message: The provided file ID is not usable.)
Or that a file with that id is already exists.

So I've tried to delete the file from google drive and then create it again with the same id:

fileToUpload.id = fileId;
  drive.files.get(fileId).then((value) {
    if (value != null) {
      drive.files.delete(fileId).then((value) {
        drive.files.create(
          fileToUpload,
          uploadMedia: ga.Media(file.openRead(), file.lengthSync()),
        );
      });
    } else {
      drive.files.create(
        fileToUpload,
        uploadMedia: ga.Media(file.openRead(), file.lengthSync()),
      );
    }
  });

But then I also get Unhandled Exception: DetailedApiRequestError(status: 400, message: The provided file ID is not usable.)
Even though I'm using the same file id given by google drive for the original file.

Any solution?


来源: stackexchange

问:
How to rename a header and add values (to this column) based on other header name?
I have multiple Pandas dataframes like this one (for different years):

df1=

```<code>        Unnamed: 0           b      c     Monthly Flow (2018)
1              nan   -0.041619  43.91               -0.041619
2              nan    0.011913  43.91               -0.041619
3              nan   -0.048801  43.91               -0.041619
4              nan    0.002857  43.91               -0.041619
5              nan    0.002204  43.91               -0.041619
6              nan   -0.007692  43.91               -0.041619
7              nan   -0.014992  43.91               -0.041619
8              nan   -0.035381  43.91               -0.041619
</code>```

And I would like to assign to the nan the year in the Monthly Flow (2018) column, thus achieving this output:

```<code>       Year           b      c     Monthly Flow (2018)
1      2018   -0.041619  43.91               -0.041619
2      2018    0.011913  43.91               -0.041619
3      2018   -0.048801  43.91               -0.041619
4      2018    0.002857  43.91               -0.041619
5      2018    0.002204  43.91               -0.041619
6      2018   -0.007692  43.91               -0.041619
7      2018   -0.014992  43.91               -0.041619
8      2018   -0.035381  43.91               -0.041619
</code>```

I know how to replace these nan by a specific year, one dataframe at a time.

But, since I have a lot of dataframes (and will have more in the future), I would like to know a way to do this automatically, for example by extracting the year value from column Monthly Flow (2018).

答:
Assuming Monthly flow is always the 5th column, you can do it like this:

```<code>import re
df = df.rename(columns={'Unnamed: 0': 'Year'})
df.iloc[:,0] = re.search('\d{4}', df.columns[4]).group(0)
</code>```

Explanation:

re.search looks for 4 numbers in a row and extracts them from the fifth column.

I rename the Unnamed column as Year.

Working code:

```<code>import pandas as pd
import numpy as np
import re
df = pd.DataFrame({'Unnamed: 0': {0: np.nan},
 'a': {0: 1},
 'a2': {0: 1},
 'a3': {0: 1},
 'Monthly Flow (2018)': {0: 'b'}})
df = df.rename(columns={'Unnamed: 0': 'Year'})
df.iloc[:,0] = re.search('\d{4}', df.columns[4]).group(0)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have multiple Pandas dataframes like this one (for different years):

df1=

        Unnamed: 0           b      c     Monthly Flow (2018)
1              nan   -0.041619  43.91               -0.041619
2              nan    0.011913  43.91               -0.041619
3              nan   -0.048801  43.91               -0.041619
4              nan    0.002857  43.91               -0.041619
5              nan    0.002204  43.91               -0.041619
6              nan   -0.007692  43.91               -0.041619
7              nan   -0.014992  43.91               -0.041619
8              nan   -0.035381  43.91               -0.041619

And I would like to assign to the nan the year in the Monthly Flow (2018) column, thus achieving this output:

       Year           b      c     Monthly Flow (2018)
1      2018   -0.041619  43.91               -0.041619
2      2018    0.011913  43.91               -0.041619
3      2018   -0.048801  43.91               -0.041619
4      2018    0.002857  43.91               -0.041619
5      2018    0.002204  43.91               -0.041619
6      2018   -0.007692  43.91               -0.041619
7      2018   -0.014992  43.91               -0.041619
8      2018   -0.035381  43.91               -0.041619

I know how to replace these nan by a specific year, one dataframe at a time.

But, since I have a lot of dataframes (and will have more in the future), I would like to know a way to do this automatically, for example by extracting the year value from column Monthly Flow (2018).

Body:
Assuming Monthly flow is always the 5th column, you can do it like this:

import re
df = df.rename(columns={'Unnamed: 0': 'Year'})
df.iloc[:,0] = re.search('\d{4}', df.columns[4]).group(0)

Explanation:

re.search looks for 4 numbers in a row and extracts them from the fifth column.

I rename the Unnamed column as Year.

Working code:

import pandas as pd
import numpy as np
import re
df = pd.DataFrame({'Unnamed: 0': {0: np.nan},
 'a': {0: 1},
 'a2': {0: 1},
 'a3': {0: 1},
 'Monthly Flow (2018)': {0: 'b'}})
df = df.rename(columns={'Unnamed: 0': 'Year'})
df.iloc[:,0] = re.search('\d{4}', df.columns[4]).group(0)


问:
Is it possible to start a brodacast receiver from android WorkManager class in Java/Kotlin
I am stuck with one question for more than one month now. I want to start a broadcast receiver from an Android  WorkManager class. I want to receive/filter all incoming text messages and then post to a server. However, my current solution cannot work for many hours before the android system kills the app and the receiver sync stops, or by the time I extract the text message from the PDU object (coming from telephone Intent) is onReceive method has already returned.
Therefore to solve this I wish to keep broadcast onReceive method running inside a WorkManager to ensure the process does not terminate so fast.  I have tried reading but I am not getting the kind of solution that works well with me, or maybe there is something not clear to me about the Broadcast Receiver or how android background processes work.
This is my current implementation.
Below is the onReceive() method as implemented on the MessageReceiver that extends BroadcastReceiver </p>

```<code>    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onReceive(final Context context, Intent intent) {
        this.context= context;
        if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
           final Bundle data = intent.getExtras();

            if (data !=null ) {
                try {
                    final Object[] pdusObj = (Object[]) data.get("pdus");
                    if (pdusObj != null) {
                        for (int i = 0; i < pdusObj.length; i++) {
                            SmsMessage currentMessage =
                                    SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                            Log.d(TAG, "run: currentMessage: " + currentMessage);

                            Log.d(TAG, "passReceivedMsg: handleMessage: message " + currentMessage);

                            int msgNo = counter++;
                            msgID = "SMS_ID_0" + msgNo;
                            sender = currentMessage.getDisplayOriginatingAddress();
                            text_message = currentMessage.getDisplayMessageBody();

                            long timestampMilliseconds = System.currentTimeMillis();
                            timestamp = formatter.format(timestampMilliseconds);

                            Data.Builder dataBuilder = new Data.Builder();
                            dataBuilder.putString("sender",sender);
                            dataBuilder.putString("message",text_message);
                            dataBuilder.putString("timestamp",timestamp);
                            dataBuilder.putString("sms_id",msgID);
//                            Log.d(TAG, "onReceive:  key:" +key+ " and keyValue "+data.get(key));

                            WorkManager mWorkManager = WorkManager.getInstance();
                            OneTimeWorkRequest mRequest = new OneTimeWorkRequest
                                    .Builder(MessageSyncWorker.class)
                                    .setInputData(dataBuilder.build())
                                    .build();
                            mWorkManager.enqueue(mRequest);
                        }
                    }
                }
                catch (Exception e){
                    Log.d(TAG, "onReceive: Exception occured "+e.getMessage());
                }
            }

       }

    }
</code>```

<p>Below is my  MessageSyncWorker class that extends the Worker- doWork ()method </p>

```<code>@NonNull
@Override
public Result doWork() {

Data inputData1 = getInputData();

sender = inputData1.getString("sender");
text_message = inputData1.getString("message");
timestamp = inputData1.getString("timestamp");
msgID = inputData1.getString("sms_id");
Log.d(TAG, "doWork: Mesage "+text_message);

SharedPreferences sharedPreferences =
        PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
BASE_API_URL = sharedPreferences.getString("settings_server_url", "");

Log.d(TAG, "doWork: BASE URL "+BASE_API_URL);

try {
    //here I upload the data to the server
    uploadMessageData();
} catch (JSONException e) {
    e.printStackTrace();
    Log.d(TAG, "doWork: uploadMessage method Exception "+e.getMessage());
}

return Result.success();
}
</code>```

答:
Finally, I have cracked it after a detailed discussion as can be seen in the comments area (for this question). I now have working code, and I trust by sharing I can help someone else stuck with similar. Below is how I did it.

here is the onReceive() method;

```<code> @Override
    public void onReceive(Context context, Intent intent) {
        if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION
                .equals(intent.getAction())){
            this.context = context;
            SmsMessage smsMessage = null;
            StringBuilder fullMessage = new StringBuilder();
            for (SmsMessage new_smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)){
                smsMessage = new_smsMessage;
                fullMessage.append(smsMessage.getDisplayMessageBody());
            }
            if (smsMessage ==null){
                return;
            }

            String sender = smsMessage.getOriginatingAddress();
            long timestampMilliseconds = System.currentTimeMillis();
            String timestamp = formatter.format(timestampMilliseconds);

            Log.d("NeTxt Receiver ", "onReceive: fullMessage: "+fullMessage);

            Data.Builder dataBuilder = new Data.Builder();
            dataBuilder.putString("fullMessage",fullMessage.toString());
            dataBuilder.putString("sender", sender);

            dataBuilder.putString("timestamp",timestamp);

            //defining constraints
            Constraints task_constraints = new Constraints.Builder()
                    .setRequiredNetworkType(NetworkType.CONNECTED)
                    .build();

            //scheduling the work
            WorkManager mWorkManager = WorkManager.getInstance();
            OneTimeWorkRequest mRequest = new OneTimeWorkRequest
                    .Builder(NewTxtWorker.class)
                    .setInputData(dataBuilder.build())
                    .setConstraints(task_constraints)
                    .build();
            mWorkManager.enqueue(mRequest);

            mWorkManager.getWorkInfoById(mRequest.getId());

        }

    }
</code>```

below is my doWork() method;

```<code>@NonNull
@Override
public Result doWork() {

    Data inputData = getInputData();
    String sender = inputData.getString("sender");
    String text_message = inputData.getString("fullMessage");
    String timestamp = inputData.getString("timestamp");

    Log.d("Txt WorkManager", "doWork: fullmessage: "+text_message);

    assert sender != null;
    assert text_message != null;
    if (!timestamp.isEmpty()||
            !sender.isEmpty()||
            !text_message.isEmpty()){

        FirebaseFirestore fireDb = FirebaseFirestore.getInstance();
        Map<String, Object> message = new HashMap<>();
        message.put("text_message", text_message);
        message.put("sender", sender);
        message.put("timestamp", timestamp);
        //sync the received message with the firebase firestore db
        fireDb.collection("text_messages")
                .add(message)
                .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                    @Override
                    public void onSuccess(DocumentReference documentReference) {
                        Log.d("Txt WorkManager", "onSuccess: doc Id"
                                +documentReference.getId());
                    }
                })
               .addOnFailureListener(new OnFailureListener() {
                   @Override
                   public void onFailure(@NonNull Exception e) {
                       Log.d("Txt WorkManager", "onFailure: "+e.getMessage());
                   }
               }) ;

    }

    return Result.failure();
}
</code>```

Body:
I am stuck with one question for more than one month now. I want to start a broadcast receiver from an Android  WorkManager class. I want to receive/filter all incoming text messages and then post to a server. However, my current solution cannot work for many hours before the android system kills the app and the receiver sync stops, or by the time I extract the text message from the PDU object (coming from telephone Intent) is onReceive method has already returned.
Therefore to solve this I wish to keep broadcast onReceive method running inside a WorkManager to ensure the process does not terminate so fast.  I have tried reading but I am not getting the kind of solution that works well with me, or maybe there is something not clear to me about the Broadcast Receiver or how android background processes work.
This is my current implementation.
Below is the onReceive() method as implemented on the MessageReceiver that extends BroadcastReceiver

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onReceive(final Context context, Intent intent) {
        this.context= context;
        if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
           final Bundle data = intent.getExtras();

            if (data !=null ) {
                try {
                    final Object[] pdusObj = (Object[]) data.get("pdus");
                    if (pdusObj != null) {
                        for (int i = 0; i < pdusObj.length; i++) {
                            SmsMessage currentMessage =
                                    SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                            Log.d(TAG, "run: currentMessage: " + currentMessage);

                            Log.d(TAG, "passReceivedMsg: handleMessage: message " + currentMessage);

                            int msgNo = counter++;
                            msgID = "SMS_ID_0" + msgNo;
                            sender = currentMessage.getDisplayOriginatingAddress();
                            text_message = currentMessage.getDisplayMessageBody();

                            long timestampMilliseconds = System.currentTimeMillis();
                            timestamp = formatter.format(timestampMilliseconds);

                            Data.Builder dataBuilder = new Data.Builder();
                            dataBuilder.putString("sender",sender);
                            dataBuilder.putString("message",text_message);
                            dataBuilder.putString("timestamp",timestamp);
                            dataBuilder.putString("sms_id",msgID);
//                            Log.d(TAG, "onReceive:  key:" +key+ " and keyValue "+data.get(key));

                            WorkManager mWorkManager = WorkManager.getInstance();
                            OneTimeWorkRequest mRequest = new OneTimeWorkRequest
                                    .Builder(MessageSyncWorker.class)
                                    .setInputData(dataBuilder.build())
                                    .build();
                            mWorkManager.enqueue(mRequest);
                        }
                    }
                }
                catch (Exception e){
                    Log.d(TAG, "onReceive: Exception occured "+e.getMessage());
                }
            }

       }

    }

Below is my  MessageSyncWorker class that extends the Worker- doWork ()method

@NonNull
@Override
public Result doWork() {

Data inputData1 = getInputData();

sender = inputData1.getString("sender");
text_message = inputData1.getString("message");
timestamp = inputData1.getString("timestamp");
msgID = inputData1.getString("sms_id");
Log.d(TAG, "doWork: Mesage "+text_message);

SharedPreferences sharedPreferences =
        PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
BASE_API_URL = sharedPreferences.getString("settings_server_url", "");

Log.d(TAG, "doWork: BASE URL "+BASE_API_URL);

try {
    //here I upload the data to the server
    uploadMessageData();
} catch (JSONException e) {
    e.printStackTrace();
    Log.d(TAG, "doWork: uploadMessage method Exception "+e.getMessage());
}

return Result.success();
}

Body:
Finally, I have cracked it after a detailed discussion as can be seen in the comments area (for this question). I now have working code, and I trust by sharing I can help someone else stuck with similar. Below is how I did it.

here is the onReceive() method;

 @Override
    public void onReceive(Context context, Intent intent) {
        if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION
                .equals(intent.getAction())){
            this.context = context;
            SmsMessage smsMessage = null;
            StringBuilder fullMessage = new StringBuilder();
            for (SmsMessage new_smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)){
                smsMessage = new_smsMessage;
                fullMessage.append(smsMessage.getDisplayMessageBody());
            }
            if (smsMessage ==null){
                return;
            }

            String sender = smsMessage.getOriginatingAddress();
            long timestampMilliseconds = System.currentTimeMillis();
            String timestamp = formatter.format(timestampMilliseconds);

            Log.d("NeTxt Receiver ", "onReceive: fullMessage: "+fullMessage);

            Data.Builder dataBuilder = new Data.Builder();
            dataBuilder.putString("fullMessage",fullMessage.toString());
            dataBuilder.putString("sender", sender);

            dataBuilder.putString("timestamp",timestamp);

            //defining constraints
            Constraints task_constraints = new Constraints.Builder()
                    .setRequiredNetworkType(NetworkType.CONNECTED)
                    .build();

            //scheduling the work
            WorkManager mWorkManager = WorkManager.getInstance();
            OneTimeWorkRequest mRequest = new OneTimeWorkRequest
                    .Builder(NewTxtWorker.class)
                    .setInputData(dataBuilder.build())
                    .setConstraints(task_constraints)
                    .build();
            mWorkManager.enqueue(mRequest);

            mWorkManager.getWorkInfoById(mRequest.getId());

        }

    }

below is my doWork() method;

@NonNull
@Override
public Result doWork() {

    Data inputData = getInputData();
    String sender = inputData.getString("sender");
    String text_message = inputData.getString("fullMessage");
    String timestamp = inputData.getString("timestamp");

    Log.d("Txt WorkManager", "doWork: fullmessage: "+text_message);

    assert sender != null;
    assert text_message != null;
    if (!timestamp.isEmpty()||
            !sender.isEmpty()||
            !text_message.isEmpty()){

        FirebaseFirestore fireDb = FirebaseFirestore.getInstance();
        Map<String, Object> message = new HashMap<>();
        message.put("text_message", text_message);
        message.put("sender", sender);
        message.put("timestamp", timestamp);
        //sync the received message with the firebase firestore db
        fireDb.collection("text_messages")
                .add(message)
                .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                    @Override
                    public void onSuccess(DocumentReference documentReference) {
                        Log.d("Txt WorkManager", "onSuccess: doc Id"
                                +documentReference.getId());
                    }
                })
               .addOnFailureListener(new OnFailureListener() {
                   @Override
                   public void onFailure(@NonNull Exception e) {
                       Log.d("Txt WorkManager", "onFailure: "+e.getMessage());
                   }
               }) ;

    }

    return Result.failure();
}


问:
MongoDB GridFS VS Directly disk IO
Use MongoDB GridFS store images and images stored directly on disk What are the advantages?</p>

答:
Main advantage in my opinion is easy files distribution across multiple servers when system start growing (sharding, replication).

Easy improvement reads/writes speed.

No need to care where to put new file.

Files systems become slow with big amount of small files.

ContentLicense: CC BY-SA 3.0

Title: MongoDB GridFS VS Directly disk IO


问:
ClickOnce with non renferenced dll
Im trying to create a ClickOnce application that needs some dlls, that can't be referenced, added on it's instalation folder for it to work.

I'm currently using a post-build event to get those dlls when in debug mode:

```<code>xcopy /y /d  "$(ProjectDir)..\libraries\$(PlatformName)\*.dll" "$(TargetDir)"
</code>```

But obviously on the installer it doesn't take those dlls into account, which means that when I try to run the program it fails to run the methods that come from those dlls, since it needs those dlls.

Is there a way to send those dlls in the ClickOnce Instalation?

I've been searching for a way to do this, but haven't found any clear solution, if this question is a duplicate, please reference the other question.

答: So I managed to make this work by literally just adding the dlls to the project, I didn't reference them, just added them and they now go with the installer.</p>

Title: ClickOnce with non renferenced dll

Body:
Im trying to create a ClickOnce application that needs some dlls, that can't be referenced, added on it's instalation folder for it to work.

I'm currently using a post-build event to get those dlls when in debug mode:

xcopy /y /d  "$(ProjectDir)..\libraries\$(PlatformName)\*.dll" "$(TargetDir)"

But obviously on the installer it doesn't take those dlls into account, which means that when I try to run the program it fails to run the methods that come from those dlls, since it needs those dlls.

Is there a way to send those dlls in the ClickOnce Instalation?

I've been searching for a way to do this, but haven't found any clear solution, if this question is a duplicate, please reference the other question.


问:
How to get params in react hooks component?
For class component there is "this.props.route.params" option. How to get params from one screen to other screen in react hook functional component.</p>

```<code>"react": "16.11.0",
"react-native": "0.62.2",
"react-navigation": "@react-navigation/native": "^5.1.2",
</code>```

答:
You can use the hook useRouter from @react-navigation/native

```<code>import * as React from 'react';
import { Text } from 'react-native';
import { useRoute } from '@react-navigation/native';

function MyText() {
  const route = useRoute();

  return <Text>{route.params.caption}</Text>;
}
</code>```

Body:
For class component there is "this.props.route.params" option. How to get params from one screen to other screen in react hook functional component.

"react": "16.11.0",
"react-native": "0.62.2",
"react-navigation": "@react-navigation/native": "^5.1.2",

Body:
You can use the hook useRouter from @react-navigation/native

import * as React from 'react';
import { Text } from 'react-native';
import { useRoute } from '@react-navigation/native';

function MyText() {
  const route = useRoute();

  return <Text>{route.params.caption}</Text>;
}


问:
How to plot an RGB image using the image() function from a 3D array?
I have an array with dimension (28,28,3) height, width, depth. Each depth is one of the RGB channels. The values are between 0 and 1.

I want to use the image() function to plot the image. The z argument is a matrix. How can I convert the array into a matrix in order to be able to plot?

My final goal is to have something like this but with color images.

答:
One approach is with rasterImage

```<code>set.seed(3)
data <- replicate(4,array(data = runif(28*28*3,0,1),
                          dim = c(28,28,3)), simplify = FALSE)

par(mfrow=c(2, 2), mar=c(0, 0, 3, 0))
sapply(seq_along(data), function(x){
  plot.new()
  rasterImage(data[[x]], xleft = 0, xright = 1,
            ytop = 0, ybottom = 1, interpolate = FALSE)
  title(paste0("Plot ",x))
})
</code>```

Body:
One approach is with rasterImage

set.seed(3)
data <- replicate(4,array(data = runif(28*28*3,0,1),
                          dim = c(28,28,3)), simplify = FALSE)

par(mfrow=c(2, 2), mar=c(0, 0, 3, 0))
sapply(seq_along(data), function(x){
  plot.new()
  rasterImage(data[[x]], xleft = 0, xright = 1,
            ytop = 0, ybottom = 1, interpolate = FALSE)
  title(paste0("Plot ",x))
})


问:
is rowversion a transactionally-consistent value to capture table data changes
If an ETL process attempts to detect data changes on system-versioned tables in SQL Server by including rows as defined by a rowversion column to be within a rowversion "delta window", e.g.:

where row_version >= @previous_etl_cycle_rowversion
  and row_version < @current_etl_cycle_rowversion
```

<p>.. and the values for <code>@previous_etl_cycle_rowversion</code> and <code>@current_etl_cycle_rowversion</code> are selected from a logging table whose newest <code>rowversion</code> gets appended to said logging table at the start of each ETL cycle via:</p>

```insert into etl_cycle_logged_rowversion_marker (cycle_start_row_version)
select @@DBTS
```

... is it possible that a rowversion of a record falling within a given "delta window" (bounded by the 2 @@DBTS values) could be missed/skipped due to rowversion's behavior vis-à-vis transactional consistency? - i.e., is it possible that rowversion would be reflected on a basis of "eventual" consistency?

I'm thinking of a case where say, 1000 records are updated within a single transaction and somehow @@DBTS is "ahead" of the record's committed rowversion yet that specific version of the record is not yet readable...

(For the sake of scoping the question, please exclude any cases of deleted records or immediately consecutive updates on a given record within such a large batch transaction.)

答: Under SNAPSHOT isolation, it turns out the proper function to inspect rowversion which will ensure contiguous delta windows while not skipping rowversion values attached to long-running transactions is MIN_ACTIVE_ROWVERSION() rather than @@DBTS.

Body:
If an ETL process attempts to detect data changes on system-versioned tables in SQL Server by including rows as defined by a rowversion column to be within a rowversion "delta window", e.g.:

where row_version >= @previous_etl_cycle_rowversion
  and row_version < @current_etl_cycle_rowversion

.. and the values for @previous_etl_cycle_rowversion and @current_etl_cycle_rowversion are selected from a logging table whose newest rowversion gets appended to said logging table at the start of each ETL cycle via:

insert into etl_cycle_logged_rowversion_marker (cycle_start_row_version)
select @@DBTS

... is it possible that a rowversion of a record falling within a given "delta window" (bounded by the 2 @@DBTS values) could be missed/skipped due to rowversion's behavior vis-à-vis transactional consistency? - i.e., is it possible that rowversion would be reflected on a basis of "eventual" consistency?

I'm thinking of a case where say, 1000 records are updated within a single transaction and somehow @@DBTS is "ahead" of the record's committed rowversion yet that specific version of the record is not yet readable...

(For the sake of scoping the question, please exclude any cases of deleted records or immediately consecutive updates on a given record within such a large batch transaction.)


问:
Do something every time a list length increases by a certain amount
I want my code to take a break every time one of my list (tumblr or save) reaches 300 entries (ie: 300, 600, 900, etc.)

This is my code:

```<code>tumblr = []
for half_hour in range(start_ts, until_ts, (60*30)):
    save = []
    try:
        data = client.tagged("fanart", before=half_hour)
            save.append(list([row[4], row[8], row[0], title, desc, url, row[5]]))
            print(row[8], title)
        if (len(tumblr) % 300 == 0) or (len(save) % 300 == 0):
            sauvegarde()
            time.sleep(60)
</code>```

I didn't put the whole script but tumblr gets filled later on in the script so at first the list has zero entry.

The problem I seem to have is that it starts right away with zero. Is there a way to disregard zero in this logic ?

Thanks

答:
I would try changing the conditional to add len(tumblr) != 0, like this:

```<code>if (len(tumblr) != 0 and (len(tumblr) % 300 == 0) or (len(save) % 300 == 0)):
    sauvegarde()
    time.sleep(60)
</code>```

I hope this helps.

Body:
I want my code to take a break every time one of my list (tumblr or save) reaches 300 entries (ie: 300, 600, 900, etc.)

This is my code:

tumblr = []
for half_hour in range(start_ts, until_ts, (60*30)):
    save = []
    try:
        data = client.tagged("fanart", before=half_hour)
            save.append(list([row[4], row[8], row[0], title, desc, url, row[5]]))
            print(row[8], title)
        if (len(tumblr) % 300 == 0) or (len(save) % 300 == 0):
            sauvegarde()
            time.sleep(60)

I didn't put the whole script but tumblr gets filled later on in the script so at first the list has zero entry.

The problem I seem to have is that it starts right away with zero. Is there a way to disregard zero in this logic ?

Thanks

Body:
I would try changing the conditional to add len(tumblr) != 0, like this:

if (len(tumblr) != 0 and (len(tumblr) % 300 == 0) or (len(save) % 300 == 0)):
    sauvegarde()
    time.sleep(60)

I hope this helps.


问:
How to use bootstrap datepicker
Okay, So I'm new to using frameworks and js libraries and I'm wanting to us bootstrap and bootstrap datepicker for a form and I have no clue if I have the file order correct but the links is how the files are setup, and I know very little about javascript, pretty much all I code in is php but I need this for a form.

Here's my testing form for the bootstrap datepicker:

```<code> <!DOCTYPE html>
 <html>
 <head>
<title>Testing</title>
<meta charset="utf-8">

<link rel="stylesheet" href="_css/datepicker.css">
<link rel="stylesheet" href="_css/bootstrap.css">
<link rel="stylesheet" href="_css/bootstrap-responsive.css">
<script type="text/javascript" src="datepicker/bootstrap-datepicker.js"></script>
 </head>
 <body>
 <center>
      <h1>BootStrap Datepicker</h1>
  <form>
  <div class="well span12 main">
  <input type="text" id="dp1" class="span2 datepicker" placeholder="Date..."
           name="date"> <br>
      </div>
      <input type="submit" value="Search" class="btn">
  </form>
 </center>

<!-- JAVAscript ----------------------------------------------------------------->
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="_js/bootstrap-datepicker.js"></script>
<script type="text/javascript" src="_js/bootstrap.js"></script>
 </body>
 </html>
</code>```

What exactly am I doing wrong?

答:
Couldn't get bootstrap datepicker to work until I wrap the textbox with position relative element as shown here:</p>

```<code><span style="position: relative">
 <input  type="text" placeholder="click to show datepicker"  id="pickyDate"/>
</span>
</code>```

Title: How to use bootstrap datepicker

Body:
Okay, So I'm new to using frameworks and js libraries and I'm wanting to us bootstrap and bootstrap datepicker for a form and I have no clue if I have the file order correct but the links is how the files are setup, and I know very little about javascript, pretty much all I code in is php but I need this for a form.

Here's my testing form for the bootstrap datepicker:

 <!DOCTYPE html>

<title>Testing</title>
<meta charset="utf-8">

<link rel="stylesheet" href="_css/datepicker.css">
<link rel="stylesheet" href="_css/bootstrap.css">
<link rel="stylesheet" href="_css/bootstrap-responsive.css">

BootStrap Datepicker

  <form>

  <input type="text" id="dp1" class="span2 datepicker" placeholder="Date..."
           name="date">

      <input type="submit" value="Search" class="btn">
  </form>

What exactly am I doing wrong?

Body:
Couldn't get bootstrap datepicker to work until I wrap the textbox with position relative element as shown here:

<span style="position: relative">
 <input  type="text" placeholder="click to show datepicker"  id="pickyDate"/>
</span>


问:
How to display different column data as tool tip in ag grid pivot mode?
```<code>var ColDef = [{
    headerName: "colA",
    field: 'colA',
    rowGroup: true
  },
  {
    headerName: "colB",
    field: 'colB',
    pivot: true,
    enablePivot: true
  },
  {
    headerName: "colC",
    field: 'colC',
    rowGroup: true
  },
  {
    field: 'colD',
    aggFunc: 'first',
    valueFormatter: currencyFormatter,
    tooltip: function(params) {
      return (params.valueFormatted);
    },
  },
  {
    field: 'comment'
  },
  {
    field: 'colF'
  }
];
function currencyFormatter(params) {
  return params.value;
}
</code>```

<p>above code is from different question. it works but i want to use different 'comment' field as tool tip to current 'colD' . also this is a group and pivot agGrid,if it is normal grid this is not a problem. I would appreciate any ideas for group and pivot agGrid? </p>

答:
```<code>    var ColDef = [{
        headerName: "colA",
        field: 'colA',
        rowGroup: true
      },
      {
        headerName: "colB",
        field: 'colB',
        pivot: true,
        enablePivot: true
      },
      {
        headerName: "colC",
        field: 'colC',
        rowGroup: true
      },
      {
        field: 'colD',
        aggFunc: 'last',
    tooltipValueGetter: commentTooltipValueGetter
      },
      {
        field: 'comment'
      },
      {
        field: 'colF'
      }
    ];

    function commentTooltipValueGetter(params) {
    const colB = params.colDef.pivotKeys[0];
    var model = params.api.getDisplayedRowAtIndex(params.rowIndex);
    for (var i = 0; i < model.allLeafChildren.length ; i++) {
        if (model.allLeafChildren[i].data.colB=== colB) {
          return model.allLeafChildren[i].data.comments;
                                                       }
                                             }
  }
</code>```

This is what i had to do for my question. It is combination of answers from @wctiger and @shuts below. So please also refer them for more context

Body:
var ColDef = [{
    headerName: "colA",
    field: 'colA',
    rowGroup: true
  },
  {
    headerName: "colB",
    field: 'colB',
    pivot: true,
    enablePivot: true
  },
  {
    headerName: "colC",
    field: 'colC',
    rowGroup: true
  },
  {
    field: 'colD',
    aggFunc: 'first',
    valueFormatter: currencyFormatter,
    tooltip: function(params) {
      return (params.valueFormatted);
    },
  },
  {
    field: 'comment'
  },
  {
    field: 'colF'
  }
];
function currencyFormatter(params) {
  return params.value;
}

above code is from different question. it works but i want to use different 'comment' field as tool tip to current 'colD' . also this is a group and pivot agGrid,if it is normal grid this is not a problem. I would appreciate any ideas for group and pivot agGrid?

Body:
    var ColDef = [{
        headerName: "colA",
        field: 'colA',
        rowGroup: true
      },
      {
        headerName: "colB",
        field: 'colB',
        pivot: true,
        enablePivot: true
      },
      {
        headerName: "colC",
        field: 'colC',
        rowGroup: true
      },
      {
        field: 'colD',
        aggFunc: 'last',
    tooltipValueGetter: commentTooltipValueGetter
      },
      {
        field: 'comment'
      },
      {
        field: 'colF'
      }
    ];

    function commentTooltipValueGetter(params) {
    const colB = params.colDef.pivotKeys[0];
    var model = params.api.getDisplayedRowAtIndex(params.rowIndex);
    for (var i = 0; i < model.allLeafChildren.length ; i++) {
        if (model.allLeafChildren[i].data.colB=== colB) {
          return model.allLeafChildren[i].data.comments;
                                                       }
                                             }
  }

This is what i had to do for my question. It is combination of answers from @wctiger and @shuts below. So please also refer them for more context


问:
WPF Datagrid: How to stay on the same row after pressing Enter?
Our client requests to stay on the same row after pressing Enter to confirm a cell update. Is this possible? Perhaps instead of going down, it could go one cell to the right instead?

Many thanks,

答:
Override the OnKeyDown method and for everything except ENTER key call the base.OnKeyDown

Not calling the parent class version will ensure that the default behavior of cell changing doesn't happen


问:
Where can I see print output in Flutter?
I am using Android Studio to develop an app with flutter and i need to print things to the console for debugging but i have no idea where to view the output as it doesn't show up in the console. I apologize if this is a stupid question but i am very new to this.</p>

答:
Where

When you run Flutter program, your ouput (e.g. from print(...)) will be in Run tab in:

How to show this

It should enable with ever app install.
But if not, you van show this tab manually from:

```<code>View -> Toogle Windows -> Run
</code>```

Body:
Where

When you run Flutter program, your ouput (e.g. from print(...)) will be in Run tab in:

How to show this

It should enable with ever app install.
But if not, you van show this tab manually from:

View -> Toogle Windows -> Run


问:
How can I import subpackage?
I have a file structure like this:

```<code>test.py
Dir1\
  __init__.py
  Something.py
  Dir2\
    __init__.py
    Something2.py
</code>```

```<code>#Dir1.__init__.py
from .Something import *
</code>```

Dir2.__init__.py have has the same code, but with .Something2

Something.py has simple add method, Something2.py has simple sub method.

What I need:

```<code>#test.py
import Dir1
print(Dir1.Dir2.sub(10, 14))
</code>```

But I get an error AttributeError: module 'Dir1' has no attribute 'Dir2'.

If I use from .Dir2 import * in Dir1.__init__.py code in test.py works, but also works print(Dir1.sub(10, 14)), what I don't want. I tryed many variants, but they brought me to error or Dir1.sub working.

This can probably be found on the Internet, but my knowledge of English is suffering and I may miss the answer. Of course I've already tried searching for it on the Internet.

I will be very grateful for your answer.

答:
<pre class="lang-py prettyprint-override"><code># test.py
import Dir1.Dir2
print(Dir1.Dir2.sub(10,14))
</code>```

<p>Should work. Also if you need to you can rename modules at import using the <code>as</code> keyword</p>

<pre class="lang-py prettyprint-override"><code>import some_module as new_name
</code>```

Title: How can I import subpackage?

Body:
I have a file structure like this:

test.py
Dir1\
  __init__.py
  Something.py
  Dir2\
    __init__.py
    Something2.py

#Dir1.__init__.py
from .Something import *

Dir2.__init__.py have has the same code, but with .Something2

Something.py has simple add method, Something2.py has simple sub method.

What I need:

#test.py
import Dir1
print(Dir1.Dir2.sub(10, 14))

But I get an error AttributeError: module 'Dir1' has no attribute 'Dir2'.

If I use from .Dir2 import * in Dir1.__init__.py code in test.py works, but also works print(Dir1.sub(10, 14)), what I don't want. I tryed many variants, but they brought me to error or Dir1.sub working.

This can probably be found on the Internet, but my knowledge of English is suffering and I may miss the answer. Of course I've already tried searching for it on the Internet.

I will be very grateful for your answer.

Body:
# test.py
import Dir1.Dir2
print(Dir1.Dir2.sub(10,14))

Should work. Also if you need to you can rename modules at import using the as keyword

import some_module as new_name


问:
Join statement in multiple thread
I have a program that starts 2 threads and use Join.My understanding says that  joins blocks the calling operation till it is finished executing .So,the below program should give 2 Million as answer since both the threads blocks till execution is completed but I am always getting the different value.This might be because first thread is completed but second thread is not run completely.
Can someone please explain the output.

Reference -Multithreading: When would I use a Join?

```<code>namespace ThreadSample
{
    class Program
    {
        static int Total = 0;
        public static void Main()
        {
            Thread thread1 = new Thread(Program.AddOneMillion);
            Thread thread2 = new Thread(Program.AddOneMillion);

            thread1.Start();
            thread2.Start();

            thread1.Join();
            thread2.Join();

            Console.WriteLine("Total = " + Total);
            Console.ReadLine();
        }
        public static void AddOneMillion()
        {
            for (int i = 1; i <= 1000000; i++)
            {
                Total++;
            }
        }
    }
}
</code>```

答:
It's because the increment operation is not done atomically. That means that each thread may hold a copy of Total and increment it. To avoid that you can use a lock or Interlock.Increment that is specific to incrementing a variable.

Clarification:

```<code>thread 1: read copy of Total
thread 2: read copy of Total
thread 1: increment and store Total
thread 2: increment and store Total (overwriting previous value)
</code>```

I leave you with all possible scenarios where things could go wrong.

I would suggest avoiding explicit threading when possible and use map reduce operations that are less error prone.

You need to read about multi-threading programming and functional programming constructs available in mainstream languages. Most languages have added libraries to leverage the multicore capabilities of modern CPUs.

Title: Join statement in multiple thread

Body:
I have a program that starts 2 threads and use Join.My understanding says that  joins blocks the calling operation till it is finished executing .So,the below program should give 2 Million as answer since both the threads blocks till execution is completed but I am always getting the different value.This might be because first thread is completed but second thread is not run completely.
Can someone please explain the output.

Reference -Multithreading: When would I use a Join?

namespace ThreadSample
{
    class Program
    {
        static int Total = 0;
        public static void Main()
        {
            Thread thread1 = new Thread(Program.AddOneMillion);
            Thread thread2 = new Thread(Program.AddOneMillion);

            thread1.Start();
            thread2.Start();

            thread1.Join();
            thread2.Join();

            Console.WriteLine("Total = " + Total);
            Console.ReadLine();
        }
        public static void AddOneMillion()
        {
            for (int i = 1; i <= 1000000; i++)
            {
                Total++;
            }
        }
    }
}

Body:
It's because the increment operation is not done atomically. That means that each thread may hold a copy of Total and increment it. To avoid that you can use a lock or Interlock.Increment that is specific to incrementing a variable.

Clarification:

thread 1: read copy of Total
thread 2: read copy of Total
thread 1: increment and store Total
thread 2: increment and store Total (overwriting previous value)

I leave you with all possible scenarios where things could go wrong.

I would suggest avoiding explicit threading when possible and use map reduce operations that are less error prone.

You need to read about multi-threading programming and functional programming constructs available in mainstream languages. Most languages have added libraries to leverage the multicore capabilities of modern CPUs.


问:
CUTENEWS.RU - Strict Standards: Only variables should be passed by reference in
I have a problem with this code, any help?

$var = reset($sql -> select(array(
  'table' => 'news',
  'join' => array('table' => 'story', 'where' => 'id = post_id'),
  'where' => array("id = $id", 'or', "url = $id")
)));
```

<p>Error: </p>

<blockquote>
```Strict Standards: Only variables should be passed by reference in

$query = reset(
    $sql->select(array(
        'table'     => 'news',
        'where'     => $where
)));
Strict Standards: Only variables should be passed by reference in
```

答:
Take a look here.

reset() function is waiting for a variable reference, instead you are passing it a function result.

For more info see php reset docs

You can, extract the result of the function and then pass it to reset() as shown below.

```<code>$select = $sql -> select(array(
  'table' => 'news',
  'join' => array('table' => 'story', 'where' => 'id = post_id'),
  'where' => array("id = $id", 'or', "url = $id")
))
$var = reset($select);
</code>```

Then the other one:

```<code>$select1 = $sql->select(array(
             'table'      => 'news',
             'where'      => $where
            ));
$query = reset($select1);
</code>```

PHP live demo

correct

incorrect

Body:
I have a problem with this code, any help?

$var = reset($sql -> select(array(
  'table' => 'news',
  'join' => array('table' => 'story', 'where' => 'id = post_id'),
  'where' => array("id = $id", 'or', "url = $id")
)));

Error:

Strict Standards: Only variables should be passed by reference in

$query = reset(
    $sql->select(array(
        'table'     => 'news',
        'where'     => $where
)));
Strict Standards: Only variables should be passed by reference in

Body:
Take a look here.

reset() function is waiting for a variable reference, instead you are passing it a function result.

For more info see php reset docs

You can, extract the result of the function and then pass it to reset() as shown below.

$select = $sql -> select(array(
  'table' => 'news',
  'join' => array('table' => 'story', 'where' => 'id = post_id'),
  'where' => array("id = $id", 'or', "url = $id")
))
$var = reset($select);

Then the other one:

$select1 = $sql->select(array(
             'table'      => 'news',
             'where'      => $where
            ));
$query = reset($select1);

PHP live demo

correct

incorrect


问:
Javascript : Create a variable that returns me only the first word of page title
I have a website page with a three words title.
how can I create a variable in Javascript that outputs only the first word of that title ?

thanks for your help !

答:
If you need the first "word" of the title, you can:

Access the document.title

Trim any unnecessary white-space

Shift the resulting array to grab the first sequence of non-white-space characters

Note: You do not need to use the global flag for the expression, because we only care about the left-hand side of the split.

const firstWordOfTitle = document.title.trim().split(/\s+/).shift();

console.log(`First word of document: "${firstWordOfTitle}"`); // "Test"```
<pre class="snippet-code-html lang-html prettyprint-override"><code><title>Test Title</title></code>```

Body:
If you need the first "word" of the title, you can:

Access the document.title

Trim any unnecessary white-space

Shift the resulting array to grab the first sequence of non-white-space characters

Note: You do not need to use the global flag for the expression, because we only care about the left-hand side of the split.

const firstWordOfTitle = document.title.trim().split(/\s+/).shift();

console.log(`First word of document: "${firstWordOfTitle}"`); // "Test"

<title>Test Title</title>


问:
Using cpquery function for several pairs from dataset
I am relatively beginner in R and trying to figure out how to use cpquery function for bnlearn package for all edges of DAG.

First of all, I created a bn object, a network of bn and a table with all strengths.

```<code>library(bnlearn)
data(learning.test)
baynet = hc(learning.test)
fit = bn.fit(baynet, learning.test)
sttbl = arc.strength(x = baynet, data = learning.test)
</code>```

Then I tried to create a new variable in sttbl dataset, which was the result of cpquery function.

```<code>sttbl = sttbl %>% mutate(prob = NA) %>% arrange(strength)
sttbl[1,4] = cpquery(fit, `A` == 1, `D` == 1)
</code>```

It looks pretty good (especially on bigger data), but when I am trying to automate this process somehow, I am struggling with errors, such as:

Error in sampling(fitted = fitted, event = event, evidence = evidence,  :
    logical vector for evidence is of length 1 instead of 10000.

In perfect situation, I need to create a function that fills the prob generated variable of sttbl dataset regardless it's size. I tried to do it with for loop to, but stumbled over the error above again and again. Unfortunately, I am deleting failed attempts, but they were smt like this:

```<code>for (i in 1:nrow(sttbl)) {
     j = sttbl[i,1]
     k = sttbl[i,2]
     sttbl[i,4]=cpquery(fit, fit$j %in% sttbl[i,1]==1, fit$k %in% sttbl[i,2]==1)
}
</code>```

or this:

```<code>for (i in 1:nrow(sttbl)) {
     sttbl[i,4]=cpquery(fit, sttbl[i,1] == 1, sttbl[i,2] == 1)
}
</code>```

Now I think I misunderstood something in R or bnlearn package.

Could you please tell me how to realize this task with filling the column by multiple cpqueries? That would help me a lot with my research!

答:
cpquery is quite difficult to work with programmatically. If you look at the examples in the help page you can see the author uses eval(parse(...)) to build the queries. I have added two approaches below, one using the methods from the help page and one using cpdist to draw samples and reweighting to get the probabilities.

Your example

```<code>library(bnlearn); library(dplyr)
data(learning.test)
baynet = hc(learning.test)
fit = bn.fit(baynet, learning.test)
sttbl = arc.strength(x = baynet, data = learning.test)
sttbl = sttbl %>% mutate(prob = NA) %>% arrange(strength)
</code>```

This uses cpquery and the much maligned eval(parse(...)) -- this is the
approach the the bnlearn author takes to do this programmatically in the ?cpquery examples. Anyway,

```<code># You want the evidence and event to be the same; in your question it is `1`
# but for example using learning.test data we use 'a'
state = "\'a\'" # note if the states are character then these need to be quoted
event = paste(sttbl$from, "==", state)
evidence = paste(sttbl$to, "==", state)

# loop through using code similar to that found in `cpquery`
set.seed(1) # to make sampling reproducible
for(i in 1:nrow(sttbl)) {
  qtxt = paste("cpquery(fit, ", event[i], ", ", evidence[i], ",n=1e6", ")")
  sttbl$prob[i] = eval(parse(text=qtxt))
}
</code>```

I find it preferable to work with cpdist which is used to generate random samples conditional on some evidence. You can then use these samples to build up queries. If you use likelihood weighting (method="lw") it is slightly easier to do this programatically (and without evil(parse(...))).
The evidence is added in a named list i.e. list(A='a').

```<code># The following just gives a quick way to assign the same
# evidence state to all the evidence nodes.
evidence = setNames(replicate(nrow(sttbl), "a", simplify = FALSE), sttbl$to)

# Now loop though the queries
# As we are using likelihood weighting we need to reweight to get the probabilities
# (cpquery does this under the hood)
# Also note with this method that you could simulate from more than
# one variable (event) at a time if the evidence was the same.
for(i in 1:nrow(sttbl)) {
  temp = cpdist(fit, sttbl$from[i], evidence[i], method="lw")
  w = attr(temp, "weights")
  sttbl$prob2[i] = sum(w[temp=='a'])/ sum(w)
}

sttbl
#   from to   strength      prob     prob2
# 1    A  D -1938.9499 0.6186238 0.6233387
# 2    A  B -1153.8796 0.6050552 0.6133448
# 3    C  D  -823.7605 0.7027782 0.7067417
# 4    B  E  -720.8266 0.7332107 0.7328657
# 5    F  E  -549.2300 0.5850828 0.5895373
</code>```

Body:
I am relatively beginner in R and trying to figure out how to use cpquery function for bnlearn package for all edges of DAG.

First of all, I created a bn object, a network of bn and a table with all strengths.

library(bnlearn)
data(learning.test)
baynet = hc(learning.test)
fit = bn.fit(baynet, learning.test)
sttbl = arc.strength(x = baynet, data = learning.test)

Then I tried to create a new variable in sttbl dataset, which was the result of cpquery function.

sttbl = sttbl %>% mutate(prob = NA) %>% arrange(strength)
sttbl[1,4] = cpquery(fit, `A` == 1, `D` == 1)

It looks pretty good (especially on bigger data), but when I am trying to automate this process somehow, I am struggling with errors, such as:

Error in sampling(fitted = fitted, event = event, evidence = evidence,  :
    logical vector for evidence is of length 1 instead of 10000.

In perfect situation, I need to create a function that fills the prob generated variable of sttbl dataset regardless it's size. I tried to do it with for loop to, but stumbled over the error above again and again. Unfortunately, I am deleting failed attempts, but they were smt like this:

for (i in 1:nrow(sttbl)) {
     j = sttbl[i,1]
     k = sttbl[i,2]
     sttbl[i,4]=cpquery(fit, fit$j %in% sttbl[i,1]==1, fit$k %in% sttbl[i,2]==1)
}

or this:

for (i in 1:nrow(sttbl)) {
     sttbl[i,4]=cpquery(fit, sttbl[i,1] == 1, sttbl[i,2] == 1)
}

Now I think I misunderstood something in R or bnlearn package.

Could you please tell me how to realize this task with filling the column by multiple cpqueries? That would help me a lot with my research!

Body:
cpquery is quite difficult to work with programmatically. If you look at the examples in the help page you can see the author uses eval(parse(...)) to build the queries. I have added two approaches below, one using the methods from the help page and one using cpdist to draw samples and reweighting to get the probabilities.

Your example

library(bnlearn); library(dplyr)
data(learning.test)
baynet = hc(learning.test)
fit = bn.fit(baynet, learning.test)
sttbl = arc.strength(x = baynet, data = learning.test)
sttbl = sttbl %>% mutate(prob = NA) %>% arrange(strength)

This uses cpquery and the much maligned eval(parse(...)) -- this is the
approach the the bnlearn author takes to do this programmatically in the ?cpquery examples. Anyway,

# You want the evidence and event to be the same; in your question it is `1`
# but for example using learning.test data we use 'a'
state = "\'a\'" # note if the states are character then these need to be quoted
event = paste(sttbl$from, "==", state)
evidence = paste(sttbl$to, "==", state)

# loop through using code similar to that found in `cpquery`
set.seed(1) # to make sampling reproducible
for(i in 1:nrow(sttbl)) {
  qtxt = paste("cpquery(fit, ", event[i], ", ", evidence[i], ",n=1e6", ")")
  sttbl$prob[i] = eval(parse(text=qtxt))
}

I find it preferable to work with cpdist which is used to generate random samples conditional on some evidence. You can then use these samples to build up queries. If you use likelihood weighting (method="lw") it is slightly easier to do this programatically (and without evil(parse(...))).
The evidence is added in a named list i.e. list(A='a').

# The following just gives a quick way to assign the same
# evidence state to all the evidence nodes.
evidence = setNames(replicate(nrow(sttbl), "a", simplify = FALSE), sttbl$to)

# Now loop though the queries
# As we are using likelihood weighting we need to reweight to get the probabilities
# (cpquery does this under the hood)
# Also note with this method that you could simulate from more than
# one variable (event) at a time if the evidence was the same.
for(i in 1:nrow(sttbl)) {
  temp = cpdist(fit, sttbl$from[i], evidence[i], method="lw")
  w = attr(temp, "weights")
  sttbl$prob2[i] = sum(w[temp=='a'])/ sum(w)
}

sttbl
#   from to   strength      prob     prob2
# 1    A  D -1938.9499 0.6186238 0.6233387
# 2    A  B -1153.8796 0.6050552 0.6133448
# 3    C  D  -823.7605 0.7027782 0.7067417
# 4    B  E  -720.8266 0.7332107 0.7328657
# 5    F  E  -549.2300 0.5850828 0.5895373


问:
How can I create a gedit plugin using python?
I wanted to create a simple gedit plugin that could save the current file when mouse leaves the text area (just like the <<leave>> event in tkinter) using python3. I went through wiki but I couldn't get much from it (All I could do was to create a plugin that just showed in plugins menu,nothing more). Can anyone help me with this?

答:
According to the Python plugin HOWTO:

The gedit window based on Gtk.Window.

Looking at the documentation for Gtk.Window, it inherits from Gtk.Widget.

Looking at the signals documentation for Gtk.Widget, it looks like leave-notify-event is what you are looking for.


问:
Html entity problem in Struts2  tag parameter
Am passing some parameters through  in Struts2, and am getting below error when there is a HTML special Character in parameter value how can i over come this...?

A herf tage used:

```<code><a href="ManufacturerProducts.action?manufId=<s:property value="manufId"/>&mName=<s:property value="manufName"/>"><img src="<s:property value="manufLogo"/>" alt="<s:property value="manufName"/>" /></a>
</code>```

Error:

```<code>12:21:46,034 WARN  [OgnlValueStack] Error setting expression ' A Manufacturing Co' with value '[Ljava.lang.String;@4acc69'
ognl.ExpressionSyntaxException: Malformed OGNL expression:  A Manufacturing Co [ognl.ParseException: Encountered " <IDENT> "Manufacturing "" at line 1, column 4.
Was expecting one of:
    <EOF>
    "," ...
    "=" ...
    "?" ...
    "||" ...
    "or" ...
    "&&" ...
    "and" ...
    "|" ...
    "bor" ...
    "^" ...
    "xor" ...
    "&" ...
    "band" ...
    "==" ...
    "eq" ...
    "!=" ...
    "neq" ...
    "<" ...
    "lt" ...
    ">" ...
    "gt" ...
    "<=" ...
    "lte" ...
    ">=" ...
    "gte" ...
    "in" ...
    "not" ...
    "<<" ...
    "shl" ...
    ">>" ...
    "shr" ...
    ">>>" ...
    "ushr" ...
    "+" ...
    "-" ...
    "*" ...
    "/" ...
    "%" ...
    "instanceof" ...
    "." ...
    "(" ...
    "[" ...
    <DYNAMIC_SUBSCRIPT> ...
    "(" ...
    ]
    at ognl.Ognl.parseExpression(Ognl.java:112)
    at com.opensymphony.xwork2.ognl.OgnlUtil.compile(OgnlUtil.java:225)
    at com.opensymphony.xwork2.ognl.OgnlUtil.setValue(OgnlUtil.java:209)
    at com.opensymphony.xwork2.ognl.OgnlValueStack.trySetValue(OgnlValueStack.java:173)
    at com.opensymphony.xwork2.ognl.OgnlValueStack.setValue(OgnlValueStack.java:160)
    at com.opensymphony.xwork2.ognl.OgnlValueStack.setValue(OgnlValueStack.java:151)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.setParameters(ParametersInterceptor.java:288)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:199)
</code>```

Thank you.

答:
One more alternatove

```<code><a href="javascript:loadvalue()">
    <img src="<s:property value='manufLogo'/>" alt="<s:property value='manufName'/>" />
</a>
</code>```

javascript

```<code>function loadvalue(){
var param=encodeURI("manufId=<s:property value='manufId'/>&mName=<s:property value='manufName'/>");
window.location="ManufacturerProducts.action?"+param;
}
</code>```

Body:
Am passing some parameters through  in Struts2, and am getting below error when there is a HTML special Character in parameter value how can i over come this...?

A herf tage used:

<a href="ManufacturerProducts.action?manufId=<s:property value="manufId"/>&mName=<s:property value="manufName"/>"><img src="<s:property value="manufLogo"/>" alt="<s:property value="manufName"/>" />

Error:

12:21:46,034 WARN  [OgnlValueStack] Error setting expression ' A Manufacturing Co' with value '[Ljava.lang.String;@4acc69'
ognl.ExpressionSyntaxException: Malformed OGNL expression:  A Manufacturing Co [ognl.ParseException: Encountered " <IDENT> "Manufacturing "" at line 1, column 4.
Was expecting one of:
    <EOF>
    "," ...
    "=" ...
    "?" ...
    "||" ...
    "or" ...
    "&&" ...
    "and" ...
    "|" ...
    "bor" ...
    "^" ...
    "xor" ...
    "&" ...
    "band" ...
    "==" ...
    "eq" ...
    "!=" ...
    "neq" ...
    "<" ...
    "lt" ...
    ">" ...
    "gt" ...
    "<=" ...
    "lte" ...
    ">=" ...
    "gte" ...
    "in" ...
    "not" ...
    "<<" ...
    "shl" ...
    ">>" ...
    "shr" ...
    ">>>" ...
    "ushr" ...
    "+" ...
    "-" ...
    "*" ...
    "/" ...
    "%" ...
    "instanceof" ...
    "." ...
    "(" ...
    "[" ...
    <DYNAMIC_SUBSCRIPT> ...
    "(" ...
    ]
    at ognl.Ognl.parseExpression(Ognl.java:112)
    at com.opensymphony.xwork2.ognl.OgnlUtil.compile(OgnlUtil.java:225)
    at com.opensymphony.xwork2.ognl.OgnlUtil.setValue(OgnlUtil.java:209)
    at com.opensymphony.xwork2.ognl.OgnlValueStack.trySetValue(OgnlValueStack.java:173)
    at com.opensymphony.xwork2.ognl.OgnlValueStack.setValue(OgnlValueStack.java:160)
    at com.opensymphony.xwork2.ognl.OgnlValueStack.setValue(OgnlValueStack.java:151)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.setParameters(ParametersInterceptor.java:288)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:199)

Thank you.

Body:
One more alternatove

<a href="javascript:loadvalue()">
    <img src="<s:property value='manufLogo'/>" alt="<s:property value='manufName'/>" />
</a>

javascript

function loadvalue(){
var param=encodeURI("manufId=<s:property value='manufId'/>&mName=<s:property value='manufName'/>");
window.location="ManufacturerProducts.action?"+param;
}


问:
Validate email format in firestore security rules
I need to make sure that if the user is updating its email, it should be a correct email address (at least including a "@" and finishing by a ".xxx")

I understood I have to use matches. I tried:

```<code>request.resource.data.email.matches(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$/i)
</code>```

But it seems it isn't RE2 compliant:

```<code>i  firestore: Change detected, updating rules...
⚠  firestore.rules:30:63 - ERROR Unexpected '_'.
⚠  firestore.rules:30:63 - ERROR Unexpected '_'.
⚠  firestore.rules:30:63 - ERROR mismatched input '_' expecting {'&&', '.', '==', '>', '>=', '[', '<', '<=', '-', '%', '!=', '||', '+', '}', ';', '/', '*', '?', 'in', 'is'}
⚠  firestore.rules:30:81 - ERROR token recognition error at: '\'
⚠  firestore.rules:30:82 - ERROR token recognition error at: '\'
⚠  firestore.rules:30:94 - ERROR Unexpected '$'.
⚠  firestore.rules:30:95 - ERROR Missing 'match' keyword before path.
⚠  firestore.rules:30:97 - ERROR mismatched input ')' expecting {'{', '/', PATH_SEGMENT}
⚠  firestore.rules:48:3 - ERROR Unexpected '}'.
✔  firestore: Rules updated.
</code>```

Is there a correct email RE2 regex somewhere? I couldn't find one.

答: According to the API documentation, matches() takes a string parameter.  This means you should put your regular expression inside double quotes to tell the language that you have a string value.</p>

Body:
I need to make sure that if the user is updating its email, it should be a correct email address (at least including a "@" and finishing by a ".xxx")

I understood I have to use matches. I tried:

request.resource.data.email.matches(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$/i)

But it seems it isn't RE2 compliant:

i  firestore: Change detected, updating rules...
⚠  firestore.rules:30:63 - ERROR Unexpected '_'.
⚠  firestore.rules:30:63 - ERROR Unexpected '_'.
⚠  firestore.rules:30:63 - ERROR mismatched input '_' expecting {'&&', '.', '==', '>', '>=', '[', '<', '<=', '-', '%', '!=', '||', '+', '}', ';', '/', '*', '?', 'in', 'is'}
⚠  firestore.rules:30:81 - ERROR token recognition error at: '\'
⚠  firestore.rules:30:82 - ERROR token recognition error at: '\'
⚠  firestore.rules:30:94 - ERROR Unexpected '$'.
⚠  firestore.rules:30:95 - ERROR Missing 'match' keyword before path.
⚠  firestore.rules:30:97 - ERROR mismatched input ')' expecting {'{', '/', PATH_SEGMENT}
⚠  firestore.rules:48:3 - ERROR Unexpected '}'.
✔  firestore: Rules updated.

Is there a correct email RE2 regex somewhere? I couldn't find one.


问:
G-Suit mail pricing , What is per user mean?
I want to buy a g-suit mail.
I already have a domain. I want to buy an email server from the g-suit.
When I visited g-suit pricing, there was "Per User" billing details. Actually I don't know what it means.

what is per user means? is that directs to per domain?
If I want to create 20 mail id in the same domain will it count as one user or 20 users?

as I already told, 20 mail id will be on the same domain name

like user1@mydomain.com, user2@mydomain.com ..... user20@mydomain.com

答:
In this case you need to pay 20 users. </p>

<p>Here I add a link with a small discount </p>

Body:
In this case you need to pay 20 users.

Here I add a link with a small discount


问:
matplotlib - Plot 3 histograms with percentage on y axis
I am trying to have 3 histograms on same plot but against percentage on the y axis but not sure how.
You can see what I am trying to do, but I can't get there! The bars don't scale property and not sure how to do that! Please help

```<code>data_1 = [1,1,2,3,4,4,5,6,7,7,7,8,9]
data_2 = [4,2,3,4,1,1,6,8,9,9,9,5,6]
data_3 = [1,2,3,4,5,6,7,8,9,9,4,3,7,1,2,3,2,5,7,3,4,7,3,8,2,3,4,7,2]

bin = [1,10,1]
bin[1] += bin[2]*2
bin[0] -= bin[2]
bins_list = np.arange(bin[0],bin[1],bin[2])
fig, ax = plt.subplots(figsize=(15, 10))

counts, bins, patches = plt.hist((np.clip(data_1 , bins_list[0], bins_list[-1]),np.clip(data_2, bins_list[0], bins_list[-1]),np.clip(data_3, bins_list[0], bins_list[-1])),
                        rwidth=0.8,
                        bins=bins_list, color=('blue', 'red', 'green'),
                        weights=None)

xlabels = bins[1:].astype(str)
xlabels[-1] = xlabels[-2] + '>'
xlabels[0] = xlabels[0] + '<'

for lb in range(1, len(xlabels)-1):
    xlabels[lb] = str(bins_list[lb])+'-'+xlabels[lb]

N_labels = len(xlabels)
plt.xticks(bin[2] * np.arange(N_labels)+bin[2]/2 + bin[0], rotation=300)
ax.set_xticklabels(xlabels)
total = 0

''' Add percentages and value for each bar '''
for c in range(len(patches)):
    for count, p in zip(counts[c], patches[c]):
        percentage = '%0.2f%%  ' % (100 * float(count) / counts[c].sum())
        total += 100 * float(count) / counts[c].sum()
        x1 = p.get_x()
        y1 = p.get_y() + p.get_height()
        ax.annotate(percentage, (x1, y1), rotation=270, fontsize = 10)

ax.yaxis.set_major_formatter(tkr.PercentFormatter(xmax=len(data_3)))

ax.grid(axis='y', color='r',  linestyle=':')
ax.set_title("Please help")

ax.set_axisbelow(True)
fig.tight_layout()
</code>```

Plot Result of code above

答:
You can pass density=True on plt.hist:

```<code>counts, bins, patches = plt.hist((np.clip(data_1 , bins_list[0], bins_list[-1]),
                                  np.clip(data_2, bins_list[0], bins_list[-1]),
                                  np.clip(data_3, bins_list[0], bins_list[-1])),
                        rwidth=0.8,
                        density=True,                                  # here
                        bins=bins_list, color=('blue', 'red', 'green'),
                        weights=None)
</code>```

Output:

Body:
I am trying to have 3 histograms on same plot but against percentage on the y axis but not sure how.
You can see what I am trying to do, but I can't get there! The bars don't scale property and not sure how to do that! Please help

data_1 = [1,1,2,3,4,4,5,6,7,7,7,8,9]
data_2 = [4,2,3,4,1,1,6,8,9,9,9,5,6]
data_3 = [1,2,3,4,5,6,7,8,9,9,4,3,7,1,2,3,2,5,7,3,4,7,3,8,2,3,4,7,2]

bin = [1,10,1]
bin[1] += bin[2]*2
bin[0] -= bin[2]
bins_list = np.arange(bin[0],bin[1],bin[2])
fig, ax = plt.subplots(figsize=(15, 10))

counts, bins, patches = plt.hist((np.clip(data_1 , bins_list[0], bins_list[-1]),np.clip(data_2, bins_list[0], bins_list[-1]),np.clip(data_3, bins_list[0], bins_list[-1])),
                        rwidth=0.8,
                        bins=bins_list, color=('blue', 'red', 'green'),
                        weights=None)

xlabels = bins[1:].astype(str)
xlabels[-1] = xlabels[-2] + '>'
xlabels[0] = xlabels[0] + '<'

for lb in range(1, len(xlabels)-1):
    xlabels[lb] = str(bins_list[lb])+'-'+xlabels[lb]

N_labels = len(xlabels)
plt.xticks(bin[2] * np.arange(N_labels)+bin[2]/2 + bin[0], rotation=300)
ax.set_xticklabels(xlabels)
total = 0

''' Add percentages and value for each bar '''
for c in range(len(patches)):
    for count, p in zip(counts[c], patches[c]):
        percentage = '%0.2f%%  ' % (100 * float(count) / counts[c].sum())
        total += 100 * float(count) / counts[c].sum()
        x1 = p.get_x()
        y1 = p.get_y() + p.get_height()
        ax.annotate(percentage, (x1, y1), rotation=270, fontsize = 10)

ax.yaxis.set_major_formatter(tkr.PercentFormatter(xmax=len(data_3)))

ax.grid(axis='y', color='r',  linestyle=':')
ax.set_title("Please help")

ax.set_axisbelow(True)
fig.tight_layout()

Plot Result of code above

Body:
You can pass density=True on plt.hist:

counts, bins, patches = plt.hist((np.clip(data_1 , bins_list[0], bins_list[-1]),
                                  np.clip(data_2, bins_list[0], bins_list[-1]),
                                  np.clip(data_3, bins_list[0], bins_list[-1])),
                        rwidth=0.8,
                        density=True,                                  # here
                        bins=bins_list, color=('blue', 'red', 'green'),
                        weights=None)

Output:


问:
Can SQL/XML UpdateGrams be run in ADO.NET?
The examples I find for executing a SQL/XML UpdateGram are all using ADODB.  Can the same thing be done with ADO.NET or is the older ADODB required?

https://learn.microsoft.com/en-us/sql/relational-databases/sqlxml-annotated-xsd-schemas-xpath-queries/updategrams/executing-an-updategram-by-using-ado-sqlxml-4-0?view=sql-server-ver15

答:
SQLXML is out of support, and never worked with ADO.NET.  It was superseded in SQL Server 2005 with the built-in XML support in SQL Server.

UpdateGrams are no more, but you can send an XML document to SQL Server and shred it for use in queries.


问:
What is the difference between eq?, eqv?, equal?, and = in Scheme?
I wonder what the difference is between those operations in Scheme. I have seen similar questions in Stack Overflow but they are about Lisp, and there is not a comparison between three of those operators.

I am writing the different types of commands in Scheme, and I get the following outputs:

```<code>(eq? 5 5) -->#t
(eq? 2.5 2.5) -->#f
(equal? 2.5 2.5) --> #t
(= 2.5 2.5) --> #t
</code>```

Why is this the case?

答:
Apart from the previous answers, I will add some comments.

All these predicates want to define the abstract function of identity for an object but in different contextes.

EQ? is implementation-dependent and it does not answer the question are 2 objects the same? only in limited use.  From implementation point of view, this predicate just compares 2 numbers (pointer to objects), it does not look at the content of the objects.   So, for example, if your implementation does not uniquely keep the strings inside but allocates different memory for each string, then (eq? "a" "a") will be false.

EQV? -- this looks inside the objects, but with limited use.  It is implementation-dependent if it returns true for (eqv? (lambda(x) x) (lambda(x) x)).  Here it's a full philosophy how to define this predicate, as we know nowadays that there are some fast methods to compare the functionality of some functions, with limited use.  But eqv? provides coherent answer for big numbers, strings, etc.

Practically, some of these predicates tries to use the abstract definition of an object (mathematically), while others use the representation of an object (how it's implemented on a real machine).  The mathematical definition of identity comes from Leibniz and it says:

```<code>X = Y  iff  for any P, P(X) = P(Y)
X, Y being objects and
P being any property associated with object X and Y.
</code>```

Ideally it would be to be able to implement this very definition on computer but for reasons of indecidability and/or speed it is not implemented literally.  This is why there are lots of operators that try each one to focus on different viewpoints around this definition.

Try to imagine the abstract definition of an identity for a continuation.  Even if you can provide a definition of a subset of functions (sigma-recursive class of functions), the language does not impose any predicate to be true or false.  It would complicate a lot both the definition of the language and much more the implementation.

The context for the other predicates is easier to analyze.

Body:
I wonder what the difference is between those operations in Scheme. I have seen similar questions in Stack Overflow but they are about Lisp, and there is not a comparison between three of those operators.

I am writing the different types of commands in Scheme, and I get the following outputs:

(eq? 5 5) -->#t
(eq? 2.5 2.5) -->#f
(equal? 2.5 2.5) --> #t
(= 2.5 2.5) --> #t

Why is this the case?

Body:
Apart from the previous answers, I will add some comments.

All these predicates want to define the abstract function of identity for an object but in different contextes.

EQ? is implementation-dependent and it does not answer the question are 2 objects the same? only in limited use.  From implementation point of view, this predicate just compares 2 numbers (pointer to objects), it does not look at the content of the objects.   So, for example, if your implementation does not uniquely keep the strings inside but allocates different memory for each string, then (eq? "a" "a") will be false.

EQV? -- this looks inside the objects, but with limited use.  It is implementation-dependent if it returns true for (eqv? (lambda(x) x) (lambda(x) x)).  Here it's a full philosophy how to define this predicate, as we know nowadays that there are some fast methods to compare the functionality of some functions, with limited use.  But eqv? provides coherent answer for big numbers, strings, etc.

Practically, some of these predicates tries to use the abstract definition of an object (mathematically), while others use the representation of an object (how it's implemented on a real machine).  The mathematical definition of identity comes from Leibniz and it says:

X = Y  iff  for any P, P(X) = P(Y)
X, Y being objects and
P being any property associated with object X and Y.

Ideally it would be to be able to implement this very definition on computer but for reasons of indecidability and/or speed it is not implemented literally.  This is why there are lots of operators that try each one to focus on different viewpoints around this definition.

Try to imagine the abstract definition of an identity for a continuation.  Even if you can provide a definition of a subset of functions (sigma-recursive class of functions), the language does not impose any predicate to be true or false.  It would complicate a lot both the definition of the language and much more the implementation.

The context for the other predicates is easier to analyze.


问:
How to wrap a Linux library to be used in Wine? I keep getting BAD_IMAGE_FORMAT
I have a Windows-only game that can be extended by plugins and a Linux library I would like to use. The application (Unity game) runs fine under Wine/Proton. I've found that Winelib can do this, and I was following the User's Guide, notably the 5th section which mentions my exact use case.

After some attempts (like removing --single-target arg from winemaker), I got to the point where the Proton debug log keeps showing c000007b which seems to be STATUS_BAD_IMAGE_FORMAT.

Note that I renamed the Linux library (and linked against that), to avoid a potential conflict between that and my wrapper.

I only have a 64-bit version of the library and it is called from C# code using the cdecl calling convention. This is what I've tried so far (and combinations of these):

Added a .spec file with contents (first without the -arch and with different ordinals):

```<code>1 cdecl -arch=x86_64 LibraryFunc (long ptr ptr) LibraryFuncWine
</code>```

Added the library's header and a .c file:

#include "library_header.h"
#include <windef.h> /* Part of the Wine header files */

enum ELibResult WINAPI LibraryFuncWine(Version version, struct CreateParams* params, struct ICore** result)
{
    enum ELibResult ret = LibraryFunc(version, params, result);

    return ret;
}
```

<ul>
<li>Used winemaker as <code>winemaker --nosource-fix --dll --nomfc -I. -L. -llinux_library .</code> then <code>make</code></li>
<li>Copied the .dll.so file all around the game</li>
<li>Copied the .dll.so file to steamapps/common/Proton 5.0/dist/lib64/wine/ and the native library to one level higher (lib64/) and removed the others</li>
<li>Also tried to copy to lib/ instead of lib64/</li>
<li>Added a dll override for the file and set it to builtin</li>
<li>Removed the referenced DLLs (odbc32, ole32, oleaut32, winspool, odbccp32) and libraries (uuid) from the makefile</li>
<li>Add <code>--mno-cygwin</code> to compiler flags</li>
<li>Add <code>-m64</code> and <code>-fPIC</code> to compiler/linker flags (based on Wine spec files)</li>
<li>I've also tried making a .def file and using that</li>
<li>Used winemaker again with the <code>--nomsvcrt</code> argument added and ran <code>make</code> (the header file includes string.h)</li>
</ul>

<p>From the Proton log (+module, the others didn't provide any more info for me):</p>

```00dc:trace:module:load_dll looking for L"Z:\\D\\a\\library\\path\\library_name" in L"Z:\\D\\gamepath;C:\\windows\\system32;C:\\windows\\system;C:\\windows;C:\\Program Files (x86)\\Steam;.;C:\\windows\\system32;C:\\windows;C:\\windows\\system32\\wbem;C:\\windows\\system32\\WindowsPowershell\\v1.0"
00dc:trace:module:get_load_order looking for L"Z:\\D\\a\\library\\path\\library_name.dll"
00dc:trace:module:get_load_order_value got standard key b for L"library_name"
00dc:trace:module:load_builtin_dll Trying built-in L"library_name.dll"
00dc:trace:module:load_so_dll loading L"\\??\\Z:\\D\\a\\library\\path\\library_name.dll" from so lib "/D/Games/SteamLibrary/steamapps/common/Proton 5.0/dist/bin/../lib64/wine/library_name.dll.so"
00dc:warn:module:load_dll Failed to load module L"Z:\\D\\a\\library\\path\\library_name"; status=c000007b
```

The same is repeated with and without .dll and starting with lib (library_name.dll, liblibrary_name and liblibrary_name.dll).

I was unable to get any more logs on what exactly goes wrong besides that error code.

On the C# side (ran by Unity in Proton) it results in a DllNotFoundException.

Wine version (winebuild, winegcc): 5.9 (staging) - gcc 9.0.1

Proton version: 5.0 - wine-5.0-603-g068dee4

答:
There may be a solution for your binary only .so using RPC.

But, since many/most linux libraries have source code, what is the specific library [that doesn't]? Is there an alternate library that is similar that does?  There may be source code for your binary library if you look hard enough for it.

However, I'm going to assume that you do have to use the binary linux library.

But, this may involve more work than you'd be willing to do.
So, how badly do you want this? ;-)

Is this for production or just personal use? I'm assuming just for personal use because you're trying to get the WinX game to work under wine.

How big is the .so in terms of the number of public API functions [that your wine program needs to call]? How many different structs are involved?

You may need to create glue/interface routines for each API call and struct.

The basic method is to use [some sort of] RPC [remote procedure call] mechanism (e.g.) https://en.wikipedia.org/wiki/Remote_procedure_call

You create a linux server that incorporates the desired [linux only] library. You write wrapper routines that convert RPC calls into the library's API calls.

In the game, your plugin would issue RPC calls that get sent to the server, the server does the processing, and sends back the results.

There are some tools that can help you with that (e.g. rpcgen)

Normally, RPC is done over a network/socket connection. For your purposes, this could be over localhost or using an AF_UNIX connection. Maybe that's fast enough for your purpose.

Otherwise, you may have to establish a shared memory buffer pool and add that as an adjunct to the RPC calls.

UPDATE:

Thanks, but can you provide more information on why it's not doable using Winelib? In the guide it says I can link a Linux library to mine I think.

It may be possible to write some glue functions. Doing so may be problematic. But, you may be able to bypass [all] this, based on what I found in the Discord SDK. See below.

The ABI differences: In WinX, the first four arguments are passed in regs and, in linux, the first six arguments are passed in regs. The registers are different. This can be handled with a "thunk" routine that establishes a new stack frame and moves the values to the correct registers for linux. See: https://en.wikipedia.org/wiki/X86_calling_conventions

But, AFAICT, on my machine at least, wine ultimately goes to /usr/bin/wine32 which is a 32 bit executable. But, your linux lib is 64 bits. That issue can't be solved easily. See: Is it possible to use both 64 bit and 32 bit instructions in the same executable in 64 bit Linux? Personally, if I had to do that, I'd go the RPC route.

The library exports 2 functions, I'm only interested in 1, the rest of the functionality is via function pointers (I'm not sure these would work over wine but not there yet). The lib is actually Discord's Game SDK so there's no replacement for it, however this is just a hobby thing.

I just downloaded discord_game_sdk.zip from the website and unzipped it. It has source code example programs. And, the requisite .h files.

There is a lib/x86 subdirectory that has: discord_game_sdk.dll and discord_game_sdk.dll.lib which are 32 bit PE format files. And, there is a lib/x86_64 subdir as well [which has a .so]

So, instead of the linux .so, can you link to those PE format files directly instead? (e.g.) They would probably be loadable with LoadLibrary

I could use sockets if there is no direct way (however wouldn't creating a unix socket have the same issues? I can definitely use localhost though).

Then, consider this a fallback position.

PF_INET socket calls to localhost are quite fast, and [with some "trickery"] you can establish shared memory space between your plugin [under wine] and a server program [which you create] that has the linux .so linked into it.

Body:
I have a Windows-only game that can be extended by plugins and a Linux library I would like to use. The application (Unity game) runs fine under Wine/Proton. I've found that Winelib can do this, and I was following the User's Guide, notably the 5th section which mentions my exact use case.

After some attempts (like removing --single-target arg from winemaker), I got to the point where the Proton debug log keeps showing c000007b which seems to be STATUS_BAD_IMAGE_FORMAT.

Note that I renamed the Linux library (and linked against that), to avoid a potential conflict between that and my wrapper.

I only have a 64-bit version of the library and it is called from C# code using the cdecl calling convention. This is what I've tried so far (and combinations of these):

Added a .spec file with contents (first without the -arch and with different ordinals):

1 cdecl -arch=x86_64 LibraryFunc (long ptr ptr) LibraryFuncWine

Added the library's header and a .c file:

#include "library_header.h"
#include <windef.h> /* Part of the Wine header files */

enum ELibResult WINAPI LibraryFuncWine(Version version, struct CreateParams* params, struct ICore** result)
{
    enum ELibResult ret = LibraryFunc(version, params, result);

    return ret;
}

Used winemaker as winemaker --nosource-fix --dll --nomfc -I. -L. -llinux_library . then make

Copied the .dll.so file all around the game

Copied the .dll.so file to steamapps/common/Proton 5.0/dist/lib64/wine/ and the native library to one level higher (lib64/) and removed the others

Also tried to copy to lib/ instead of lib64/

Added a dll override for the file and set it to builtin

Removed the referenced DLLs (odbc32, ole32, oleaut32, winspool, odbccp32) and libraries (uuid) from the makefile

Add --mno-cygwin to compiler flags

Add -m64 and -fPIC to compiler/linker flags (based on Wine spec files)

I've also tried making a .def file and using that

Used winemaker again with the --nomsvcrt argument added and ran make (the header file includes string.h)

From the Proton log (+module, the others didn't provide any more info for me):

00dc:trace:module:load_dll looking for L"Z:\\D\\a\\library\\path\\library_name" in L"Z:\\D\\gamepath;C:\\windows\\system32;C:\\windows\\system;C:\\windows;C:\\Program Files (x86)\\Steam;.;C:\\windows\\system32;C:\\windows;C:\\windows\\system32\\wbem;C:\\windows\\system32\\WindowsPowershell\\v1.0"
00dc:trace:module:get_load_order looking for L"Z:\\D\\a\\library\\path\\library_name.dll"
00dc:trace:module:get_load_order_value got standard key b for L"library_name"
00dc:trace:module:load_builtin_dll Trying built-in L"library_name.dll"
00dc:trace:module:load_so_dll loading L"\\??\\Z:\\D\\a\\library\\path\\library_name.dll" from so lib "/D/Games/SteamLibrary/steamapps/common/Proton 5.0/dist/bin/../lib64/wine/library_name.dll.so"
00dc:warn:module:load_dll Failed to load module L"Z:\\D\\a\\library\\path\\library_name"; status=c000007b

The same is repeated with and without .dll and starting with lib (library_name.dll, liblibrary_name and liblibrary_name.dll).

I was unable to get any more logs on what exactly goes wrong besides that error code.

On the C# side (ran by Unity in Proton) it results in a DllNotFoundException.

Wine version (winebuild, winegcc): 5.9 (staging) - gcc 9.0.1

Proton version: 5.0 - wine-5.0-603-g068dee4


问:
Setting decimal places in an MDB database
Part of a project I am working on is programmatically create a series of MDB files which will be the final deliverables. The specs from the client ask for some fields in the tables to have 3 decimal places.

I create the mdb files using python at first, and then to be able to alter the columns to DECIMAL (10,3), I use ADODB (C#, .NET 4.0) - as i couldn't find something suitable in Python. Problem though is that this will not be enough for the client. They want to open the MDB and in Design Mode to see the Decimal places for these fields to be set to 3. If they are not, the file is not accepted.

It has now taken me the best part of 3 days trying to come up with a solution. One likely candidate was DAO and the Field2 object but this object has so far eluded me. I am using the Microsoft DAO 3.6 Objects but Field2 doesn't seem to be part of the assembly. And dont even know if this will actually do what is required...

Does anyone know a way to do this? Don't care if its DAO, ADO, OLEDB or any other 3 letter acronym to be honest? How can I get from this:

to this - PROGRAMMATICALLY??

答:
```<code>Public Sub DBF_SetDecPoints(ByVal DBNom As String, ByVal DBTab As String, ByVal Campo As String, ByVal NDEC As Short)
    Dim DB As DAO.Database
    Dim TD As DAO.TableDef
    Dim FD As DAO.Field
    Dim PP As DAO.Property

    If DBF_Exists(DBNom, DBTab, Campo) Then
        'Call DBF_SetProperty(DBNom$, DBTab$, Campo$, "Format", DaoText, "Fixed")
        DB = DAOEngine.Workspaces(0).OpenDatabase(DBNom)
        TD = DB.TableDefs(DBTab)
        FD = TD.Fields(Campo)
        PP = FD.CreateProperty("Format", DaoText, "Fixed")
        On Error Resume Next
        FD.Properties.Append(PP)
        FD.Properties("Format").Value = "Fixed"
        PP = FD.CreateProperty("DecimalPlaces", DaoByte, NDEC)
        FD.Properties.Append(PP)
        FD.Properties("DecimalPlaces").Value = NDEC
        On Error GoTo 0
        DB.Close()
    End If
End Sub
</code>```


问:
Apache Solr Search for Distance Calculation
Hi I am using Apache solr v8

I need to calculate distance between n-dim vector in query search,
how could i do that.

Because I need to calculate distance between face encoding vectors in python's Face_recognition module

答:
Answer:
The distance formula should apply in sort field </p>

```<code>sort : dist(2, db_vector_header, user_vector) asc
</code>```

Body:
Answer:
The distance formula should apply in sort field

sort : dist(2, db_vector_header, user_vector) asc


问:
How to get the Enum Index value in C#
In C, enums, internally equates to an integer. Therefore we can treat data types of enum as integer also.

How to achieve the same with C#?

答:
By default the underlying type of each element in the enum is integer.

```<code>enum Values
{
   A,
   B,
   C
}
</code>```

You can also specify custom value for each item:

```<code>enum Values
{
   A = 10,
   B = 11,
   C = 12
}
int x = (int)Values.A; // x will be 10;
</code>```

Note: By default, the first enumerator has the value 0.

Title: How to get the Enum Index value in C#

Body:
By default the underlying type of each element in the enum is integer.

enum Values
{
   A,
   B,
   C
}

You can also specify custom value for each item:

enum Values
{
   A = 10,
   B = 11,
   C = 12
}
int x = (int)Values.A; // x will be 10;

Note: By default, the first enumerator has the value 0.


问:
How to compile torch 1.5.0 without GPU support?
I want to install pytorch 1.5.0 on AWS lambda. Since the torch library is very large, I need to make it as small as possible to fit within the size limits. My script looks like this so far:

    mkdir python
    docker run \
        --rm \
        -v $(pwd):/build \
        python:3.8 \
        sh -c "
            cd /build;
            pip3 install torch==1.5.0 -t python/torch --no-cache-dir;
            find . -type d -name '__pycache__' | xargs rm -rf;
            find . -type d -name 'tests' | xargs rm -rf;
            find . -type f -name '*.py[co]' | xargs rm -rf;
        ";

    zip -r9 torch.zip python;

```

But the resulting zip file is very large (500+ MB). However, one of the largest files in the installation package is libtorch_cuda.so. Removing that file makes the zip file less than half the size. I know that cuda is a library for GPUs, and since AWS lambda doesn't have a GPU, i don't need this support. But when I remove that file torch will not import correctly.

torch 1.4.0, by comparison, is much smaller because it did not by default include the cuda libraries.

I want torch 1.5.0 without the GPU support.

Is there a way to pip install torch==1.5.0 without gpu support?

答:
PyTorch also distributes CPU only versions, that you can install with pip. Although they aren't published to PyPI, so you need to get them from their own registry.

You can get the CPU version on PyTorch - Getting Started Locally by selecting CUDA: None.

pip install torch==1.5.0+cpu -f https://download.pytorch.org/whl/torch_stable.html
```

Body:
I want to install pytorch 1.5.0 on AWS lambda. Since the torch library is very large, I need to make it as small as possible to fit within the size limits. My script looks like this so far:

    mkdir python
    docker run \
        --rm \
        -v $(pwd):/build \
        python:3.8 \
        sh -c "
            cd /build;
            pip3 install torch==1.5.0 -t python/torch --no-cache-dir;
            find . -type d -name '__pycache__' | xargs rm -rf;
            find . -type d -name 'tests' | xargs rm -rf;
            find . -type f -name '*.py[co]' | xargs rm -rf;
        ";

    zip -r9 torch.zip python;

But the resulting zip file is very large (500+ MB). However, one of the largest files in the installation package is libtorch_cuda.so. Removing that file makes the zip file less than half the size. I know that cuda is a library for GPUs, and since AWS lambda doesn't have a GPU, i don't need this support. But when I remove that file torch will not import correctly.

torch 1.4.0, by comparison, is much smaller because it did not by default include the cuda libraries.

I want torch 1.5.0 without the GPU support.

Is there a way to pip install torch==1.5.0 without gpu support?


问:
Optimal way to store data from Pandas to Snowflake
The dataframe is huge (7-8 million rows). Tried to_sql with chunksize = 5000 but it never finished.

Using,

```<code>from sqlalchemy import create_engine
from snowflake.sqlalchemy import URL

df.to_sql(snowflake_table , engine, if_exists='replace', index=False, index_label=None, chunksize=20000)
</code>```

What are other optimal solutions for storing data into SF from Pandas DF? Or what am I doing wrong here? The DF is usually of size 7-10 million rows.

答: pandas does an 'insert into ...' with multiple values behind the scene. Snowflake has a restriction up to 16384 records on ingestion. Please change your chunksize=16384.</p>

Body:
The dataframe is huge (7-8 million rows). Tried to_sql with chunksize = 5000 but it never finished.

Using,

from sqlalchemy import create_engine
from snowflake.sqlalchemy import URL

df.to_sql(snowflake_table , engine, if_exists='replace', index=False, index_label=None, chunksize=20000)

What are other optimal solutions for storing data into SF from Pandas DF? Or what am I doing wrong here? The DF is usually of size 7-10 million rows.