问:
Github Uploading Project(push issue)
I'm stuck here in the process of uploading.
    $ git push -u origin master
    To https://github.com/akhilrajarj/Digiledge.git
     ! [rejected]        master -> master (non-fast-forward)
    error: failed to push some refs to 'https://github.com/akhilrajarj/Digiledge.git'
    hint: Updates were rejected because the tip of your current branch is behind
    hint: its remote counterpart. Integrate the remote changes (e.g.
    hint: 'git pull ...') before pushing again.
    hint: See the 'Note about fast-forwards' in 'git push --help' for details.</p>

答:
You can forcibly push to origin using this command mentioned here

But keep in mind, you may lose some history points in the remote branch

Title: Github Uploading Project(push issue)


来源: stackexchange

问:
Gitlab-runner run too long
I made a static site and now trying to configure GitLab CI/CD.

The source code for the site is on a remote server.

This is my gitlab-ci.yml

```<code>image: ruby:2.6

variables:
  JEKYLL_ENV: production

before_script:
  - gem install bundler
  - bundle install

deploy:
  stage: deploy
  script:
  - bundle exec jekyll build --watch

  only:
    - master
</code>```

I use --watch because without using --watch job passed correctly, changes are displayed on the local computer, but no updates are displayed on the remote server.

There is a line in the answer:

Auto-regeneration: disabled for '/ builds / wiki / docplus'. Use --watch to enable

But with --watch I push my commits and gitlab-runner runs too long and job failed

```<code>$ bundle exec jekyll build --watch
Configuration file: /builds/wiki/docplus/_config.yml
            Source: /builds/wiki/docplus
       Destination: /builds/wiki/docplus/_site
 Incremental build: disabled. Enable with --incremental
      Generating...
                    done in 1.863 seconds.
 Auto-regeneration: enabled for '/builds/wiki/docplus'
Pulling docker image gitlab/gitlab-runner-helper:x86_64-003fe500 ...
ERROR: Job failed: execution took longer than 1h0m0s seconds
</code>```

What's wrong?

答:
Update your deploy.script to just build (without --watch):

deploy:
  stage: deploy
  script:
  - bundle exec jekyll build
```

ContentLicense: CC BY-SA 4.0

Title: Gitlab-runner run too long

Body:
I made a static site and now trying to configure GitLab CI/CD.

The source code for the site is on a remote server.

This is my gitlab-ci.yml

image: ruby:2.6

variables:
  JEKYLL_ENV: production

before_script:
  - gem install bundler
  - bundle install

deploy:
  stage: deploy
  script:
  - bundle exec jekyll build --watch

  only:
    - master

I use --watch because without using --watch job passed correctly, changes are displayed on the local computer, but no updates are displayed on the remote server.

There is a line in the answer:

Auto-regeneration: disabled for '/ builds / wiki / docplus'. Use --watch to enable

But with --watch I push my commits and gitlab-runner runs too long and job failed

$ bundle exec jekyll build --watch
Configuration file: /builds/wiki/docplus/_config.yml
            Source: /builds/wiki/docplus
       Destination: /builds/wiki/docplus/_site
 Incremental build: disabled. Enable with --incremental
      Generating...
                    done in 1.863 seconds.
 Auto-regeneration: enabled for '/builds/wiki/docplus'
Pulling docker image gitlab/gitlab-runner-helper:x86_64-003fe500 ...
ERROR: Job failed: execution took longer than 1h0m0s seconds

What's wrong?


问:
Scikit-Learn: Labels don't match in Confusion Matrix
Let's say I have an array with (potentially) 43 different values, e.g.

```<code>import pandas as pd
Y_test = pd.Series([4,4,4,42,42,0,1,1,19], dtype=int)
Y_hat = pd.Series([4,4,2,32,42,0,5,5,19], dtype=int)
</code>```

Whenever I try to plot the confusion matrix with:

```<code>def create_conf_mat(index, y_test, y_hat):
    cm = confusion_matrix(y_test, y_hat)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(cm)
    plt.title(f'Confusion Matrix ({index} features, 1 outcome)')
    fig.colorbar(cax)
    plt.xlabel('Predicted')
    plt.ylabel('Actual')
    plt.savefig(f'confm_{index}.png')
    plt.savefig(f'confm_{index}.svg')
    plt.savefig(f'confm_{index}.pdf')
    return
</code>```

I don't get the labels [0, 1, 2, 4, 5, 19, 32, 42] but [0, 1, 2, 3, 4, 5, 6, 7].
I tried to set the labels explicitly by using the unique values in y_test/y_hat as the labels argument but it doesn't work either. I even tried to convert the integer values as strings but by doing so, sklearn complains that at least one label has to be in y_true.
Does anyone know how I could get the actual values within y_test and y_pred to be plotted as labels within the confusion matrix?

答:
As hinted in the documentation, about the labels parameter to confusion_matrix:

If None is given, those that appear at least once in y_true or y_pred are used in sorted order.

So, we need to grab together both lists, and extract the list of unique numbers:

```<code>labels = np.unique(np.concatenate([y_test.values, y_hat.values]))
plt.xticks(range(len(labels)), labels)
plt.yticks(range(len(labels)), labels)
</code>```

Please note that the latest version of 'scikit-learn' now includes an integrated function to plot a confusion matrix with example code.

Body:
Let's say I have an array with (potentially) 43 different values, e.g.

import pandas as pd
Y_test = pd.Series([4,4,4,42,42,0,1,1,19], dtype=int)
Y_hat = pd.Series([4,4,2,32,42,0,5,5,19], dtype=int)

Whenever I try to plot the confusion matrix with:

def create_conf_mat(index, y_test, y_hat):
    cm = confusion_matrix(y_test, y_hat)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(cm)
    plt.title(f'Confusion Matrix ({index} features, 1 outcome)')
    fig.colorbar(cax)
    plt.xlabel('Predicted')
    plt.ylabel('Actual')
    plt.savefig(f'confm_{index}.png')
    plt.savefig(f'confm_{index}.svg')
    plt.savefig(f'confm_{index}.pdf')
    return

I don't get the labels [0, 1, 2, 4, 5, 19, 32, 42] but [0, 1, 2, 3, 4, 5, 6, 7].
I tried to set the labels explicitly by using the unique values in y_test/y_hat as the labels argument but it doesn't work either. I even tried to convert the integer values as strings but by doing so, sklearn complains that at least one label has to be in y_true.
Does anyone know how I could get the actual values within y_test and y_pred to be plotted as labels within the confusion matrix?

Body:
As hinted in the documentation, about the labels parameter to confusion_matrix:

If None is given, those that appear at least once in y_true or y_pred are used in sorted order.

So, we need to grab together both lists, and extract the list of unique numbers:

labels = np.unique(np.concatenate([y_test.values, y_hat.values]))
plt.xticks(range(len(labels)), labels)
plt.yticks(range(len(labels)), labels)

Please note that the latest version of 'scikit-learn' now includes an integrated function to plot a confusion matrix with example code.


问:
RegEx optional group with optional sub-group
I have a set of strings with fairly inconsistent naming, that should be structured enough to be divided into groups though.

Here's an excerpt:

```<code>test test 1970-2020 w15.txt
test 1970-2020 w15.csv
test  1990-99 q1 .txt
test 1981 w15 .csv
test test  w15.csv
</code>```

I am trying to extract information by groups (test-name, (year)?, suffix, type) using the following RegEx:

```<code>(.*)\s+([0-9]+(\-[0-9]+)?\s+)?((w|q)[0-9]+(\s+)?)(\..*)$
</code>```

It works except for the optional group matching the years (interval of year's, single year or no year at all).
What am I missing to make the pattern work?

Here's also a link to RegEx101 for testing:

https://regex101.com/r/wG3aM3/817

答:
You could make the pattern a bit more specific and make the content of the year optional

```<code>^(.*?)\s+((?:\d{4}(?:-(?:\d{4}|\d{2}))?)?)\s+([wq][0-9]+)\s*(\.\w+)$
</code>```

Explanation

^ Start of string

(.*?) Capture group 1 Match 0+ times any char except a newline non greedy

\s+ Match 1+ whitespace chars

( Capture group 2

(?: Non capture group

\d{4}(?:-(?:\d{4}|\d{2}))? Match 4 digits and optionally - and 2 or 4 digits

)? Close non capture group and make the year optional

) Close group 2

\s+ Match 1+ whitespace chars

([wq][0-9]+) Capture group 3 Match either w or q and 1+ digits 0-9

\s* Match 0+ whitespace chars

(\.\w+) Capture group 4, match a dot and 1+ word characters

$ End of string

Regex demo

Note that \s could also match a newline.

Body:
I have a set of strings with fairly inconsistent naming, that should be structured enough to be divided into groups though.

Here's an excerpt:

test test 1970-2020 w15.txt
test 1970-2020 w15.csv
test  1990-99 q1 .txt
test 1981 w15 .csv
test test  w15.csv

I am trying to extract information by groups (test-name, (year)?, suffix, type) using the following RegEx:

(.*)\s+([0-9]+(\-[0-9]+)?\s+)?((w|q)[0-9]+(\s+)?)(\..*)$

It works except for the optional group matching the years (interval of year's, single year or no year at all).
What am I missing to make the pattern work?

Here's also a link to RegEx101 for testing:

https://regex101.com/r/wG3aM3/817

Body:
You could make the pattern a bit more specific and make the content of the year optional

^(.*?)\s+((?:\d{4}(?:-(?:\d{4}|\d{2}))?)?)\s+([wq][0-9]+)\s*(\.\w+)$

Explanation

^ Start of string

(.*?) Capture group 1 Match 0+ times any char except a newline non greedy

\s+ Match 1+ whitespace chars

( Capture group 2

(?: Non capture group

\d{4}(?:-(?:\d{4}|\d{2}))? Match 4 digits and optionally - and 2 or 4 digits

)? Close non capture group and make the year optional

) Close group 2

\s+ Match 1+ whitespace chars

([wq][0-9]+) Capture group 3 Match either w or q and 1+ digits 0-9

\s* Match 0+ whitespace chars

(\.\w+) Capture group 4, match a dot and 1+ word characters

$ End of string

Regex demo

Note that \s could also match a newline.


问:
Android SMS Broadcast Receiver doesn't work
Hi I'm trying to catch the sms content and use in my app, so I made a BroadcastReceiver with Permission and Manifests But when the device receive sms, my code doesn't run which means that the BroadcastReceiver doesn't fire.
I also checked many Articles inside and outside here, there're some:

Android Sms Receiver Result to Main Activity
SMS receiver didn't work

Android SMS Receiver not working

Broadcast Receiver not working for SMS

Here is a part of my Manifest:

```<code><uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<application.
...
...
<receiver android:name="com.example.android.receiver.SmsReceiver"
            android:permission="android.permission.BROADCAST_SMS">
            <intent-filter android:priority="2147483647">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>
</application>
</code>```

And This is my Receiver

```<code>public class SmsReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "SMS Received!", Toast.LENGTH_LONG).show();
    }
}
</code>```

I also tried to register the receiver dynamically inside activity onCreate() but nothing changed

```<code>IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
intentFilter.setPriority(2147483647);
registerReceiver(new SmsReceiver(), intentFilter);
</code>```

Does anyone know where is the problem? It should just Toast that a message is recieved so I can continue work but the receiver doesn't seem to even fire

答:
You should read Automatic SMS Verification.

public abstract Task startSmsRetriever ()

Starts SmsRetriever, which waits for a matching SMS message until timeout (5 minutes). The matching SMS message will be sent via a Broadcast Intent with action
SmsRetriever.SMS_RETRIEVED_ACTION.

When you are ready to verify the user's phone number, get an instance of the SmsRetrieverClient object, call startSmsRetriever, and attach success and failure listeners to the SMS retrieval task:

```<code>SmsRetrieverClient mClient = SmsRetriever.getClient(this);
Task<Void> mTask = mClient.startSmsRetriever();
mTask.addOnSuccessListener(new OnSuccessListener<Void>() {
  @Override public void onSuccess(Void aVoid) {
    Toast.makeText(YourActivity.this, "SMS Retriever starts", Toast.LENGTH_LONG).show();
  }
});
mTask.addOnFailureListener(new OnFailureListener() {
  @Override public void onFailure(@NonNull Exception e) {
    Toast.makeText(YourActivity.this, "Error", Toast.LENGTH_LONG).show();
  }
});
</code>```

When a verification message is received on the user's device, Play services explicitly broadcasts to your app a SmsRetriever.SMS_RETRIEVED_ACTION Intent, which contains the text of the message. Use a BroadcastReceiver to receive this verification message.

```<code>public void onReceive(Context context, Intent intent) {
    if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction())) {
      Bundle extras = intent.getExtras();
      Status status = (Status) extras.get(SmsRetriever.EXTRA_STATUS);

      switch(status.getStatusCode()) {
        case CommonStatusCodes.SUCCESS:
          // Get SMS message contents
          String message = (String) extras.get(SmsRetriever.EXTRA_SMS_MESSAGE);
          // Extract one-time code from the message and complete verification
          // by sending the code back to your server.
          break;
        case CommonStatusCodes.TIMEOUT:
          // Waiting for SMS timed out (5 minutes)
          // Handle the error ...
          break;
      }
    }
  }
</code>```

Register Your BroadcastReceiver with the intent filter com.google.android.gms.auth.api.phone.SMS_RETRIEVED in your app's AndroidManifest.xml file.

```<code><receiver android:name=".YourBroadcastReceiver" android:exported="true">
    <intent-filter>
        <action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED"/>
    </intent-filter>
</receiver>
</code>```

Finally, Register your BroadcastReceiver in your onCreate() section.

```<code>IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(SmsRetriever.SMS_RETRIEVED_ACTION);
getApplicationContext().registerReceiver(broadcastReceiverOBJ, intentFilter);
</code>```

For Demo purpose you should read Automatic SMS Verification Android

ContentLicense: CC BY-SA 3.0

Body:
Hi I'm trying to catch the sms content and use in my app, so I made a BroadcastReceiver with Permission and Manifests But when the device receive sms, my code doesn't run which means that the BroadcastReceiver doesn't fire.
I also checked many Articles inside and outside here, there're some:

Android Sms Receiver Result to Main Activity
SMS receiver didn't work

Android SMS Receiver not working

Broadcast Receiver not working for SMS

Here is a part of my Manifest:

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<application.
...
...
<receiver android:name="com.example.android.receiver.SmsReceiver"
            android:permission="android.permission.BROADCAST_SMS">
            <intent-filter android:priority="2147483647">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>
</application>

And This is my Receiver

public class SmsReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "SMS Received!", Toast.LENGTH_LONG).show();
    }
}

I also tried to register the receiver dynamically inside activity onCreate() but nothing changed

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
intentFilter.setPriority(2147483647);
registerReceiver(new SmsReceiver(), intentFilter);

Does anyone know where is the problem? It should just Toast that a message is recieved so I can continue work but the receiver doesn't seem to even fire

Body:
You should read Automatic SMS Verification.

public abstract Task startSmsRetriever ()

Starts SmsRetriever, which waits for a matching SMS message until timeout (5 minutes). The matching SMS message will be sent via a Broadcast Intent with action
SmsRetriever.SMS_RETRIEVED_ACTION.

When you are ready to verify the user's phone number, get an instance of the SmsRetrieverClient object, call startSmsRetriever, and attach success and failure listeners to the SMS retrieval task:

SmsRetrieverClient mClient = SmsRetriever.getClient(this);
Task<Void> mTask = mClient.startSmsRetriever();
mTask.addOnSuccessListener(new OnSuccessListener<Void>() {
  @Override public void onSuccess(Void aVoid) {
    Toast.makeText(YourActivity.this, "SMS Retriever starts", Toast.LENGTH_LONG).show();
  }
});
mTask.addOnFailureListener(new OnFailureListener() {
  @Override public void onFailure(@NonNull Exception e) {
    Toast.makeText(YourActivity.this, "Error", Toast.LENGTH_LONG).show();
  }
});

When a verification message is received on the user's device, Play services explicitly broadcasts to your app a SmsRetriever.SMS_RETRIEVED_ACTION Intent, which contains the text of the message. Use a BroadcastReceiver to receive this verification message.

public void onReceive(Context context, Intent intent) {
    if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction())) {
      Bundle extras = intent.getExtras();
      Status status = (Status) extras.get(SmsRetriever.EXTRA_STATUS);

      switch(status.getStatusCode()) {
        case CommonStatusCodes.SUCCESS:
          // Get SMS message contents
          String message = (String) extras.get(SmsRetriever.EXTRA_SMS_MESSAGE);
          // Extract one-time code from the message and complete verification
          // by sending the code back to your server.
          break;
        case CommonStatusCodes.TIMEOUT:
          // Waiting for SMS timed out (5 minutes)
          // Handle the error ...
          break;
      }
    }
  }

Register Your BroadcastReceiver with the intent filter com.google.android.gms.auth.api.phone.SMS_RETRIEVED in your app's AndroidManifest.xml file.

<receiver android:name=".YourBroadcastReceiver" android:exported="true">
    <intent-filter>
        <action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED"/>
    </intent-filter>
</receiver>

Finally, Register your BroadcastReceiver in your onCreate() section.

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(SmsRetriever.SMS_RETRIEVED_ACTION);
getApplicationContext().registerReceiver(broadcastReceiverOBJ, intentFilter);

For Demo purpose you should read Automatic SMS Verification Android


问:
GCS bucket update frequency ,how do I set it?
I am trying to use logstash to push messages to the GCS using the output plugin below. I am able to see the msgs in the bucket, however they appear every hour and not real time. Where can I change the frequency of the log send?

https://www.elastic.co/guide/en/logstash/current/plugins-outputs-google_cloud_storage.html

P.S: I tried to add this to my config file but of no use:
flush_interval_secs => 2

my config looks something like this:

```<code>input{
kafka {
    zk_connect => "xxxxxxxxxxxxxxxxxxxxxx"
    group_id => "yyyyyyyyyyyyyyyyyyyyyyyyyyyy"
    topic_id => "zzzzzzzzzzzzzzzzz"
    reset_beginning => true
    auto_offset_reset => "smallest"
    }
}
output
{
    google_cloud_storage {
       bucket => "aaaa/bbb"
       flush_interval_secs => 15
    }
    stdout
         {
              codec => rubydebug
         }
}
</code>```

答:
From Documentation:

Uploader interval when uploading new files to GCS. Adjust time based on your time pattern (for example, for hourly files, this interval can be around one hour).

Default value is 60.

Example:

```<code>output {
   google_cloud_storage {
     bucket => "my_bucket"                                     (required)
     date_pattern => "%Y-%m-%dT%H:00"                          (optional)
     uploader_interval_secs => 60                              (optional)
   }
}
</code>```

Additionally, you can also set the date_pattern, which is the time pattern for log file.

Body:
I am trying to use logstash to push messages to the GCS using the output plugin below. I am able to see the msgs in the bucket, however they appear every hour and not real time. Where can I change the frequency of the log send?

https://www.elastic.co/guide/en/logstash/current/plugins-outputs-google_cloud_storage.html

P.S: I tried to add this to my config file but of no use:
flush_interval_secs => 2

my config looks something like this:

input{
kafka {
    zk_connect => "xxxxxxxxxxxxxxxxxxxxxx"
    group_id => "yyyyyyyyyyyyyyyyyyyyyyyyyyyy"
    topic_id => "zzzzzzzzzzzzzzzzz"
    reset_beginning => true
    auto_offset_reset => "smallest"
    }
}
output
{
    google_cloud_storage {
       bucket => "aaaa/bbb"
       flush_interval_secs => 15
    }
    stdout
         {
              codec => rubydebug
         }
}

Body:
From Documentation:

Uploader interval when uploading new files to GCS. Adjust time based on your time pattern (for example, for hourly files, this interval can be around one hour).

Default value is 60.

Example:

output {
   google_cloud_storage {
     bucket => "my_bucket"                                     (required)
     date_pattern => "%Y-%m-%dT%H:00"                          (optional)
     uploader_interval_secs => 60                              (optional)
   }
}

Additionally, you can also set the date_pattern, which is the time pattern for log file.


问:
Problem updating object properties inside a promise-aware for loop in javascript
I am having a problem accessing updated object properties inside a for loop in Javascript.

```<code>let distribution = await ctx.db.query.distribution(
      {
        where: {
          id,
        },
      },
      `
    {
      id
      clients {
        id
        wallet {
          amount
        }
      }
    }`,
  );

let count = 0;

for (const client of distribution.clients) {
   await ctx.db.mutation.updateWallet({
       where: {
         id: client.id,
       },
       data: {
         amount: client.wallet.amount + someAmount,
       },
    });
    distribution.clients[count].wallet.amount = client.wallet.amount + someAmount;
    count++;
  }
</code>```

In the above code, I execute a graphQL query to fetch all information associated with a distribution. I then want to iterate through the associated clients array and update each client’s wallet. The same client may appear multiple times in this array and each time
their wallet must be updated.

A problem occurs when a wallet has already been updated in a previous iteration. When I try to update the amount a second time, the client.wallet.amount reflects the initial value of the wallet rather than value after the first update.

Clearly the property clients[count].wallet.amount attribute of the distribution object isn’t being updated after each iteration. I thought javascript objects were passed by reference, and therefore the object should be updated after each iteration.

Could someone explain to me why the distribution object property is not being updated and how I can update it correctly?

FYI: I cannot use other loops such as forEach as it is not promise-aware and does not suppose async/await

答:
A problem occurs when a wallet has already been updated in a previous iteration.

Each wallet object is only modified once when the loop runs. Two or more wallet objects in the array may represent the same row in the database, but they are still distinct objects -- changing one will not change the other.

```<code>const wallets = [
  { id: 1, amount: 0 },
  { id: 2, amount: 0 },
  { id: 1, amount: 0 },
]
for (const wallet of wallets) {
  wallet.amount = wallet.amount + 5
}
console.log(wallets[0]) // { id: 1, amount: 5 }
console.log(wallets[1]) // { id: 2, amount: 5 }
console.log(wallets[2]) // { id: 1, amount: 5 }
</code>```

Note that we don't need to use a count variable at all. Because the const wallet is a reference to the original object in the array, if we modify it, we modify the original object.

If you want need to track the amounts by ID, you'd need to implement that logic. For example:

```<code>const wallets = [
  { id: 1, amount: 0 },
  { id: 2, amount: 0 },
  { id: 1, amount: 0 },
]
const amountsById = {}
for (const wallet of wallets) {
  amountsById[wallet.id] = (amountsById[wallet.id] || wallet.amount) + 5
}
const updatedWallets = wallets.map(wallet => ({
  ...wallet,
  amount: amountsById[wallet.id],
}))
console.log(updatedWallets[0]) // { id: 1, amount: 10 }
console.log(updatedWallets[1]) // { id: 2, amount: 5 }
console.log(updatedWallets[2]) // { id: 1, amount: 10 }
</code>```

Body:
I am having a problem accessing updated object properties inside a for loop in Javascript.

let distribution = await ctx.db.query.distribution(
      {
        where: {
          id,
        },
      },
      `
    {
      id
      clients {
        id
        wallet {
          amount
        }
      }
    }`,
  );

let count = 0;

for (const client of distribution.clients) {
   await ctx.db.mutation.updateWallet({
       where: {
         id: client.id,
       },
       data: {
         amount: client.wallet.amount + someAmount,
       },
    });
    distribution.clients[count].wallet.amount = client.wallet.amount + someAmount;
    count++;
  }

In the above code, I execute a graphQL query to fetch all information associated with a distribution. I then want to iterate through the associated clients array and update each client’s wallet. The same client may appear multiple times in this array and each time
their wallet must be updated.

A problem occurs when a wallet has already been updated in a previous iteration. When I try to update the amount a second time, the client.wallet.amount reflects the initial value of the wallet rather than value after the first update.

Clearly the property clients[count].wallet.amount attribute of the distribution object isn’t being updated after each iteration. I thought javascript objects were passed by reference, and therefore the object should be updated after each iteration.

Could someone explain to me why the distribution object property is not being updated and how I can update it correctly?

FYI: I cannot use other loops such as forEach as it is not promise-aware and does not suppose async/await

Body:
A problem occurs when a wallet has already been updated in a previous iteration.

Each wallet object is only modified once when the loop runs. Two or more wallet objects in the array may represent the same row in the database, but they are still distinct objects -- changing one will not change the other.

const wallets = [
  { id: 1, amount: 0 },
  { id: 2, amount: 0 },
  { id: 1, amount: 0 },
]
for (const wallet of wallets) {
  wallet.amount = wallet.amount + 5
}
console.log(wallets[0]) // { id: 1, amount: 5 }
console.log(wallets[1]) // { id: 2, amount: 5 }
console.log(wallets[2]) // { id: 1, amount: 5 }

Note that we don't need to use a count variable at all. Because the const wallet is a reference to the original object in the array, if we modify it, we modify the original object.

If you want need to track the amounts by ID, you'd need to implement that logic. For example:

const wallets = [
  { id: 1, amount: 0 },
  { id: 2, amount: 0 },
  { id: 1, amount: 0 },
]
const amountsById = {}
for (const wallet of wallets) {
  amountsById[wallet.id] = (amountsById[wallet.id] || wallet.amount) + 5
}
const updatedWallets = wallets.map(wallet => ({
  ...wallet,
  amount: amountsById[wallet.id],
}))
console.log(updatedWallets[0]) // { id: 1, amount: 10 }
console.log(updatedWallets[1]) // { id: 2, amount: 5 }
console.log(updatedWallets[2]) // { id: 1, amount: 10 }


问:
Node.js - Calling asynchronous functions whenever a toggle is changed
In my website, I have a toggle button that determines whether or not a given user will receive messages from a given source. Whenever this toggle is changed, an asynchronous function needs to be called. However, if the toggle is changed, and then it is quickly changed again, my program must wait for the previous asynchronous call to finish. Here are my two functions that call the asynchronous functions

```<code>_enable() {
    let params = determineSubscriptionParams(this.endpoint, this.level);

    SNS_CLIENT.subscribe(params, (err, data) => {
        if (err) {
            throw err;
        }
        else {
            // do stuff here
        }
    });
}

_disable() {
    let params = {
        SubscriptionArn: this.subscriptionArn
    }

    SNS_CLIENT.unsubscribe(params, (err, data) => {
        if (err) {
            throw err;
        }
        else {
            // do stuff here
        }
    });
}
</code>```

Both of these functions are members of a class and the subscribe and unsubscribe functions are the asynchronous calls

答:
You are looking for a lock for critical sections of code. If you don't want to implement your own, you could use async-lock to accomplish this.

This is will make the second request made in quick succession unable to enter the critical part of the code before the first request has released it.

Body:
In my website, I have a toggle button that determines whether or not a given user will receive messages from a given source. Whenever this toggle is changed, an asynchronous function needs to be called. However, if the toggle is changed, and then it is quickly changed again, my program must wait for the previous asynchronous call to finish. Here are my two functions that call the asynchronous functions

_enable() {
    let params = determineSubscriptionParams(this.endpoint, this.level);

    SNS_CLIENT.subscribe(params, (err, data) => {
        if (err) {
            throw err;
        }
        else {
            // do stuff here
        }
    });
}

_disable() {
    let params = {
        SubscriptionArn: this.subscriptionArn
    }

    SNS_CLIENT.unsubscribe(params, (err, data) => {
        if (err) {
            throw err;
        }
        else {
            // do stuff here
        }
    });
}

Both of these functions are members of a class and the subscribe and unsubscribe functions are the asynchronous calls


问:
shiny: start the app with hidden tabs, with NO delay
I would like to build an application and some of the tabs will be hidden to the user until he types the right password. I know how to do this with shinyjs::hideTab:

```<code>library(shiny);library(shinyjs)
ui <- fluidPage(useShinyjs(),
  navbarPage("hello", id="hello",
             tabPanel("home", br(), h3("this is home"),passwordInput("pass", "enter 'password' to see the tabs: "),actionButton("enter", "enter")),
             tabPanel("tab2", br(), h4("this is tab2")),
             tabPanel("tab3 with a lot of stuff in it", br(), h4("this is tab3"))))
server <- function(input, output, session) {
  hideTab("hello", "tab2"); hideTab("hello", "tab3 with a lot of stuff in it")
  observeEvent(input$enter, {
    if (input$pass == "password"){showTab("hello", "tab2"); showTab("hello", "tab3 with a lot of stuff in it")}})}
shinyApp(ui, server)
</code>```

However there is a little "thing". In my application, the hidden tabs have a lot of stuff, like widgets, uiOutputs, plots, images, file reading in global.R, etc. The consequence is that the loading time is higher and during this loading time of the application (before the hideTab instruction gets run) the user actually sees the hidden tab and can even click on them and see what's inside. They stay "visible" for like 1 second and then get hidden.

Is there a way to make them immediately hidden, before the UI gets built? I'd prefer a solution without having to put all my ui code into the server.R script...

Thanks

答:
I solved this problem creating a new function (above the UI definition) to include the style="display:none; on the right li tags:

```<code>tabsethidepanels<-function(tag, indexes = NULL) {
  if (class(tag) == "shiny.tag" && tag$name == "div" && tag$attribs$class == "tabbable") {
    if (is.null(indexes)) indexes<-seq_along(tag$children[[1]]$children[[1]])
    for (i in indexes) tag$children[[1]]$children[[1]][[i]]$attribs<-c(tag$children[[1]]$children[[1]][[i]]$attribs, list(style="display:none;"))
    tag
  } else stop("tag must be a tabsetPanel!", call. = F)
}
</code>```

And define the tabset accordingly:

```<code>tabsethidepanels(
  tabsetPanel(
    id = "mytab",
    selected = "tab7-not2hide",
    tabPanel("tab1"),
    tabPanel("tab2"),
    tabPanel("tab3"),
    tabPanel("tab4"),
    tabPanel("tab5"),
    tabPanel("tab6"),
    tabPanel("tab7-not2hide")
  ),
  indexes = 1:6
)
</code>```

The "indexes" field are usefull to select only the right tabs to hide:

```<code><div class="tabbable">
  <ul class="nav nav-tabs shiny-tab-input" id="mytab" data-tabsetid="2818">
    <li style="display:none;">
      <a href="#tab-2818-1" data-toggle="tab" data-value="tab1">tab1</a>
    </li>
    <li style="display:none;">
      <a href="#tab-2818-2" data-toggle="tab" data-value="tab2">tab2</a>
    </li>
    <li style="display:none;">
      <a href="#tab-2818-3" data-toggle="tab" data-value="tab3">tab3</a>
    </li>
    <li style="display:none;">
      <a href="#tab-2818-4" data-toggle="tab" data-value="tab4">tab4</a>
    </li>
    <li style="display:none;">
      <a href="#tab-2818-5" data-toggle="tab" data-value="tab5">tab5</a>
    </li>
    <li style="display:none;">
      <a href="#tab-2818-6" data-toggle="tab" data-value="tab6">tab6</a>
    </li>
    <li class="active">
      <a href="#tab-2818-7" data-toggle="tab" data-value="tab7-not2hide">tab7-not2hide</a>
    </li>
  </ul>
  <div class="tab-content" data-tabsetid="2818">
    <div class="tab-pane" data-value="tab1" id="tab-2818-1"></div>
    <div class="tab-pane" data-value="tab2" id="tab-2818-2"></div>
    <div class="tab-pane" data-value="tab3" id="tab-2818-3"></div>
    <div class="tab-pane" data-value="tab4" id="tab-2818-4"></div>
    <div class="tab-pane" data-value="tab5" id="tab-2818-5"></div>
    <div class="tab-pane" data-value="tab6" id="tab-2818-6"></div>
    <div class="tab-pane active" data-value="tab7-not2hide" id="tab-2818-7"></div>
  </div>
</div>
</code>```

Remember to select a tab not to hide as active selected = "tab7-not2hide".

If you need to hide all tabs I sugest to create a "blank" tabPanel, select his one as active and hide all tabs with indexes = NULL.

Body:
I would like to build an application and some of the tabs will be hidden to the user until he types the right password. I know how to do this with shinyjs::hideTab:

library(shiny);library(shinyjs)
ui <- fluidPage(useShinyjs(),
  navbarPage("hello", id="hello",
             tabPanel("home", br(), h3("this is home"),passwordInput("pass", "enter 'password' to see the tabs: "),actionButton("enter", "enter")),
             tabPanel("tab2", br(), h4("this is tab2")),
             tabPanel("tab3 with a lot of stuff in it", br(), h4("this is tab3"))))
server <- function(input, output, session) {
  hideTab("hello", "tab2"); hideTab("hello", "tab3 with a lot of stuff in it")
  observeEvent(input$enter, {
    if (input$pass == "password"){showTab("hello", "tab2"); showTab("hello", "tab3 with a lot of stuff in it")}})}
shinyApp(ui, server)

However there is a little "thing". In my application, the hidden tabs have a lot of stuff, like widgets, uiOutputs, plots, images, file reading in global.R, etc. The consequence is that the loading time is higher and during this loading time of the application (before the hideTab instruction gets run) the user actually sees the hidden tab and can even click on them and see what's inside. They stay "visible" for like 1 second and then get hidden.

Is there a way to make them immediately hidden, before the UI gets built? I'd prefer a solution without having to put all my ui code into the server.R script...

Thanks

Body:
I solved this problem creating a new function (above the UI definition) to include the style="display:none; on the right li tags:

tabsethidepanels<-function(tag, indexes = NULL) {
  if (class(tag) == "shiny.tag" && tag$name == "div" && tag$attribs$class == "tabbable") {
    if (is.null(indexes)) indexes<-seq_along(tag$children[[1]]$children[[1]])
    for (i in indexes) tag$children[[1]]$children[[1]][[i]]$attribs<-c(tag$children[[1]]$children[[1]][[i]]$attribs, list(style="display:none;"))
    tag
  } else stop("tag must be a tabsetPanel!", call. = F)
}

And define the tabset accordingly:

tabsethidepanels(
  tabsetPanel(
    id = "mytab",
    selected = "tab7-not2hide",
    tabPanel("tab1"),
    tabPanel("tab2"),
    tabPanel("tab3"),
    tabPanel("tab4"),
    tabPanel("tab5"),
    tabPanel("tab6"),
    tabPanel("tab7-not2hide")
  ),
  indexes = 1:6
)

The "indexes" field are usefull to select only the right tabs to hide:

<div class="tabbable">
  <ul class="nav nav-tabs shiny-tab-input" id="mytab" data-tabsetid="2818">
    <li style="display:none;">
      <a href="#tab-2818-1" data-toggle="tab" data-value="tab1">tab1</a>
    </li>
    <li style="display:none;">
      <a href="#tab-2818-2" data-toggle="tab" data-value="tab2">tab2</a>
    </li>
    <li style="display:none;">
      <a href="#tab-2818-3" data-toggle="tab" data-value="tab3">tab3</a>
    </li>
    <li style="display:none;">
      <a href="#tab-2818-4" data-toggle="tab" data-value="tab4">tab4</a>
    </li>
    <li style="display:none;">
      <a href="#tab-2818-5" data-toggle="tab" data-value="tab5">tab5</a>
    </li>
    <li style="display:none;">
      <a href="#tab-2818-6" data-toggle="tab" data-value="tab6">tab6</a>
    </li>
    <li class="active">
      <a href="#tab-2818-7" data-toggle="tab" data-value="tab7-not2hide">tab7-not2hide</a>
    </li>
  </ul>
  <div class="tab-content" data-tabsetid="2818">
    <div class="tab-pane" data-value="tab1" id="tab-2818-1"></div>
    <div class="tab-pane" data-value="tab2" id="tab-2818-2"></div>
    <div class="tab-pane" data-value="tab3" id="tab-2818-3"></div>
    <div class="tab-pane" data-value="tab4" id="tab-2818-4"></div>
    <div class="tab-pane" data-value="tab5" id="tab-2818-5"></div>
    <div class="tab-pane" data-value="tab6" id="tab-2818-6"></div>
    <div class="tab-pane active" data-value="tab7-not2hide" id="tab-2818-7"></div>
  </div>
</div>

Remember to select a tab not to hide as active selected = "tab7-not2hide".

If you need to hide all tabs I sugest to create a "blank" tabPanel, select his one as active and hide all tabs with indexes = NULL.


问:
PHPmailer not connecting to office365 SMTP
I have a script that uses phpmailer to send emails via office 365 smtp. It had been working for the last year or so. Now I'm getting an error connecting to the server.

```<code>PHP Fatal error:  Uncaught PHPMailer\PHPMailer\Exception: SMTP Error: Could not connect to SMTP host. in C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php:1898
Stack trace:
#0 C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php(1725): PHPMailer\PHPMailer\PHPMailer->smtpConnect(Array)
#1 C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php(1481): PHPMailer\PHPMailer\PHPMailer->smtpSend('Date: Fri, 14 F...', 'This is a multi...')
#2 C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php(1320): PHPMailer\PHPMailer\PHPMailer->postSend()
#3 C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\submitform2.php(195): PHPMailer\PHPMailer\PHPMailer->send()
#4 {main}
thrown in C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php on line 1898
</code>```

The script is as follows:

```<code>require 'vendor/autoload.php';
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.office365.com';
$mail->Port       = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth   = true;
$mail->Username = "user@company.org";
$mail->Password = "password";
$mail->SetFrom('sentfromemail@company.org', 'FromEmail');
//$mail->addAddress('user@company.org', 'ToEmail');
$mail->addAddress('user2@company.org', 'ToEmail');
$mail->addBCC('user2@company.org', 'ToBCCEmail');
$mail->SMTPDebug  = 3;
$mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
$mail->Debugoutput = 'echo';
$mail->IsHTML(true);

$mail->Subject = 'Parish Registration Form';
$mail->Body    = $body;
$mail->AltBody = $body;

if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
else {
    echo 'Message has been sent';
}
</code>```

I've searched the internet for the connection settings associated with Office 365 and I see nothing wrong. Did something change on the Microsoft servers that I should know about but don't?

答:
There is nothing wrong on your end.

Check your firewall for port 587 blocking. If not then the issue might be from SMTP server-side. Contact Microsoft support.

Body:
I have a script that uses phpmailer to send emails via office 365 smtp. It had been working for the last year or so. Now I'm getting an error connecting to the server.

PHP Fatal error:  Uncaught PHPMailer\PHPMailer\Exception: SMTP Error: Could not connect to SMTP host. in C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php:1898
Stack trace:
#0 C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php(1725): PHPMailer\PHPMailer\PHPMailer->smtpConnect(Array)
#1 C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php(1481): PHPMailer\PHPMailer\PHPMailer->smtpSend('Date: Fri, 14 F...', 'This is a multi...')
#2 C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php(1320): PHPMailer\PHPMailer\PHPMailer->postSend()
#3 C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\submitform2.php(195): PHPMailer\PHPMailer\PHPMailer->send()
#4 {main}
thrown in C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php on line 1898

The script is as follows:

require 'vendor/autoload.php';
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.office365.com';
$mail->Port       = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth   = true;
$mail->Username = "user@company.org";
$mail->Password = "password";
$mail->SetFrom('sentfromemail@company.org', 'FromEmail');
//$mail->addAddress('user@company.org', 'ToEmail');
$mail->addAddress('user2@company.org', 'ToEmail');
$mail->addBCC('user2@company.org', 'ToBCCEmail');
$mail->SMTPDebug  = 3;
$mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
$mail->Debugoutput = 'echo';
$mail->IsHTML(true);

$mail->Subject = 'Parish Registration Form';
$mail->Body    = $body;
$mail->AltBody = $body;

if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
else {
    echo 'Message has been sent';
}

I've searched the internet for the connection settings associated with Office 365 and I see nothing wrong. Did something change on the Microsoft servers that I should know about but don't?


问:
Firefox CSS spacing issues cross-os
I'm having an issue with Firefox. It displays differently in Windows than on OSX. It looks to be a font spacing issue, or font size, but I can't figure it out. Both use the exact same properties.

Top Window: Mac OSX, Bottom: WinXP

Here's the basic HTML/Computed Style:

Any ideas from anyone?

答:
You're most likely seeing a delta because of the font chosen.  There are only a handful of fonts that are common across Windows & Mac, some of which (Lucida Sans/Lucida Sans Unicode) which contain different kerning across those platforms.

It would be very helpful to see the CSS font information for the elements in question.

The solutions (assuming it is the kerning issue mentioned above):

Choose a font that kerns better on both platforms.  Arial may work well in this case.

Pick a narrower font and ensure that it works on both platforms.

Make sure the design can accomodate extra width. I think you'll find that you have a problem in Windows if you have 10 items in your cart or go above $100.

You can use cufon for this, but I'm not a huge fan of it because of the licensing and printability issues.  You can license a font pretty cheaply from somebody like MyFonts.

Title: Firefox CSS spacing issues cross-os


问:
External SNMP manager unable to reach snmp clients on k8s
I have requirement for setting SNMP client running on Kubernetes pod from where i need to send traps to SNMP alarm manager which is not Kubernetes based. Now, there are two problems:

SNMP trap client send alarm with source IP and if i have more than one client then they are reaching on SNMP Alarm manager from same source IP i.e worker node IP.

SNMP Alarm Manager is sending trap to worker node IP on every 2 mins as per design and getting heartbeat failure as no SNMP client is running on worker node. As SNMP client is running on POD and for reaching pod in ingress we need Load balancer IP.

Now it would have been resolved if we could have set source IP as Load Balancer IP for SNMP alarm manager to get traps from same IP and send get to same Load Balancer IP.

Looking forward for your suggestions on it.

答:
If you run your pods on hostNetwork(set the field hostNetwork: true in your pod template) then your pod's and worker node IP will be same.
This will solve the problem where the reply from SNMP Alarm Manager got missed.

If you want to run multiple SNMP clients then you can run them on different worker nodes with hostNetwork and all of them will have different IP address.


问:
Popover attached to cell in UICollectionView moving when is called the ReloadData of this collection view
I have a UICollectionView that the user can clicks and it shows a popover attached to the cell clicked. In iOS 12, the popover stayed in the same origin (x,y or cell) if the reload data was called or not, but in iOS 13, the popover moves between the cells when the reload data of the collection view is called.

Follow a video of the behavior in iOS 13:
https://vimeo.com/385021234

The presentation is done using the following code:

```<code>func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    guard let cell = collectionView.cellForItem(at: indexPath) else {
        return
    }

    presentPopover(from: self, cell: cell)
}

func presentPopover(from view: UIViewController, cell: UIView) {
    let popoverView = PopoverViewController(nibName: "PopoverViewController", bundle: nil)
    let popover: UIPopoverPresentationController = popoverView.popoverPresentationController!

    popover.sourceRect = cell.bounds
    popover.sourceView = cell

    view.present(popoverView, animated: true, completion: nil)
}
</code>```

And the PopoverViewController is using the modalPresentationStyle = .popover

Anyone had this issue before in iOS 13?
Our application was working fine in iOS 11 and 12.

I have an example of this behavior in the following git repository: https://github.com/diegodossantos95/UICollectionViewPopoverBug

Steps to reproduce in the repository:

Click on a collection cell

Popover opens

Wait for the reload data

Thanks,

Diego.

答:
Instead of attaching the popover to a cell who you can guarantee won't be dequeued, you could use a temporary UIView created from the cell's frame and then attach the popover to that.  Here's the relevant code to accomplish this.

```<code>class ViewController: UIViewController {
    var timer = Timer()

    var popOverTempView = UIView()

    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(reloadData), userInfo: nil, repeats: true)
        self.collectionView.addSubview(popOverTempView)
        popOverTempView.isHidden = true
        popOverTempView.backgroundColor = .clear
    }

}

extension ViewController: UICollectionViewDelegate {

    func presentPopover(from view: UIViewController, cell: UIView) {
        let popoverView = PopoverViewController(nibName: "PopoverViewController", bundle: nil)
        let popover: UIPopoverPresentationController = popoverView.popoverPresentationController!

        popoverView.delegate = self

        popOverTempView.frame = cell.frame
        popOverTempView.isHidden = false
        popover.sourceRect = popOverTempView.bounds
        popover.sourceView = popOverTempView

        view.present(popoverView, animated: true, completion: nil)

    }

}

extension ViewController: PopoverViewControllerDelegate {
    func willDismissPopover() {
        popOverTempView.isHidden = true
    }
}

protocol PopoverViewControllerDelegate {
    func willDismissPopover()
}

class PopoverViewController: UIViewController {

    var delegate: PopoverViewControllerDelegate?

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        delegate?.willDismissPopover()
    }
}
</code>```

Update 5/20/20:

I think I found a cleaner more direct fix.  Instead of using a cell's bounds directly, convert it's contentView's frame to the collectionView's coordinate space, then use that as the sourceRect and present from the current view controller's view.

```<code>func presentPopover(from view: UIViewController, cell: UICollectionViewCell, indexPath: IndexPath) {
    let popoverView = PopoverViewController(nibName: "PopoverViewController", bundle: nil)
    let popover: UIPopoverPresentationController = popoverView.popoverPresentationController!

    var rect = cell.convert(cell.contentView.frame, to: collectionView)
    rect = collectionView.convert(rect, to: self.view)

    popover.sourceRect = rect
    popover.sourceView = self.view

    view.present(popoverView, animated: true, completion: nil)
}
</code>```

Body:
I have a UICollectionView that the user can clicks and it shows a popover attached to the cell clicked. In iOS 12, the popover stayed in the same origin (x,y or cell) if the reload data was called or not, but in iOS 13, the popover moves between the cells when the reload data of the collection view is called.

Follow a video of the behavior in iOS 13:
https://vimeo.com/385021234

The presentation is done using the following code:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    guard let cell = collectionView.cellForItem(at: indexPath) else {
        return
    }

    presentPopover(from: self, cell: cell)
}

func presentPopover(from view: UIViewController, cell: UIView) {
    let popoverView = PopoverViewController(nibName: "PopoverViewController", bundle: nil)
    let popover: UIPopoverPresentationController = popoverView.popoverPresentationController!

    popover.sourceRect = cell.bounds
    popover.sourceView = cell

    view.present(popoverView, animated: true, completion: nil)
}

And the PopoverViewController is using the modalPresentationStyle = .popover

Anyone had this issue before in iOS 13?
Our application was working fine in iOS 11 and 12.

I have an example of this behavior in the following git repository: https://github.com/diegodossantos95/UICollectionViewPopoverBug

Steps to reproduce in the repository:

Click on a collection cell

Popover opens

Wait for the reload data

Thanks,

Diego.

Body:
Instead of attaching the popover to a cell who you can guarantee won't be dequeued, you could use a temporary UIView created from the cell's frame and then attach the popover to that.  Here's the relevant code to accomplish this.

class ViewController: UIViewController {
    var timer = Timer()

    var popOverTempView = UIView()

    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(reloadData), userInfo: nil, repeats: true)
        self.collectionView.addSubview(popOverTempView)
        popOverTempView.isHidden = true
        popOverTempView.backgroundColor = .clear
    }

}

extension ViewController: UICollectionViewDelegate {

    func presentPopover(from view: UIViewController, cell: UIView) {
        let popoverView = PopoverViewController(nibName: "PopoverViewController", bundle: nil)
        let popover: UIPopoverPresentationController = popoverView.popoverPresentationController!

        popoverView.delegate = self

        popOverTempView.frame = cell.frame
        popOverTempView.isHidden = false
        popover.sourceRect = popOverTempView.bounds
        popover.sourceView = popOverTempView

        view.present(popoverView, animated: true, completion: nil)

    }

}

extension ViewController: PopoverViewControllerDelegate {
    func willDismissPopover() {
        popOverTempView.isHidden = true
    }
}

protocol PopoverViewControllerDelegate {
    func willDismissPopover()
}

class PopoverViewController: UIViewController {

    var delegate: PopoverViewControllerDelegate?

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        delegate?.willDismissPopover()
    }
}

Update 5/20/20:

I think I found a cleaner more direct fix.  Instead of using a cell's bounds directly, convert it's contentView's frame to the collectionView's coordinate space, then use that as the sourceRect and present from the current view controller's view.

func presentPopover(from view: UIViewController, cell: UICollectionViewCell, indexPath: IndexPath) {
    let popoverView = PopoverViewController(nibName: "PopoverViewController", bundle: nil)
    let popover: UIPopoverPresentationController = popoverView.popoverPresentationController!

    var rect = cell.convert(cell.contentView.frame, to: collectionView)
    rect = collectionView.convert(rect, to: self.view)

    popover.sourceRect = rect
    popover.sourceView = self.view

    view.present(popoverView, animated: true, completion: nil)
}


问:
Setting up an automated testing framework with Selenium
I am working on large websites that get updated (new features added, content changed, etc.) at least once a week. testing however, if at all present, is never as thorough as it should be. so a week ago i started looking into automated testing and selenium.

I read that if you wanna do it right, dont rely solely on selenium ide. programming your tests offers a lot more options. i wasn't comfortable with the third party PHP bindings at all so i quickly skipped to using java for programming the tests.

Now my question revolves around how to cleverly setup the system that will be running the tests. my idea was the following:

the tests will/should be totally autonomous

nevertheless i want to have some kind of main application to loop all these tests and run them one after another

the main application should be running 24/7 or at least get started periodically by a cronjob or something

tests should be run in as much browsers (or simulated clients??) as possible. so far i'm using FF, IE and chrome through their respective WebDrivers.

I wanna name some folder and collect all the tests in that folder. the main application will then just take whatever is in that folder and run it. then everybody will just create their tests and put them in that folder, so they'll get added to the queue

it would be nice to have a way to create tests with selenium ide, export them and they immediately work with my main application (i.e. they get run correctly without any modifications needed). ok, i know i said, selenium ide is disadvised but i feel it's a good start for some simple tests. also, people without any programming knowledge can still use it. as it is right now, i'm exporting the tests created with selenium ide as "Java / JUnit 4 / WebDriver" and changing a little bit of code (passing a WebDriver obect as a parameter).

Here is the code for my "main application":

```<code>import java.io.File;
import java.io.FilenameFilter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;

public class SeleniumTest {

    public static void main(String[] args) throws
    ClassNotFoundException, InstantiationException,IllegalAccessException,
    NoSuchMethodException, SecurityException, IllegalArgumentException,
    InvocationTargetException {
        String[] drivers = {
                "org.openqa.selenium.firefox.FirefoxDriver",
                "org.openqa.selenium.ie.InternetExplorerDriver",
                "org.openqa.selenium.chrome.ChromeDriver"
        };
        Class params[] = {WebDriver.class};
        String testFolderName = "lookhere";

        while (true) {
            //get all .java files from some folder. those will be the tests to run
            File testFolder = new File(testFolderName);
            FilenameFilter filter = new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.endsWith(".java");
                }
            };
            String[] tests = testFolder.list(filter);
            if (tests == null) {
                System.exit(0);
            }

            for(int i=0; i<drivers.length; i++) {
                //loop through different drivers, instantiate them
                Class webDriverClass = Class.forName(drivers[i]);
                WebDriver driver = (WebDriver) webDriverClass.newInstance();
                driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

                for (int j=0; j<tests.length; j++) {
                    //loop through tests, instantiate them
                    String currentTestName = tests[j].replace(".java", "");
                    Class testClass = Class.forName(currentTestName);
                    Object test = testClass.newInstance();

                    Method methods[] = testClass.getDeclaredMethods();
                    Method fn;

                    //run every method that starts with "test" (usually just one)
                    //also run setUp, passing the driver object
                    for(int k=0; k<methods.length; k++) {
                        if (methods[k].getName().startsWith("test")) {
                            fn = testClass.getDeclaredMethod(methods[k].getName());
                            fn.invoke(test);
                        } else if(methods[k].getName().equals("setUp")) {
                            fn = testClass.getDeclaredMethod("setUp", params);
                            fn.invoke(test, driver);
                        }
                    }
                }

                driver.quit();
            }
        }
    }
}
</code>```

As you can probably see, i am not at all an expert at java, so dont be put off by bad form (like the long throws-declaration of the main method).

Now, for my questions:

is my entire concept, that i formulated above, okay? that is: having a main application run all the tests and a queue to which i can add/remove tests on the fly. or are there other methods of best practice regarding this? what other concept/architecture can you think of?

is there a way to create tests with selenium ide, export them and they immediately work with the main application without any modification needed?

ok since i posted code, you probably wanna go crazy and criticize that ;-) i'm open for all kinds of suggestions.

is it possible with selenium to run different versions of IE (or any browser, for that matter) ? it probably just runs the browser version that i have installed. so if i wanna test different versions of one browser, i have to call remote machines which means selenium grid? i'm really just guessing right now :)

答:
Although I do not have a complete solution, I do have from experience some aspects to think about:

Try not to test the whole site, but start with the most import parts
that are (business) critical. In a typical content website with a

self service part, I would focus on the self service part. If there

are business critical parts on your home page, you could write

automated tests for that too.

People who can break the tests, should write the tests. As developers break tests all the time (by writing/changing code), developers should write the tests!

Developers should in my opinion choose their own tools. In our case the PHP developers use beehat.org for the website. The Angular developers of the self service application use Protractor.

For testing multiple browsers and versions, take a look at BrowserStack.com. Even with browserstack, you still want to think about the number of browsers to test against. Because every browser/version is an extra effort. Maybe you could test for the browsers most users visit your site with (80%?) and have the business accept the risk of not making the effort to test 100%. This of course depends heavily on your business model and risk appetite.

Hope this helps in some way.

Body:
I am working on large websites that get updated (new features added, content changed, etc.) at least once a week. testing however, if at all present, is never as thorough as it should be. so a week ago i started looking into automated testing and selenium.

I read that if you wanna do it right, dont rely solely on selenium ide. programming your tests offers a lot more options. i wasn't comfortable with the third party PHP bindings at all so i quickly skipped to using java for programming the tests.

Now my question revolves around how to cleverly setup the system that will be running the tests. my idea was the following:

the tests will/should be totally autonomous

nevertheless i want to have some kind of main application to loop all these tests and run them one after another

the main application should be running 24/7 or at least get started periodically by a cronjob or something

tests should be run in as much browsers (or simulated clients??) as possible. so far i'm using FF, IE and chrome through their respective WebDrivers.

I wanna name some folder and collect all the tests in that folder. the main application will then just take whatever is in that folder and run it. then everybody will just create their tests and put them in that folder, so they'll get added to the queue

it would be nice to have a way to create tests with selenium ide, export them and they immediately work with my main application (i.e. they get run correctly without any modifications needed). ok, i know i said, selenium ide is disadvised but i feel it's a good start for some simple tests. also, people without any programming knowledge can still use it. as it is right now, i'm exporting the tests created with selenium ide as "Java / JUnit 4 / WebDriver" and changing a little bit of code (passing a WebDriver obect as a parameter).

Here is the code for my "main application":

import java.io.File;
import java.io.FilenameFilter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;

public class SeleniumTest {

    public static void main(String[] args) throws
    ClassNotFoundException, InstantiationException,IllegalAccessException,
    NoSuchMethodException, SecurityException, IllegalArgumentException,
    InvocationTargetException {
        String[] drivers = {
                "org.openqa.selenium.firefox.FirefoxDriver",
                "org.openqa.selenium.ie.InternetExplorerDriver",
                "org.openqa.selenium.chrome.ChromeDriver"
        };
        Class params[] = {WebDriver.class};
        String testFolderName = "lookhere";

        while (true) {
            //get all .java files from some folder. those will be the tests to run
            File testFolder = new File(testFolderName);
            FilenameFilter filter = new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.endsWith(".java");
                }
            };
            String[] tests = testFolder.list(filter);
            if (tests == null) {
                System.exit(0);
            }

            for(int i=0; i<drivers.length; i++) {
                //loop through different drivers, instantiate them
                Class webDriverClass = Class.forName(drivers[i]);
                WebDriver driver = (WebDriver) webDriverClass.newInstance();
                driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

                for (int j=0; j<tests.length; j++) {
                    //loop through tests, instantiate them
                    String currentTestName = tests[j].replace(".java", "");
                    Class testClass = Class.forName(currentTestName);
                    Object test = testClass.newInstance();

                    Method methods[] = testClass.getDeclaredMethods();
                    Method fn;

                    //run every method that starts with "test" (usually just one)
                    //also run setUp, passing the driver object
                    for(int k=0; k<methods.length; k++) {
                        if (methods[k].getName().startsWith("test")) {
                            fn = testClass.getDeclaredMethod(methods[k].getName());
                            fn.invoke(test);
                        } else if(methods[k].getName().equals("setUp")) {
                            fn = testClass.getDeclaredMethod("setUp", params);
                            fn.invoke(test, driver);
                        }
                    }
                }

                driver.quit();
            }
        }
    }
}

As you can probably see, i am not at all an expert at java, so dont be put off by bad form (like the long throws-declaration of the main method).

Now, for my questions:

is my entire concept, that i formulated above, okay? that is: having a main application run all the tests and a queue to which i can add/remove tests on the fly. or are there other methods of best practice regarding this? what other concept/architecture can you think of?

is there a way to create tests with selenium ide, export them and they immediately work with the main application without any modification needed?

ok since i posted code, you probably wanna go crazy and criticize that ;-) i'm open for all kinds of suggestions.

is it possible with selenium to run different versions of IE (or any browser, for that matter) ? it probably just runs the browser version that i have installed. so if i wanna test different versions of one browser, i have to call remote machines which means selenium grid? i'm really just guessing right now :)


问:
R Visuals not loading in Power BI Services
I am having a nightmare with my R visuals in PBI Services, the visual worked fine for the last 9 months and come yesterday they are no longer rendering in PBI Service. I have checked to see if the R packages are with the PBI library and tick. below is the package list. I have updated Cran R from 3.6.1 to 3.6.2

library(dplyr)
library(ggplot2)
library(survival)
library(survminer)
library(grid)
library(gridExtra)

cannot see the wood for the trees, help kindly please. Not sure if this could be something to do with the gateway and or tenant or something else.

答:
Hi thanks for the feedback, noted for future posts. I have managed to get a resolution to the issue, the issue is with Premium Capacity and Microsoft product end.

not sure how to move forward with the question now. Assistance appreciated from the community.


问:
enabling aws-xray serverless.yml
I am trying to enable aws-xray for all lambda functions the following way:

serverless.yml

```<code>provider:
  tracing:
    lambda: true
    apiGateway: true

  name: aws
  runtime: nodejs8.10

  stage: ${opt:stage, 'dev'}
  region: ${opt:region, 'ca-central-1'}
</code>```

service.ts

import * as AWS from 'aws-sdk'
import * as AWSXRay from 'aws-xray-sdk'
const XAWS = AWSXRay.captureAWS(AWS)
const docClient: DocumentClient = new XAWS.DynamoDB.DocumentClient()
const s3 = new XAWS.S3({signatureVersion: 'v4'})
```

<p>after <code>sls deploy</code> I get the following error:</p>

```An error occurred: <some_lambda funcion> - The provided execution role does not have permissions to call PutTraceSegments on XRAY (Service: AWSLambdaInternal; Status Code: 400; Error Code: InvalidParameterValueException; Request ID: 364243f8-8847-48ef-87ad-75da2537e7f7).
```

<p>I am not sure what the problem is. I have also tried deploying with:</p>

```  iamRoleStatements:
    - Effect: Allow
      Action:
        - "xray:PutTraceSegments"
        - "xray:PutTelemetryRecords"
      Resource:
        - "*"
```

<p>still the same issue.</p>

<p>I would greatly appreciate any help as I have no idea why this is an issue especially since I have another project with tracing enabled the exact same way with no issue!</p>

<p>package.json:</p>

```{
  "name": "mini-twitter",
  "version": "1.0.0",
  "description": "Serverless Mini-Twitter app",
  "dependencies": {
    "aws-xray-sdk": "^2.2.0",
    "source-map-support": "^0.5.11",
  },
  "devDependencies": {
    "@types/aws-lambda": "^8.10.17",
    "@types/node": "^10.14.4",
    "aws-sdk": "^2.433.0",
    "serverless-iam-roles-per-function": "^1.0.4",
    "serverless-webpack": "^5.2.0",
    "ts-loader": "^5.3.3",
    "typescript": "^3.4.1",
  }
}
```

答:
If the permission

```<code>      - Effect: Allow
        Action:
          - "xray:PutTraceSegments"
          - "xray:PutTelemetryRecords"
        Resource:
          - "*"
</code>```

which you added was not globally then you should also make sure the function which you mentioned as <some_lambda funcion> in your lambda here should have the permissions too. ie if you are using a plugin like serverless-iam-roles-per-function
This worked for my case however I don't still get the exact cause of the problem since others work without it.

Title: enabling aws-xray serverless.yml

Body:
I am trying to enable aws-xray for all lambda functions the following way:

serverless.yml

provider:
  tracing:
    lambda: true
    apiGateway: true

  name: aws
  runtime: nodejs8.10

  stage: ${opt:stage, 'dev'}
  region: ${opt:region, 'ca-central-1'}

service.ts

import * as AWS from 'aws-sdk'
import * as AWSXRay from 'aws-xray-sdk'
const XAWS = AWSXRay.captureAWS(AWS)
const docClient: DocumentClient = new XAWS.DynamoDB.DocumentClient()
const s3 = new XAWS.S3({signatureVersion: 'v4'})

after sls deploy I get the following error:

An error occurred: <some_lambda funcion> - The provided execution role does not have permissions to call PutTraceSegments on XRAY (Service: AWSLambdaInternal; Status Code: 400; Error Code: InvalidParameterValueException; Request ID: 364243f8-8847-48ef-87ad-75da2537e7f7).

I am not sure what the problem is. I have also tried deploying with:

  iamRoleStatements:
    - Effect: Allow
      Action:
        - "xray:PutTraceSegments"
        - "xray:PutTelemetryRecords"
      Resource:
        - "*"

still the same issue.

I would greatly appreciate any help as I have no idea why this is an issue especially since I have another project with tracing enabled the exact same way with no issue!

package.json:

{
  "name": "mini-twitter",
  "version": "1.0.0",
  "description": "Serverless Mini-Twitter app",
  "dependencies": {
    "aws-xray-sdk": "^2.2.0",
    "source-map-support": "^0.5.11",
  },
  "devDependencies": {
    "@types/aws-lambda": "^8.10.17",
    "@types/node": "^10.14.4",
    "aws-sdk": "^2.433.0",
    "serverless-iam-roles-per-function": "^1.0.4",
    "serverless-webpack": "^5.2.0",
    "ts-loader": "^5.3.3",
    "typescript": "^3.4.1",
  }
}

Body:
If the permission

      - Effect: Allow
        Action:
          - "xray:PutTraceSegments"
          - "xray:PutTelemetryRecords"
        Resource:
          - "*"

which you added was not globally then you should also make sure the function which you mentioned as <some_lambda funcion> in your lambda here should have the permissions too. ie if you are using a plugin like serverless-iam-roles-per-function
This worked for my case however I don't still get the exact cause of the problem since others work without it.


问:
C#: Send input from inactive window
I'm trying to send input from a WPF Window which doesn't have focus. The idea is to create a virtual numpad, whereby pressing Alt+M for example sends Alt+Numpad0. I've got Michael Kennedy's global hooks working, but I can't find a way to:

1) Send keys from an inactive window

2) Swallow these keys so they're not processed by the application which has focus.

The second may become a non-issue once I get the first fixed.

System.Windows.Forms.SendKeys didn't work for this because I need to simulate the Alt+xxx combinations to generate the right characters. I also tried System.Windows.Input.InputManager.Process() from an MSDN post, but if the Window sending the input doesn't have focus, the InputSource I was using (second parameter - Keyboard.PrimaryDevice.ActiveSource) is null.

Any ideas?

Why a virtual numpad? Without a numpad on my laptop (Studio 1555) I can't enter symbols without opening charmap - thanks Dell!

答: Check out Windows Input Simulator for simulating keystrokes. Or use AutoHotkey to grab any keystroke and resend it as some other keystroke.</p>

Title: C#: Send input from inactive window


问:
How to repeat value of array in Flutter
I'm iOS Developer and new for Flutter. In the Swift language If we want to repeat the same value for a specific time in the Array.

Ex.

If In the Array I want to repeat 0 for 5 times then I can do by one line of code like below.

```<code>let fiveZeros = Array(repeating: "0", count: 5)
print(fiveZeros)
// Prints "["0", "0", "0", "0", "0"]"
</code>```

init(repeating:count:) function used.

So I'm looking for any function or code that works in Flutter.

I do googling but didn't find a solution.

答:
Starting from Dart 2.3.0 you can use conditional and loop initializers, so for your case it should be:

```<code>var fiveZeros = [for (var i = 0; i < 5; ++i) 0];
</code>```

Everything becomes much flexible and powerful when you want to initialize by expression, not just constant:

```<code>var cubes = [for (var i = 0; i < 5; ++i) i * i * i];
</code>```

is the same as [0, 1, 8, 27, 64].

Conditional elements are also essential taking into account the possibility to build a list of widgets where some of them depend on the state or platform.

More details here

Title: How to repeat value of array in Flutter

Body:
I'm iOS Developer and new for Flutter. In the Swift language If we want to repeat the same value for a specific time in the Array.

Ex.

If In the Array I want to repeat 0 for 5 times then I can do by one line of code like below.

let fiveZeros = Array(repeating: "0", count: 5)
print(fiveZeros)
// Prints "["0", "0", "0", "0", "0"]"

init(repeating:count:) function used.

So I'm looking for any function or code that works in Flutter.

I do googling but didn't find a solution.

Body:
Starting from Dart 2.3.0 you can use conditional and loop initializers, so for your case it should be:

var fiveZeros = [for (var i = 0; i < 5; ++i) 0];

Everything becomes much flexible and powerful when you want to initialize by expression, not just constant:

var cubes = [for (var i = 0; i < 5; ++i) i * i * i];

is the same as [0, 1, 8, 27, 64].

Conditional elements are also essential taking into account the possibility to build a list of widgets where some of them depend on the state or platform.

More details here


问:
Can you change the flex-direction of flexbox dynamically in CSS and JavaScript?
Given a variable, isRow, if true I want to display the the flex-direction: row but if it is false I want to the flex direction: column.

If there is a way to do this differently than what I am attempting, please let me know!

document.getElementsByClassName("flex-container")[0].style.flex-direction = "row";
//can I use: document.getElementById("flex-cointainer") instead?```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.flex-container {
  display: flex;
  flex-direction: column;
  background-color: DodgerBlue;
}

.flex-container > p {
  background-color: #f1f1f1;
  width: 100px;
  margin: 10px;
  text-align: center;
  line-height: 75px;
  font-size: 30px;
}</code>```

Hello World!

Hello World!

```

答:
you should change style.flex-direction to style.flexDirection and about your comment , yes you can use document.getElementById("flex-cointainer") but first you have to add id to your element like

and here is full working code :

var isRow = true;
var myContainer = document.getElementById("flex-container");
if(isRow) {
  myContainer.style.flexDirection = "row";
}else {
  myContainer.style.flexDirection = "column";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#flex-container {
  display: flex;
  flex-direction: column;
  background-color: DodgerBlue;
}

#flex-container > p {
  background-color: #f1f1f1;
  width: 100px;
  margin: 10px;
  text-align: center;
  line-height: 75px;
  font-size: 30px;
}</code>```

<!DOCTYPE html>

<title>Test</title>

Hello World!

Hello World!

```

Body:
Given a variable, isRow, if true I want to display the the flex-direction: row but if it is false I want to the flex direction: column.

If there is a way to do this differently than what I am attempting, please let me know!

document.getElementsByClassName("flex-container")[0].style.flex-direction = "row";
//can I use: document.getElementById("flex-cointainer") instead?

.flex-container {
  display: flex;
  flex-direction: column;
  background-color: DodgerBlue;
}

.flex-container > p {
  background-color: #f1f1f1;
  width: 100px;
  margin: 10px;
  text-align: center;
  line-height: 75px;
  font-size: 30px;
}

Hello World!

Hello World!

Body:
you should change style.flex-direction to style.flexDirection and about your comment , yes you can use document.getElementById("flex-cointainer") but first you have to add id to your element like

<div class="flex-container" id="flex-container">

and here is full working code :

var isRow = true;
var myContainer = document.getElementById("flex-container");
if(isRow) {
  myContainer.style.flexDirection = "row";
}else {
  myContainer.style.flexDirection = "column";
}

#flex-container {
  display: flex;
  flex-direction: column;
  background-color: DodgerBlue;
}

#flex-container > p {
  background-color: #f1f1f1;
  width: 100px;
  margin: 10px;
  text-align: center;
  line-height: 75px;
  font-size: 30px;
}

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<head>
<body>
<div id="flex-container">
<p id="p1">Hello World!</p>
<p id="p2">Hello World!</p>
</div>
</body>
</html>


问:
Excel VBA, 2003 - Convert string to 2-dimensional array
I inherited an old Excel (.xls) spreadsheet starting from 2005.

For some reason the spreadsheet uses the name manager for quite large data stored as strings instead of referring to a table with the data. This is what I am trying to change so it will be easier to change the data currently stored in the name manager (at the moment it is not possible to change any of the data as the character limit in the name manager has somehow been exceeded).

I would like to make use of as much of the current VBA code as possible which is why I currently have a setup where I use VBA to convert data from the spreadsheet to a string in the form of

```<code>"CELL"\"CELL"\"...""CELL";"CELL"\"CELL"\"CELL";
</code>```

Where I (or the old code) make use of backslash, \, as a delimiter for a new column and semicolon, ;, as a delimiter for a new row.

I want to convert my string to an 2-dimensional array called 'arkArray' so I can make use of the following code:

```<code>arkCellData = arkArray(i, j)
</code>```

What is the best way to do so?

答:
Here is a typical method:

```<code>Sub Fill2D()
    Dim s As String, r As Range
    Dim kolumn As Long, roww As Long
    Dim arr1, arr2, a1, a2

    kolumn = 0
    roww = 1
    s = "alpha\beta\gamma;mike\jim\john;red\blue\green"

    arr1 = Split(s, ";")

    For Each a1 In arr1
        roww = 1
        kolumn = kolumn + 1
        arr2 = Split(a1, "\")
        For Each a2 In arr2
            Cells(roww, kolumn) = a2
            roww = roww + 1
        Next a2
    Next a1

End Sub
</code>```

(you would change the starting values of kolumn and roww to pick a different starting point)

Once the 2-D array is in cells, you would verify it and then copy it into an internal VBA array.

Body:
I inherited an old Excel (.xls) spreadsheet starting from 2005.

For some reason the spreadsheet uses the name manager for quite large data stored as strings instead of referring to a table with the data. This is what I am trying to change so it will be easier to change the data currently stored in the name manager (at the moment it is not possible to change any of the data as the character limit in the name manager has somehow been exceeded).

I would like to make use of as much of the current VBA code as possible which is why I currently have a setup where I use VBA to convert data from the spreadsheet to a string in the form of

"CELL"\"CELL"\"...""CELL";"CELL"\"CELL"\"CELL";

Where I (or the old code) make use of backslash, \, as a delimiter for a new column and semicolon, ;, as a delimiter for a new row.

I want to convert my string to an 2-dimensional array called 'arkArray' so I can make use of the following code:

arkCellData = arkArray(i, j)

What is the best way to do so?

Body:
Here is a typical method:

Sub Fill2D()
    Dim s As String, r As Range
    Dim kolumn As Long, roww As Long
    Dim arr1, arr2, a1, a2

    kolumn = 0
    roww = 1
    s = "alpha\beta\gamma;mike\jim\john;red\blue\green"

    arr1 = Split(s, ";")

    For Each a1 In arr1
        roww = 1
        kolumn = kolumn + 1
        arr2 = Split(a1, "\")
        For Each a2 In arr2
            Cells(roww, kolumn) = a2
            roww = roww + 1
        Next a2
    Next a1

End Sub

(you would change the starting values of kolumn and roww to pick a different starting point)

Once the 2-D array is in cells, you would verify it and then copy it into an internal VBA array.


问:
CameraX make ImageAnalysis same size as Preview
I want to be able to get the exact image for analysis step as I get in preview.
I have preview use case:

```<code>val metrics = DisplayMetrics().also { binding.codeScannerView.display.getRealMetrics(it) }
    val screenAspectRatio = Rational(metrics.widthPixels, metrics.heightPixels)
    val previewConfig = PreviewConfig.Builder().apply {
        setTargetAspectRatio(screenAspectRatio)
    }.build()
</code>```

And next to it I have analysis use case config:

```<code>val analyzerConfig = ImageAnalysisConfig.Builder().apply {
        setTargetResolution(Size(metrics.heightPixels, metrics.widthPixels))
        setTargetAspectRatio(screenAspectRatio)
        val analyzerThread = HandlerThread(
                "QrCodeReader").apply { start() }
        setCallbackHandler(Handler(analyzerThread.looper))
        setImageReaderMode(
                ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE)
    }.build()
</code>```

My preview is fullscreen so it's size is 1440x2560. But if I try to get dimensions from ImageProxy in analyzer, I get 1920x1050 which seems to have incorrect dimensions and switched width with height. Why is that and how can I force my analysis step to have same dimensions as full screen?

答:
Intro:

```<code>implementation 'androidx.camera:camera-core:1.0.0-alpha10'
implementation 'androidx.camera:camera-camera2:1.0.0-alpha10'
implementation "androidx.camera:camera-lifecycle:1.0.0-alpha10"
implementation "androidx.camera:camera-view:1.0.0-alpha07"
implementation 'com.google.firebase:firebase-ml-vision:24.0.1'
implementation 'com.google.firebase:firebase-ml-vision-barcode-model:16.0.2'
</code>```

I am solve this issue via the method FirebaseVisionImage.fromBitmap(bitmap)
where bitmap - manual cropped && rotated image according to preview configuration.
The steps are:

when you setup ImageAnalysis.Builder() && Preview.Builder()
obtain the on-screen rendered size for
androidx.camera.view.PreviewView element:

```<code>previewView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
val previewSize = Size(previewView.width, previewView.height)
</code>```

Then pass the size into your own ImageAnalysis.Analyzer
implementation (let's say it will be viewFinderSize variable, usage see below)

when override fun analyze(mediaImage: ImageProxy){ occurs, do the manual crop of received ImageProxy. I am use the snippet from another SO question about distorted YUV_420_888 image: https://stackoverflow.com/a/45926852/2118862

When you do the cropping, keep in mind that ImageAnalysis use case receive image aligned in vertical-middle basis within your preview use case. In other words, received image, after rotation will be vertically centred as if it will be inside your preview area (even if your preview area is smaller than the image passed into analysis). So, crop area should be calculated in both directions from the vertical center: up and down.

The vertical size of the crop (height) should be manually calculated on the horizontal size basis. This means, when you receive image into analysis, it has full horizontal size within your preview area (100% of width inside preview is equal 100% of width inside analysis). So, no hidden zones in horizontal dimension. This open the way to calculate the size for vertical cropping. I am done this with next code:

```<code>var bitmap = ... <- obtain the bitmap as suggested in the SO link above
val matrix = Matrix()
matrix.postRotate(90f)
bitmap = Bitmap.createBitmap(bitmap, 0, 0, image.width, image.height, matrix, true)
val cropHeight = if (bitmap.width < viewFinderSize!!.width) {
    // if preview area larger than analysing image
    val koeff = bitmap.width.toFloat() / viewFinderSize!!.width.toFloat()
    viewFinderSize!!.height.toFloat() * koeff
} else {
    // if preview area smaller than analysing image
    val prc = 100 - (viewFinderSize!!.width.toFloat()/(bitmap.width.toFloat()/100f))
    viewFinderSize!!.height + ((viewFinderSize!!.height.toFloat()/100f) * prc)
}

val cropTop = (bitmap.height/2)-((cropHeight)/2)
bitmap = Bitmap.createBitmap(bitmap, 0, cropTop.toInt(), bitmap.width, cropHeight.toInt())
</code>```

The final value in bitmap variable - is the cropped image ready to pass into FirebaseVisionImage.fromBitmap(bitmap)

PS.
welcome to improve the suggested variant

Body:
I want to be able to get the exact image for analysis step as I get in preview.
I have preview use case:

val metrics = DisplayMetrics().also { binding.codeScannerView.display.getRealMetrics(it) }
    val screenAspectRatio = Rational(metrics.widthPixels, metrics.heightPixels)
    val previewConfig = PreviewConfig.Builder().apply {
        setTargetAspectRatio(screenAspectRatio)
    }.build()

And next to it I have analysis use case config:

val analyzerConfig = ImageAnalysisConfig.Builder().apply {
        setTargetResolution(Size(metrics.heightPixels, metrics.widthPixels))
        setTargetAspectRatio(screenAspectRatio)
        val analyzerThread = HandlerThread(
                "QrCodeReader").apply { start() }
        setCallbackHandler(Handler(analyzerThread.looper))
        setImageReaderMode(
                ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE)
    }.build()

My preview is fullscreen so it's size is 1440x2560. But if I try to get dimensions from ImageProxy in analyzer, I get 1920x1050 which seems to have incorrect dimensions and switched width with height. Why is that and how can I force my analysis step to have same dimensions as full screen?

Body:
Intro:

implementation 'androidx.camera:camera-core:1.0.0-alpha10'
implementation 'androidx.camera:camera-camera2:1.0.0-alpha10'
implementation "androidx.camera:camera-lifecycle:1.0.0-alpha10"
implementation "androidx.camera:camera-view:1.0.0-alpha07"
implementation 'com.google.firebase:firebase-ml-vision:24.0.1'
implementation 'com.google.firebase:firebase-ml-vision-barcode-model:16.0.2'

I am solve this issue via the method FirebaseVisionImage.fromBitmap(bitmap)
where bitmap - manual cropped && rotated image according to preview configuration.
The steps are:

when you setup ImageAnalysis.Builder() && Preview.Builder()
obtain the on-screen rendered size for
androidx.camera.view.PreviewView element:

previewView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
val previewSize = Size(previewView.width, previewView.height)

Then pass the size into your own ImageAnalysis.Analyzer
implementation (let's say it will be viewFinderSize variable, usage see below)

when override fun analyze(mediaImage: ImageProxy){ occurs, do the manual crop of received ImageProxy. I am use the snippet from another SO question about distorted YUV_420_888 image: https://stackoverflow.com/a/45926852/2118862

When you do the cropping, keep in mind that ImageAnalysis use case receive image aligned in vertical-middle basis within your preview use case. In other words, received image, after rotation will be vertically centred as if it will be inside your preview area (even if your preview area is smaller than the image passed into analysis). So, crop area should be calculated in both directions from the vertical center: up and down.

The vertical size of the crop (height) should be manually calculated on the horizontal size basis. This means, when you receive image into analysis, it has full horizontal size within your preview area (100% of width inside preview is equal 100% of width inside analysis). So, no hidden zones in horizontal dimension. This open the way to calculate the size for vertical cropping. I am done this with next code:

var bitmap = ... <- obtain the bitmap as suggested in the SO link above
val matrix = Matrix()
matrix.postRotate(90f)
bitmap = Bitmap.createBitmap(bitmap, 0, 0, image.width, image.height, matrix, true)
val cropHeight = if (bitmap.width < viewFinderSize!!.width) {
    // if preview area larger than analysing image
    val koeff = bitmap.width.toFloat() / viewFinderSize!!.width.toFloat()
    viewFinderSize!!.height.toFloat() * koeff
} else {
    // if preview area smaller than analysing image
    val prc = 100 - (viewFinderSize!!.width.toFloat()/(bitmap.width.toFloat()/100f))
    viewFinderSize!!.height + ((viewFinderSize!!.height.toFloat()/100f) * prc)
}

val cropTop = (bitmap.height/2)-((cropHeight)/2)
bitmap = Bitmap.createBitmap(bitmap, 0, cropTop.toInt(), bitmap.width, cropHeight.toInt())

The final value in bitmap variable - is the cropped image ready to pass into FirebaseVisionImage.fromBitmap(bitmap)

PS.
welcome to improve the suggested variant


问:
Operating on every element of a list without for loop
Now I know this question is as bizarre as it sounds, but I have found myself in a situation where I may need to avoid looping over the list, unless I manage to identify the source of the problem.

The problem:

```<code>def SomeFunction(args):
    someList = [here, are, list, elements]
    print (someList) # works normal
    for elem in someList:
        print (elem) # side effects observed here (and not sure why at this stage), only the first element is printed
</code>```

Is there any other way of accessing list elements in a manner that a for loop would do?

答:
In general, this can be achieved using recursion.

Here is the algorithm that I used to process lists using recursion :-

Function process_list(takes the first element of a list as an argument)

If the list has ended:
 return(end function execution).

Process the current element.

Call the function process_list(pass it the next element in the list).

Body:
Now I know this question is as bizarre as it sounds, but I have found myself in a situation where I may need to avoid looping over the list, unless I manage to identify the source of the problem.

The problem:

def SomeFunction(args):
    someList = [here, are, list, elements]
    print (someList) # works normal
    for elem in someList:
        print (elem) # side effects observed here (and not sure why at this stage), only the first element is printed

Is there any other way of accessing list elements in a manner that a for loop would do?


问:
Is there a technique with timescaledb to delete rows to reduce the frequency of older timescale data?
I'm storing a number of rows in a hypertable. The table size is growing quite large now even in its current test configuration.

I'd like to reduce the frequency of data from say once every 5 seconds to say once every 60 seconds for data older than a week by deleting a number of these older records.

Can anyone recommend an approach for doing so, or perhaps a better approach that better fits with timescaledb design?

答:
Take a look on Data Retention

For example:

```<code>SELECT drop_chunks(interval '24 hours', 'conditions');
</code>```

This will drop all chunks from the hypertable 'conditions' that only include data older than this duration, and will not delete any individual rows of data in chunks.

Body:
Take a look on Data Retention

For example:

SELECT drop_chunks(interval '24 hours', 'conditions');

This will drop all chunks from the hypertable 'conditions' that only include data older than this duration, and will not delete any individual rows of data in chunks.


问:
Trouble converting UTF-8 string to XML/HTML string
I have a string that is encoded in UTF-8, and I am trying to display the text on a web page. I've noticed that any attempt I've made to convert any special characters to XML-encoded characters was a failure. I know what I'm doing wrong, but I don't know how to make it right.

Edit: The original question only showed the following string as one without the b prefix, without paying any attention to the conversion with str(). Below is the updated conversion process that was not shown.

Here's the example string I'm working with, which has a horizontal ellipsis at the end:

>>> html = b'
Lorem ipsum dolor sit amet\\xe2\\x80\\xa6
'
>>> html = str(html)
```

<p>My problem is that UTF-8 characters are of variable length, so I can't just do something like this:</p>

<pre class="lang-py prettyprint-override"><code>>>> import re
>>> re.sub(r'\\(x[a-f\d]{2})', r'&#\1;', html) # Don't do this!
'<p>Lorem ipsum dolor sit ametâ€¦</p>'
</code>```

This gives three extended characters that are totally valid UTF-8, but not the right encoding. In my case, I can simply do:

>>> re.sub(r'\\xe2\\x80\\xa6', '…', html)
'
Lorem ipsum dolor sit amet…
'
```

But this only covers one of many character encodings. I obviously don't have the time, the patience, or any intention of writing substitutions for every character.

So, my question is this: how do I tell the byte-length of a character? Is there some byte mask I can use to tell if a byte is the first or last byte of a character? Any other method of determining the length, or a module that will do it for me, is welcome.

答:
The html is being received as UTF8-encoded bytes.  The bytes may be converted to a str by decoding them like this:

```<code>html = bytes_string.decode('utf-8')
</code>```

or like this

```<code>html = str(bytes_string, 'utf-8')
</code>```

Doing str(bytes_string) will not decode the bytes, it will return the repr of the bytes.

Once decoded, characters can be converted to the equivalent html entities using data from the html.entities module in the standard library, and str.translate.

```<code>from html import entities

# If we don;t want to convert html tags, don't include
# '<' and '>' in the translation table.
skip = {ord(x) for x in '<>'}
trans_table = {k: '&{};'.format(v)
               for k, v in entities.codepoint2name.items() if k not in skip}

translated = s.translate(trans_table)
print(translated)
</code>```

Output

Lorem ipsum dolor sit amet…

```

I discuss how the translation works in more depth in this answer.

Body:
I have a string that is encoded in UTF-8, and I am trying to display the text on a web page. I've noticed that any attempt I've made to convert any special characters to XML-encoded characters was a failure. I know what I'm doing wrong, but I don't know how to make it right.

Edit: The original question only showed the following string as one without the b prefix, without paying any attention to the conversion with str(). Below is the updated conversion process that was not shown.

Here's the example string I'm working with, which has a horizontal ellipsis at the end:

>>> html = b'
Lorem ipsum dolor sit amet\\xe2\\x80\\xa6
'
>>> html = str(html)

My problem is that UTF-8 characters are of variable length, so I can't just do something like this:

>>> import re
>>> re.sub(r'\\(x[a-f\d]{2})', r'&#\1;', html) # Don't do this!
'
Lorem ipsum dolor sit ametâ€¦
'

This gives three extended characters that are totally valid UTF-8, but not the right encoding. In my case, I can simply do:

>>> re.sub(r'\\xe2\\x80\\xa6', '…', html)
'
Lorem ipsum dolor sit amet…
'

But this only covers one of many character encodings. I obviously don't have the time, the patience, or any intention of writing substitutions for every character.

So, my question is this: how do I tell the byte-length of a character? Is there some byte mask I can use to tell if a byte is the first or last byte of a character? Any other method of determining the length, or a module that will do it for me, is welcome.

Body:
The html is being received as UTF8-encoded bytes.  The bytes may be converted to a str by decoding them like this:

html = bytes_string.decode('utf-8')

or like this

html = str(bytes_string, 'utf-8')

Doing str(bytes_string) will not decode the bytes, it will return the repr of the bytes.

Once decoded, characters can be converted to the equivalent html entities using data from the html.entities module in the standard library, and str.translate.

from html import entities

# If we don;t want to convert html tags, don't include
# '<' and '>' in the translation table.
skip = {ord(x) for x in '<>'}
trans_table = {k: '&{};'.format(v)
               for k, v in entities.codepoint2name.items() if k not in skip}

translated = s.translate(trans_table)
print(translated)

Output

<p>Lorem ipsum dolor sit amet&hellip;</p>

I discuss how the translation works in more depth in this answer.