问:
Fastify test unit keeps getting timed out (Node Tap)
I am testing a NodeJS app on Fastify , using Node Tap. I'm new to both platforms.
The test case unit is supposed to connect to graphql and run a sample query. I can see that the query is executed and the test assertions being passed successfully :

```<code>Executing (default): SELECT `id`, `title`, `type`, `description`, `published`,` FROM `articles` AS `Article` WHERE `Article`.`section_id` IS NOT NULL AND `Article`.`date_published` <= NOW() AND ORDER BY `Article`.`TITLE` ASC,LIMIT 5;
</code>```

However, the test case keeps taking 30 seconds and eventually getting timed out. I

```<code>FAIL  test/fastify-tests.js
 ✖ timeout!

  test: TAP
  signal: SIGTERM
  handles:
    - type: Socket
      events:
        - end
        - data
        - error
        - clientError
        - close
        - drain
  expired: TAP
</code>```

I also noticed it adds an extra assertion to the number of tests. For example , in the case where I have only one assertion , it states it is testing two :

```<code>Asserts:  1 failed, 1 passed, of 2
</code>```

My test case :

```<code>const tap = require('tap');
const fastify = require('../fastifyapp');

tap.test('POST  to `/graphql` route', t => {
t.plan(1); //plan for 1 assertion
const app = fastify.FastifyApp();
app.inject({
    method: 'POST',
    url: 'http://localhost/graphql',
    payload: {
        "operationName:": null,
        "query": '{\n' +
            'article(limit: 5) {\n' +
            'id\n' +
            '}\n' +
            '}\n',
    "variables": {
        "visibility": "PUBLIC",
        "articletype": "SPORTS",
        "OFFSET": 0,
        "articleSortBy": "ID",
        "articleSort": "ASC",
        }
    }
}, (err, response) => {
    t.error(err);  // assertion 1
});
});
</code>```

Would love it if someone could help me understand why :

it times out every time

it adds an extra assertion to the list of tests being taken in

答:
You need to close your connection to the database.

1. By Make use of fastify hooks:

I have an example with mongoose and you can search postgresql, mysql, or whatever db you're connecting to:

fastify
      .decorate('mongoose', db)
      .addHook('onClose', (fastify, done) => {
        fastify.mongoose.connection.close();
      });
```

2. By separate the database connection:

you can provide the database instance as an option. and define .close() callback function to call every time you make tests.

Body:
I am testing a NodeJS app on Fastify , using Node Tap. I'm new to both platforms.
The test case unit is supposed to connect to graphql and run a sample query. I can see that the query is executed and the test assertions being passed successfully :

Executing (default): SELECT `id`, `title`, `type`, `description`, `published`,` FROM `articles` AS `Article` WHERE `Article`.`section_id` IS NOT NULL AND `Article`.`date_published` <= NOW() AND ORDER BY `Article`.`TITLE` ASC,LIMIT 5;

However, the test case keeps taking 30 seconds and eventually getting timed out. I

FAIL  test/fastify-tests.js
 ✖ timeout!

  test: TAP
  signal: SIGTERM
  handles:
    - type: Socket
      events:
        - end
        - data
        - error
        - clientError
        - close
        - drain
  expired: TAP

I also noticed it adds an extra assertion to the number of tests. For example , in the case where I have only one assertion , it states it is testing two :

Asserts:  1 failed, 1 passed, of 2

My test case :

const tap = require('tap');
const fastify = require('../fastifyapp');

tap.test('POST  to `/graphql` route', t => {
t.plan(1); //plan for 1 assertion
const app = fastify.FastifyApp();
app.inject({
    method: 'POST',
    url: 'http://localhost/graphql',
    payload: {
        "operationName:": null,
        "query": '{\n' +
            'article(limit: 5) {\n' +
            'id\n' +
            '}\n' +
            '}\n',
    "variables": {
        "visibility": "PUBLIC",
        "articletype": "SPORTS",
        "OFFSET": 0,
        "articleSortBy": "ID",
        "articleSort": "ASC",
        }
    }
}, (err, response) => {
    t.error(err);  // assertion 1
});
});

Would love it if someone could help me understand why :

it times out every time

it adds an extra assertion to the list of tests being taken in

Body:
You need to close your connection to the database.

1. By Make use of fastify hooks:

I have an example with mongoose and you can search postgresql, mysql, or whatever db you're connecting to:

fastify
      .decorate('mongoose', db)
      .addHook('onClose', (fastify, done) => {
        fastify.mongoose.connection.close();
      });

2. By separate the database connection:

you can provide the database instance as an option. and define .close() callback function to call every time you make tests.


来源: stackexchange

问:
Finding in elements in a tuple and filtering them
Assuming I have a tuple like:

```<code>[('text-1','xxx'), ('img-1','iii'), ('img-2','jjj'), ('text-2','xxx')]
</code>```

I want to filter out the list and produce a new one with elements that begin with 'img'. So my new list will look like:

```<code>[('img-1','iii'), ('img-2','jjj')]
</code>```

Thanks!

答:
Something like this perhaps?</p>

```<code>l2 = [item for item in l1 if item[0].startswith('img')]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Assuming I have a tuple like:

[('text-1','xxx'), ('img-1','iii'), ('img-2','jjj'), ('text-2','xxx')]

I want to filter out the list and produce a new one with elements that begin with 'img'. So my new list will look like:

[('img-1','iii'), ('img-2','jjj')]

Thanks!

Body:
Something like this perhaps?

l2 = [item for item in l1 if item[0].startswith('img')]


问:
How do I select pandas row if a column in that row contains a substring present in a list
So if my pandas df has two columns, Countries and places:

```<code>  Countries     Places
0        US   New York
1        UK   Old York
2    France      Paris
3     India  New Delhi
</code>```

I have a list like so: l = ['New','Old']

How would I select rows for which the places column contain text that contain string that is also present in my list.
(The whole string may or may not be present in the list)
(It should create a data frame that only contains, US, UK, India but NOT france).
(It will

答:
Use str.contains

```<code>l = ['New', 'Old']
out = df[df['Places'].str.contains('|'.join(l))]
print(out)

# Output
  Countries     Places
0        US   New York
1        UK   Old York
3     India  New Delhi
</code>```

Note: str.contains search in whole string. If you want to limit the search to the start of string, use str.match instead.

ContentLicense: CC BY-SA 4.0

Body:
So if my pandas df has two columns, Countries and places:

  Countries     Places
0        US   New York
1        UK   Old York
2    France      Paris
3     India  New Delhi

I have a list like so: l = ['New','Old']

How would I select rows for which the places column contain text that contain string that is also present in my list.
(The whole string may or may not be present in the list)
(It should create a data frame that only contains, US, UK, India but NOT france).
(It will

Body:
Use str.contains

l = ['New', 'Old']
out = df[df['Places'].str.contains('|'.join(l))]
print(out)

# Output
  Countries     Places
0        US   New York
1        UK   Old York
3     India  New Delhi

Note: str.contains search in whole string. If you want to limit the search to the start of string, use str.match instead.


问:
Extract PSD features from a 3D array that contains EEG data
I am new to EEG signal processing and I am trying to implement a function that calculates PSD features using Python.

The input of this function is a NumPy  3D-array called "trials", with size (240, 2047, 16) that contains EEG data in this form: (trials x time x channels)

I need to extract PSD features for the whole trial, for each channel and return an array of all the results.

Fs is 512Hz

This is my code so far:

```<code>from scipy import signal

def PSD(trials):
    psd = []
    fs = 512.

    for i in range(len(trials)):
        for j in range(len(trials[i])):
            f, Pxx = signal.welch(trials[i][j], fs, nperseg = 16)
            psd.append(Pxx)

    psd = np.array(psd)

    return psd
</code>```

Is there a more efficient way to implement this?

答:
According to the documentation of scipy.signal.welch, by default the PSD is calculated over the last axis of the array.

This means you can do:

```<code>f, Pxx = scipy.signal.welch(trials, fs=512.0, nperseg=16)
</code>```

Pxx is then of shape (240, 2047, 9). In your example code, psd has shape (491280, 9). If you would like your results to take this shape, simply reshape the array:

```<code>Pxx = Pxx.reshape(491280, 9)
</code>```

Also, in your example code you append the sample frequencies to psd rather than the PSD, so your current code doesn't return the PSD.

Body:
I am new to EEG signal processing and I am trying to implement a function that calculates PSD features using Python.

The input of this function is a NumPy  3D-array called "trials", with size (240, 2047, 16) that contains EEG data in this form: (trials x time x channels)

I need to extract PSD features for the whole trial, for each channel and return an array of all the results.

Fs is 512Hz

This is my code so far:

from scipy import signal

def PSD(trials):
    psd = []
    fs = 512.

    for i in range(len(trials)):
        for j in range(len(trials[i])):
            f, Pxx = signal.welch(trials[i][j], fs, nperseg = 16)
            psd.append(Pxx)

    psd = np.array(psd)

    return psd

Is there a more efficient way to implement this?

Body:
According to the documentation of scipy.signal.welch, by default the PSD is calculated over the last axis of the array.

This means you can do:

f, Pxx = scipy.signal.welch(trials, fs=512.0, nperseg=16)

Pxx is then of shape (240, 2047, 9). In your example code, psd has shape (491280, 9). If you would like your results to take this shape, simply reshape the array:

Pxx = Pxx.reshape(491280, 9)

Also, in your example code you append the sample frequencies to psd rather than the PSD, so your current code doesn't return the PSD.


问:
Getting a segmentation fault in C with unsigned long long int?
Im trying to code a decimal to binary converter in C. I have to use unsigned long long int because the largest number I have to be able to calculate is 18,446,744,073,709,551,615. On the Linux server my professor has us use, it says there is a segmentation fault, and on CLion debugger it says "Exception = EXC_BAD_ACCESS (code=2, address=0x7ff7bc694ff8)" and claims i = {unsigned long long} 18446744073708503289, which isn't right. It does this no matter what number userInput is.

What I currently have:

```<code>#include <stdio.h>

int main(void)
{
  unsigned long long int userInput;
  unsigned long long int i;
  unsigned long long int binary[] = {};

  printf("Enter a number from 0 to 18,446,744,073,709,551,615: ");
  scanf("%lld", &userInput);

  printf("\nThe binary value of %lld is: ", userInput);

  if (userInput == 0)
  {
      printf("0");
  }
  else
  {
    for (i = 0; userInput > 0; i++)
    {
        binary[i] = userInput%2;
        userInput = userInput/2;
    }
    for (i -= 1; i >= 0; i--)
    {
        printf("%lld", binary[i]);
    }
  }

  printf("\n");

  return 0;
}
</code>```

答:
Because binary was not given an explicit size and was given an empty initializer list, the array has size 0.  Any attempt to use such an array will trigger undefined behavior which in this particular case causes a crash.

You need to store up to 64 binary digits, so make the array that size.

```<code>unsigned long long int binary[64];
</code>```

Another problem is in this conditional:

```<code>for (i -= 1; i >= 0; i--)
</code>```

Because i has an unsigned type, the condition i >= 0 will always be true.  So change the type of i to int.

```<code>int i;
</code>```

Body:
Im trying to code a decimal to binary converter in C. I have to use unsigned long long int because the largest number I have to be able to calculate is 18,446,744,073,709,551,615. On the Linux server my professor has us use, it says there is a segmentation fault, and on CLion debugger it says "Exception = EXC_BAD_ACCESS (code=2, address=0x7ff7bc694ff8)" and claims i = {unsigned long long} 18446744073708503289, which isn't right. It does this no matter what number userInput is.

What I currently have:

#include <stdio.h>

int main(void)
{
  unsigned long long int userInput;
  unsigned long long int i;
  unsigned long long int binary[] = {};

  printf("Enter a number from 0 to 18,446,744,073,709,551,615: ");
  scanf("%lld", &userInput);

  printf("\nThe binary value of %lld is: ", userInput);

  if (userInput == 0)
  {
      printf("0");
  }
  else
  {
    for (i = 0; userInput > 0; i++)
    {
        binary[i] = userInput%2;
        userInput = userInput/2;
    }
    for (i -= 1; i >= 0; i--)
    {
        printf("%lld", binary[i]);
    }
  }

  printf("\n");

  return 0;
}

Body:
Because binary was not given an explicit size and was given an empty initializer list, the array has size 0.  Any attempt to use such an array will trigger undefined behavior which in this particular case causes a crash.

You need to store up to 64 binary digits, so make the array that size.

unsigned long long int binary[64];

Another problem is in this conditional:

for (i -= 1; i >= 0; i--)

Because i has an unsigned type, the condition i >= 0 will always be true.  So change the type of i to int.

int i;


问:
How to have cursor change with buttonclick
I have set up a switcher on my website to toggle between normal mouse / pointer & a Lego hand as a cursor and a head as pointer. However, I can only get the cursor to show when clicking the switcher. How can I also add this pointer

(cursor: url(https://cdn.shopify.com/s/files/1/0571/7137/8349/files/pointer.png?v=1644096049), pointer;)

It should be assigned to the following classes:

a, button, input, input, button, a, input, .slider, .round

I have then also added a snippet, which lets the switcher / checkbox stay on checked...
(You can see that on this video [password is 12345678]: https://easyupload.io/gknxoi)

However after a reload of the page for example, the switcher stays on checked, but the cursor doesn't show up...

var cbs = document.querySelectorAll('input[type=checkbox]');
for (var i = 0; i < cbs.length; i++) {
  cbs[i].addEventListener('change', function() {
    if (this.checked) {
      document.body.style.cursor = "url(https://cdn.shopify.com/s/files/1/0571/7137/8349/files/cursor.png?v=1644096068), auto";
    } else {
      document.body.style.cursor = "default";
    }
  });
}

$(function() {
  var test = localStorage.input === 'true' ? true : false;
  $('input').prop('checked', test || false);
});

$('input').on('change', function() {
  localStorage.input = $(this).is(':checked');
  console.log($(this).is(':checked'));
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.switcheronheader {
  position: relative;
  display: inline-block;
  width: 30px;
  height: 17px;
  margin-bottom: 2px;
}

.mouseswitcher {
  /*   border-left: 1px solid #248751; */
  padding-left: 20px;
}

.switcheronheader input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 13px;
  width: 13px;
  left: 2px;
  bottom: 2px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked+.slider {
  background-color: #248751;
}

input:focus+.slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked+.slider:before {
  -webkit-transform: translateX(13px);
  -ms-transform: translateX(13px);
  transform: translateX(13px);
}

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}</code>```

                     <input type="checkbox" id="overheaderswitch">

```

答:
Is this what you are looking for?

a, input, button, .slider, .round {
  margin: 15px;
  cursor:url(https://cdn.shopify.com/s/files/1/0571/7137/8349/files/pointer.png?v=1644096049), auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" value="lego"/>
link to google.com</code>```

Body:
I have set up a switcher on my website to toggle between normal mouse / pointer & a Lego hand as a cursor and a head as pointer. However, I can only get the cursor to show when clicking the switcher. How can I also add this pointer

(cursor: url(https://cdn.shopify.com/s/files/1/0571/7137/8349/files/pointer.png?v=1644096049), pointer;)

It should be assigned to the following classes:

a, button, input, input, button, a, input, .slider, .round

I have then also added a snippet, which lets the switcher / checkbox stay on checked...
(You can see that on this video [password is 12345678]: https://easyupload.io/gknxoi)

However after a reload of the page for example, the switcher stays on checked, but the cursor doesn't show up...

var cbs = document.querySelectorAll('input[type=checkbox]');
for (var i = 0; i < cbs.length; i++) {
  cbs[i].addEventListener('change', function() {
    if (this.checked) {
      document.body.style.cursor = "url(https://cdn.shopify.com/s/files/1/0571/7137/8349/files/cursor.png?v=1644096068), auto";
    } else {
      document.body.style.cursor = "default";
    }
  });
}

$(function() {
  var test = localStorage.input === 'true' ? true : false;
  $('input').prop('checked', test || false);
});

$('input').on('change', function() {
  localStorage.input = $(this).is(':checked');
  console.log($(this).is(':checked'));
});

.switcheronheader {
  position: relative;
  display: inline-block;
  width: 30px;
  height: 17px;
  margin-bottom: 2px;
}

.mouseswitcher {
  /*   border-left: 1px solid #248751; */
  padding-left: 20px;
}

.switcheronheader input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 13px;
  width: 13px;
  left: 2px;
  bottom: 2px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked+.slider {
  background-color: #248751;
}

input:focus+.slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked+.slider:before {
  -webkit-transform: translateX(13px);
  -ms-transform: translateX(13px);
  transform: translateX(13px);
}

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}

                     <input type="checkbox" id="overheaderswitch">

Body:
Is this what you are looking for?

a, input, button, .slider, .round {
  margin: 15px;
  cursor:url(https://cdn.shopify.com/s/files/1/0571/7137/8349/files/pointer.png?v=1644096049), auto;
}

<input type="button" value="lego"/>
<a href="http://google.com" target="_blank">link to google.com</a>


问:
What is the proper way to send a broadcast from an activity to a service?
I have an activity with a button than sends a broadcast to an accessibility service (they're in the same app but different processes). I'm sorry if this was already answered many times but I can't find the proper method to do it. To be clear what I wrote works but I don't know if it's the proper way. I wrote this in the activity:

```<code>Intent intent = new Intent("roastie_toastie");
sendBroadcast(intent);
</code>```

And in the accessibility service wrote this:

```<code>IntentFilter intentFilter = new IntentFilter("roastie_toastie");
receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

    }
};
registerReceiver(receiver, intentFilter);
</code>```

Does anything else need to be added to the intent and intentFilter to be sure that this broadcast does not consume any battery and is only sent and received inside the app?

答:
is there any way to also specify the sender's packageName for the receiver's IntentFilter so that it only listens to broadcasts from inside the app?

No, sorry. However, if this is all one app, then you do not need to use registerReceiver().

Presumably, right now, in your manifest, you have a <service> element that has android:process to have the service run in a separate process from the rest of the app. You can have a <receiver> element that has the same android:process attribute, to have it run in the same process as the service. If you have the <receiver> also be android:exported="false", then only your app can send broadcasts to it. Your sending code would use an explicit Intent, identifying the specific BroadcastReceiver class.

Once you have your broadcast over to the service's process via that BroadcastReceiver, it and the service can communicate via some common process-wide singleton.

Body:
I have an activity with a button than sends a broadcast to an accessibility service (they're in the same app but different processes). I'm sorry if this was already answered many times but I can't find the proper method to do it. To be clear what I wrote works but I don't know if it's the proper way. I wrote this in the activity:

Intent intent = new Intent("roastie_toastie");
sendBroadcast(intent);

And in the accessibility service wrote this:

IntentFilter intentFilter = new IntentFilter("roastie_toastie");
receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

    }
};
registerReceiver(receiver, intentFilter);

Does anything else need to be added to the intent and intentFilter to be sure that this broadcast does not consume any battery and is only sent and received inside the app?


问:
Get enum value by name stored in a string in PHP
I want to get the value of an Enum in PHP by its name.
My enum is like:

```<code>enum Status : int
{
    case ACTIVE = 1;
    case REVIEWED = 2;
    // ...
}
</code>```

Status::from(2) can be used to get "REVIEWED", but how can I resolve the value from the name stored in a string ?

答:
To get value from the name:

```<code>enum Status : int
{
   case ACTIVE = 1;
   case REVIEWED = 2;
   // ...
}

print(Status::REVIEWED->value);
</code>```

Enum documentation

Body:
I want to get the value of an Enum in PHP by its name.
My enum is like:

enum Status : int
{
    case ACTIVE = 1;
    case REVIEWED = 2;
    // ...
}

Status::from(2) can be used to get "REVIEWED", but how can I resolve the value from the name stored in a string ?

Body:
To get value from the name:

enum Status : int
{
   case ACTIVE = 1;
   case REVIEWED = 2;
   // ...
}

print(Status::REVIEWED->value);

Enum documentation


问:
How to stretch this button in flutter?
I am learning flutter, and faced this issue:

I want the equal button to stretch to the left and cover the whole green area as shown in the picture.

The equal button is in one column and the other four buttons are in another column. And in turn, both of these columns are in a row. i.e

```<code>Column:
  Row:
    Column 1:
      Equal-Button // If I warp it in expended, it goes out of sight.
    Column 2:
      the other four buttons
</code>```

What is the proper way to fix it, not just hacks. How would you do it?

Here is the whole code:
Github Gist

答: You'll need to have it in its own column then use crossAxisAlignment.stretch. Just ensure it occupies a finite space

Title: How to stretch this button in flutter?

Body:
I am learning flutter, and faced this issue:

I want the equal button to stretch to the left and cover the whole green area as shown in the picture.

The equal button is in one column and the other four buttons are in another column. And in turn, both of these columns are in a row. i.e

Column:
  Row:
    Column 1:
      Equal-Button // If I warp it in expended, it goes out of sight.
    Column 2:
      the other four buttons

What is the proper way to fix it, not just hacks. How would you do it?

Here is the whole code:
Github Gist


答:
You can wrap the Elevated Button with Sized Box and give it a width of your choice,
than if you want to put the '=' string to the right instead of center you can just wrap the text with align and set alignemnt to your choice</p>
```<code> SizedBox(
              width: 300,
              child: ElevatedButton(
                style: ButtonStyle(
                  backgroundColor:
                      MaterialStateProperty.all(Colors.grey.shade600),
                ),
                child: Align(
                  alignment: Alignment.centerRight,
                  child: Text(
                    "=",
                    style: TextStyle(fontSize: 26),
                  ),
                ),
                onPressed: () {},
              ),
            )

</code>```

Title: How to stretch this button in flutter?

Body:
You can wrap the Elevated Button with Sized Box and give it a width of your choice,
than if you want to put the '=' string to the right instead of center you can just wrap the text with align and set alignemnt to your choice

 SizedBox(
              width: 300,
              child: ElevatedButton(
                style: ButtonStyle(
                  backgroundColor:
                      MaterialStateProperty.all(Colors.grey.shade600),
                ),
                child: Align(
                  alignment: Alignment.centerRight,
                  child: Text(
                    "=",
                    style: TextStyle(fontSize: 26),
                  ),
                ),
                onPressed: () {},
              ),
            )


问:
Express route with dynamic params not working

router.get('/:id ', (req, res) => {
    res.send(req.params.id);
});```

When I call this on exmaple "http://localhost/12" I will get an error called "Cannot Get /12"

Any ideas what I am missing out?

答:
You need to register your router to main app in your index.js

In your router.js folder

```<code>const express = require('express');
const router = express.Router()
router.get('/:id ', (req, res) => {
    res.send(req.params.id);
});
</code>```

and in your index.js

```<code>const express = require('express');
app = express()
app.use(router)
</code>```

Body:
router.get('/:id ', (req, res) => {
    res.send(req.params.id);
});

When I call this on exmaple "http://localhost/12" I will get an error called "Cannot Get /12"

Any ideas what I am missing out?

Body:
You need to register your router to main app in your index.js

In your router.js folder

const express = require('express');
const router = express.Router()
router.get('/:id ', (req, res) => {
    res.send(req.params.id);
});

and in your index.js

const express = require('express');
app = express()
app.use(router)


问:
Unable to connect ASP.NET app to SQL Server on Docker
I have created and am running SQL Server on Docker (on Mac). I am able to connect to it on Azure. I was able to run dotnet ef database update and the database appears in azure.

However, when I run my asp.net project and try to run a simple GET request to the database I get a pre-login handshake error. The GET request shouldn't be the problem as I am following a tutorial and it's basically the same.

I have specified the connection chain in appsettings.json:

```<code>"ConnectionStrings": {
    "CodeCamp": "Data Source=localhost, 1433;Initial Catalog=PSCodeCamp;User ID=sa;Password=Password-Is-L0ng"
  }
</code>```

I used the same credentials to connect in Azure.

TL:DR: Handshake error in Rider/Postman, Working fine in Azure.

I also noticed that if I try to connect in azure while the app is running I get the same handshake error in Azure and I also tried to disconnect azure before running the app, still getting the same error.

The error in question:

```<code>The timeout period elapsed while attempting to consume the pre-login handshake acknowledgement.  This could be because the pre-login handshake failed or the server was unable to respond back in time.  The duration spent while attempting to connect to this server was - [Pre-Login] initialization=40; handshake=14974;
</code>```

答: Depending on the image, the Password part of your connection string should be replaced with SA_PASSWORD. There's some information on the dockerhub but not too informative.

Body:
I have created and am running SQL Server on Docker (on Mac). I am able to connect to it on Azure. I was able to run dotnet ef database update and the database appears in azure.

However, when I run my asp.net project and try to run a simple GET request to the database I get a pre-login handshake error. The GET request shouldn't be the problem as I am following a tutorial and it's basically the same.

I have specified the connection chain in appsettings.json:

"ConnectionStrings": {
    "CodeCamp": "Data Source=localhost, 1433;Initial Catalog=PSCodeCamp;User ID=sa;Password=Password-Is-L0ng"
  }

I used the same credentials to connect in Azure.

TL:DR: Handshake error in Rider/Postman, Working fine in Azure.

I also noticed that if I try to connect in azure while the app is running I get the same handshake error in Azure and I also tried to disconnect azure before running the app, still getting the same error.

The error in question:

The timeout period elapsed while attempting to consume the pre-login handshake acknowledgement.  This could be because the pre-login handshake failed or the server was unable to respond back in time.  The duration spent while attempting to connect to this server was - [Pre-Login] initialization=40; handshake=14974;


问:
Swift: Why DateComponentsFormatter.localizedString(from:unitsStyle:) does not work for weekday?
Why DateComponentsFormatter.localizedString(from:unitsStyle:) does not work for weekday?

```<code>let twoDays = DateComponents(day: 2)
let threeWeeks = DateComponents(weekday: 3)

DateComponentsFormatter.localizedString(from: twoDays, unitsStyle: .full) ?? "found nil" // "2 days"
DateComponentsFormatter.localizedString(from: threeWeeks, unitsStyle: .full) ?? "found nil" // returns "found nil"
</code>```

答:
The DateComponents has a property named allowedUnits, weekday is not a legal unit.

The allowed units are:

year
month
weekOfMonth
day
hour
minute
second

see this ref.

Body:
Why DateComponentsFormatter.localizedString(from:unitsStyle:) does not work for weekday?

let twoDays = DateComponents(day: 2)
let threeWeeks = DateComponents(weekday: 3)

DateComponentsFormatter.localizedString(from: twoDays, unitsStyle: .full) ?? "found nil" // "2 days"
DateComponentsFormatter.localizedString(from: threeWeeks, unitsStyle: .full) ?? "found nil" // returns "found nil"


问:
Redux Toolkit - do not send request when query param is invalid
I've checked the redux toolkit docs and don't see an example of this typical use case: do not send the request of the query has an invalid param.

For example, a get request to endpoint /categories/{name} requires a name value. If name does not have a value, then the request should not be made.

```<code>const baseQuery = fetchBaseQuery({
  baseUrl: Constants.PATHWAY_API_URL
});

export const pathwayApi = createApi({
  reducerPath: 'pathwayApi',
  baseQuery: baseQueryWithReAuth,
  endpoints: builder => ({
    getSubCategories: builder.query({
      // NETWORK REQUEST SHOULD NOT BE MADE IF "name" param is falsy
      query: name => `${Constants.PATHWAY_API.CATEGORIES_PATH_NAME}/${name}`,
    }),
  }),
});

</code>```

I want to add this type of param validation to all my queries that require a param value or values. What's the recommended approach / pattern for handling this validation at the createApi (or possibly fetchBaseQuery) layer?
Thanks in advance!

答:
You can actually throw an error in your query function.

```<code>export const pathwayApi = createApi({
  reducerPath: "pathwayApi",
  baseQuery: baseQueryWithReAuth,
  endpoints: (builder) => ({
    getSubCategories: builder.query({
      // NETWORK REQUEST SHOULD NOT BE MADE IF "name" param is falsy
      query: (name) => {
        if (!name) {
          throw new Error("Category name is required.");
        }
        return `${Constants.PATHWAY_API.CATEGORIES_PATH_NAME}/${name}`;
      }
    })
  })
});
</code>```

When this happens, your hook will have isError: true  but no network request will be made.  The error property of your hook will be a SerializedError object with properties name, message and stack, which you can use to display the error in your UI.

This is the same type of error object that you get if you have a TypeError somewhere in your code.  Note that JavaScript errors will have error.message while API errors (FetchBaseQueryError) will have error.error.

```<code>const Category = ({ name }) => {
  const { data, error, isError } = useGetSubCategoriesQuery(name);

  return (
    <div>
      <h3>Name: "{name}"</h3>
      {isError && (
          <div>{error?.error ?? error?.message}</div>
      )}
    </div>
  );
};
</code>```

CodeSandbox Link

Body:
I've checked the redux toolkit docs and don't see an example of this typical use case: do not send the request of the query has an invalid param.

For example, a get request to endpoint /categories/{name} requires a name value. If name does not have a value, then the request should not be made.

const baseQuery = fetchBaseQuery({
  baseUrl: Constants.PATHWAY_API_URL
});

export const pathwayApi = createApi({
  reducerPath: 'pathwayApi',
  baseQuery: baseQueryWithReAuth,
  endpoints: builder => ({
    getSubCategories: builder.query({
      // NETWORK REQUEST SHOULD NOT BE MADE IF "name" param is falsy
      query: name => `${Constants.PATHWAY_API.CATEGORIES_PATH_NAME}/${name}`,
    }),
  }),
});

I want to add this type of param validation to all my queries that require a param value or values. What's the recommended approach / pattern for handling this validation at the createApi (or possibly fetchBaseQuery) layer?
Thanks in advance!

Body:
You can actually throw an error in your query function.

export const pathwayApi = createApi({
  reducerPath: "pathwayApi",
  baseQuery: baseQueryWithReAuth,
  endpoints: (builder) => ({
    getSubCategories: builder.query({
      // NETWORK REQUEST SHOULD NOT BE MADE IF "name" param is falsy
      query: (name) => {
        if (!name) {
          throw new Error("Category name is required.");
        }
        return `${Constants.PATHWAY_API.CATEGORIES_PATH_NAME}/${name}`;
      }
    })
  })
});

When this happens, your hook will have isError: true  but no network request will be made.  The error property of your hook will be a SerializedError object with properties name, message and stack, which you can use to display the error in your UI.

This is the same type of error object that you get if you have a TypeError somewhere in your code.  Note that JavaScript errors will have error.message while API errors (FetchBaseQueryError) will have error.error.

const Category = ({ name }) => {
  const { data, error, isError } = useGetSubCategoriesQuery(name);

  return (
    <div>
      <h3>Name: "{name}"</h3>
      {isError && (
          <div>{error?.error ?? error?.message}</div>
      )}
    </div>
  );
};

CodeSandbox Link


问:
What's the benefit of WEBVTT(.vtt) over SubReal (.srt)?
I finally came to a conclusion that google-chrome does not support .srt because WEBVTT is HTML5 standard.

Now I am wondering what's the reasoning behind this decision.

It seems that google-chrome might have supported .srt too because:

.srt was widely used

.srt and .vtt has almost no difference

Is there anything better in WEBVTT that makes .srt obsolete?

答:
Short answer

WebVTT was built as an extension of SRT to add useful features that are not available in SRT. In its most basic form, WebVTT looks near identical to SRT. However, WebVTT adds many (optional) ways to format the output and provide auxiliary information that SRT does not have. The downside of extra features is that it's more difficult for a player to support it. Because SRT has very few features, most players support it.

Long answer

WebVTT (Web Video Text Tracks) was originally called WebSRT. It was made to be an extension of SRT (SubRip). When not using any of the additional features that WebVTT provides, WebVTT looks near identical to SRT. For example, a simple case in SRT might look like:

```<code>1
00:00:00.000 --> 00:00:02.000
The first cue text.

2
00:00:02.000 --> 00:00:04.000
The second cue text.
</code>```

where the equivalent WebVTT might look like:

```<code>WEBVTT

00:00.000 --> 00:02.000
The first cue text.

00:02.000 --> 00:04.000
The second cue text.
</code>```

The reason WebVTT was made was to add many features that don't exist in SRT. For example, in WebVTT you can add data showing who the speaker of a cue is:

```<code>00:02.000 --> 00:04.000
<v Mary>Hi, I'm Mary!
</code>```

SRT doesn't officially include any font styling. Simple font styling is unofficially supported within SRT by many players, but since it's not officially part of the format, there are no guarantees. WebVTT does include font styling as part of the format. For simple font styling, the unofficial SRT and WebVTT again look similar:

```<code><b>This text is bold.</b>
</code>```

However, WebVTT includes many types of font styling and many methods of including the font styling that are not included by SRT. For example, WebVTT has style sheets similar to CSS for HTML. For the above labeled speaker example, you can include font styling for all instances of a specific speaker in the file:

```<code>::cue(v[voice="Mary"]) { color: lime }
</code>```

This can be useful when multiple speakers are talking over each other so that their speech can be differentiated in the subtitles.

Just as a quick sampling of some other stuff WebVTT supports that SRT does not,

Positioning and sizing the cues within the viewport:

```<code>00:00:00.000 --> 00:00:04.000 position:10%,line-left align:left size:35%
I'm over here.
</code>```

Ruby text for small characters above the normal ones (often used in East Asian languages to provide phonetic guides):

```<code>00:02.000 --> 00:04.000
<ruby>東京<rt>とうきょう</rt></ruby>
</code>```

Cues subdivided in time:

```<code>00:00:00.000 --> 00:00:06.000
This <00:00:01.000>text <00:00:02.000>appears <00:00:03.000>over <00:00:04.000>5 <00:00:05.000>seconds.
</code>```

The advantage of SRT is that it's so simple that more players support it. Luckily, it's fairly easy to translate SRT to WebVTT and vice versa. Since WebVTT is basically a superset of SRT, you just need to change some minor syntax to convert from SRT to WebVTT. To go from WebVTT to SRT, you strip out all extra features tags, then perform the slight syntax change. Of course, in this direction, you lose all the extra features WebVTT provided.

Where SRT was developed by a relatively obscure group, WebVTT is a W3C standard. As noted by the original question, it is more or less the "official" caption/subtitle format for HTML5.

Body:
Short answer

WebVTT was built as an extension of SRT to add useful features that are not available in SRT. In its most basic form, WebVTT looks near identical to SRT. However, WebVTT adds many (optional) ways to format the output and provide auxiliary information that SRT does not have. The downside of extra features is that it's more difficult for a player to support it. Because SRT has very few features, most players support it.

Long answer

WebVTT (Web Video Text Tracks) was originally called WebSRT. It was made to be an extension of SRT (SubRip). When not using any of the additional features that WebVTT provides, WebVTT looks near identical to SRT. For example, a simple case in SRT might look like:

1
00:00:00.000 --> 00:00:02.000
The first cue text.

2
00:00:02.000 --> 00:00:04.000
The second cue text.

where the equivalent WebVTT might look like:

WEBVTT

00:00.000 --> 00:02.000
The first cue text.

00:02.000 --> 00:04.000
The second cue text.

The reason WebVTT was made was to add many features that don't exist in SRT. For example, in WebVTT you can add data showing who the speaker of a cue is:

00:02.000 --> 00:04.000
<v Mary>Hi, I'm Mary!

SRT doesn't officially include any font styling. Simple font styling is unofficially supported within SRT by many players, but since it's not officially part of the format, there are no guarantees. WebVTT does include font styling as part of the format. For simple font styling, the unofficial SRT and WebVTT again look similar:

<b>This text is bold.</b>

However, WebVTT includes many types of font styling and many methods of including the font styling that are not included by SRT. For example, WebVTT has style sheets similar to CSS for HTML. For the above labeled speaker example, you can include font styling for all instances of a specific speaker in the file:

::cue(v[voice="Mary"]) { color: lime }

This can be useful when multiple speakers are talking over each other so that their speech can be differentiated in the subtitles.

Just as a quick sampling of some other stuff WebVTT supports that SRT does not,

Positioning and sizing the cues within the viewport:

00:00:00.000 --> 00:00:04.000 position:10%,line-left align:left size:35%
I'm over here.

Ruby text for small characters above the normal ones (often used in East Asian languages to provide phonetic guides):

00:02.000 --> 00:04.000
<ruby>東京<rt>とうきょう</rt></ruby>

Cues subdivided in time:

00:00:00.000 --> 00:00:06.000
This <00:00:01.000>text <00:00:02.000>appears <00:00:03.000>over <00:00:04.000>5 <00:00:05.000>seconds.

The advantage of SRT is that it's so simple that more players support it. Luckily, it's fairly easy to translate SRT to WebVTT and vice versa. Since WebVTT is basically a superset of SRT, you just need to change some minor syntax to convert from SRT to WebVTT. To go from WebVTT to SRT, you strip out all extra features tags, then perform the slight syntax change. Of course, in this direction, you lose all the extra features WebVTT provided.

Where SRT was developed by a relatively obscure group, WebVTT is a W3C standard. As noted by the original question, it is more or less the "official" caption/subtitle format for HTML5.


问:
How do I load url into Image into DrawImage in Compose UI Android Jetpack?
I can use
val image = +imageResource(R.drawable.header)
and use DrawImage(image) to load image from Drawable Resource,

But how do I load a string url into the DrawImage(image)?. I've tried using Glide, but it needs to load into imageView. meanwhile DrawImage(image) doesn't take input from imageView.

Thanks.

答:
I have found a very easy way to show an image from an URL.

Add
dependencies{ implementation("io.coil-kt:coil:1.4.0") }

Just do this

imageView.load("https://www.example.com/image.jpg")

Also for a resource o file you can do this:

```<code>imageView.load(R.drawable.image)

imageView.load(File("/path/to/image.jpg"))
</code>```

Requests can be configured with an optional trailing lambda:

```<code>imageView.load("https://www.example.com/image.jpg") {
    crossfade(true)
    placeholder(R.drawable.image)
    transformations(CircleCropTransformation())
}
</code>```

I found this info from official coil page here: enter link description here

Body:
I have found a very easy way to show an image from an URL.

Add
dependencies{ implementation("io.coil-kt:coil:1.4.0") }

Just do this

imageView.load("https://www.example.com/image.jpg")

Also for a resource o file you can do this:

imageView.load(R.drawable.image)

imageView.load(File("/path/to/image.jpg"))

Requests can be configured with an optional trailing lambda:

imageView.load("https://www.example.com/image.jpg") {
    crossfade(true)
    placeholder(R.drawable.image)
    transformations(CircleCropTransformation())
}

I found this info from official coil page here: enter link description here


答:
One way:

```<code>>>> l = [('text-1','xxx'), ('img-1','iii'), ('img-2','jjj'), ('text-2','xxx')]
>>> [t for t in l if t[0].startswith('img')]
[('img-1', 'iii'), ('img-2', 'jjj')]
</code>```

Another way:

```<code>>>> filter(lambda x: x[0].startswith('img'), l)
[('img-1', 'iii'), ('img-2', 'jjj')]
</code>```

The first is called a list comprehension. See F.C.'s answer for a related technique. The basic syntax is [{expression} for {item_var_or_vars} in {iterable} if {boolean_expression}]. It's semantically equivalent to something like this:

```<code>new_list = []
for {item_var_or_vars} in {iterable}:
    if {boolean_expression}:
        new_list.append({expression})
</code>```

The if {boolean_expression} bit is optional, just as it is in the for loop.

The second is simply the built-in function filter, which accepts a test function and an iterable, and returns a list containing every element that "passes" the test function. lambda, if you haven't seen it before, is just a quick way of defining a function. You could do this instead:

```<code>def keep_this_element(element):
    return element[0].startswith('img')   # returns True for ('img...', '...')

new_list = filter(keep_this_element, l)   # keeps only elements that return True
</code>```

Title: Finding in elements in a tuple and filtering them

Body:
Assuming I have a tuple like:

[('text-1','xxx'), ('img-1','iii'), ('img-2','jjj'), ('text-2','xxx')]

I want to filter out the list and produce a new one with elements that begin with 'img'. So my new list will look like:

[('img-1','iii'), ('img-2','jjj')]

Thanks!

Body:
One way:

>>> l = [('text-1','xxx'), ('img-1','iii'), ('img-2','jjj'), ('text-2','xxx')]
>>> [t for t in l if t[0].startswith('img')]
[('img-1', 'iii'), ('img-2', 'jjj')]

Another way:

>>> filter(lambda x: x[0].startswith('img'), l)
[('img-1', 'iii'), ('img-2', 'jjj')]

The first is called a list comprehension. See F.C.'s answer for a related technique. The basic syntax is [{expression} for {item_var_or_vars} in {iterable} if {boolean_expression}]. It's semantically equivalent to something like this:

new_list = []
for {item_var_or_vars} in {iterable}:
    if {boolean_expression}:
        new_list.append({expression})

The if {boolean_expression} bit is optional, just as it is in the for loop.

The second is simply the built-in function filter, which accepts a test function and an iterable, and returns a list containing every element that "passes" the test function. lambda, if you haven't seen it before, is just a quick way of defining a function. You could do this instead:

def keep_this_element(element):
    return element[0].startswith('img')   # returns True for ('img...', '...')

new_list = filter(keep_this_element, l)   # keeps only elements that return True


问:
How to check if a python string is a valid Bengali word using regular expression?
I am trying to test if a word is a valid Bengali word which may contain Bengali letters, vowel markers, 'Hasanta' ("্"), Bengali digits, all punctuation symbols including Bengali "।". We can test this easily for English using regex patter "\w+", but I cannot find any way to do this in Bengali.

For example, these strings: "আমি", "ভাত", "খাই।", "১২৩" should be detected as valid Bengali words, but "I", "eat", "rice", "123" should be detected as invalid words.

答:
You can pip install regex and use

bool(regex.fullmatch(r'\P{L}*\p{Bengali}+(?:\P{L}+\p{Bengali}+)*\P{L}*', word)
```
<p>Note that <code>regex.fullmatch</code> will require a full string to match the following pattern:</p>
<ul>
<li><code>\P{L}*</code> - zero or more non-letter chars</li>
<li><code>\p{Bengali}+</code> - one or more Bengali chars</li>
<li><code>(?:\P{L}+\p{Bengali}+)*</code> - zero or more sequences of one or more non-letter chars and then one or more Bengali chars</li>
<li><code>\P{L}*</code> - zero or more non-letter chars.</li>
</ul>
<p>See the Python demo:</p>
<pre class="lang-py prettyprint-override"><code>import regex
words = ["আমি", "ভাত", "খাই।", "১২৩", "I", "eat", "rice", "123"]
for word in words:
    print( word, '=>', bool(regex.fullmatch(r'\P{L}*\p{Bengali}+(?:\P{L}+\p{Bengali}+)*\P{L}*', word)) )
</code>```

Output:

আমি => True
ভাত => True
খাই। => True
১২৩ => True
I => False
eat => False
rice => False
123 => False
```

Body:
You can pip install regex and use

bool(regex.fullmatch(r'\P{L}*\p{Bengali}+(?:\P{L}+\p{Bengali}+)*\P{L}*', word)

Note that regex.fullmatch will require a full string to match the following pattern:

\P{L}* - zero or more non-letter chars

\p{Bengali}+ - one or more Bengali chars

(?:\P{L}+\p{Bengali}+)* - zero or more sequences of one or more non-letter chars and then one or more Bengali chars

\P{L}* - zero or more non-letter chars.

See the Python demo:

import regex
words = ["আমি", "ভাত", "খাই।", "১২৩", "I", "eat", "rice", "123"]
for word in words:
    print( word, '=>', bool(regex.fullmatch(r'\P{L}*\p{Bengali}+(?:\P{L}+\p{Bengali}+)*\P{L}*', word)) )

Output:

আমি => True
ভাত => True
খাই। => True
১২৩ => True
I => False
eat => False
rice => False
123 => False


问:
Java: PubsubMessage Subscriber receives message with no data or attribute
I'm trying to receive message to a topic and receive the message in the subscriber. But in the subscriber I don't receive any message, only an empty PubsubMessage.

Subscriber

```<code>package com.dsam.assignment02.functions;

import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import com.google.pubsub.v1.PubsubMessage;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;

public class OrderBillPdfGeneratorFunction implements BackgroundFunction<PubsubMessage> {
    private static final Logger logger = Logger.getLogger(OrderBillPdfGeneratorFunction.class.getName());

    @Override
    public void accept(PubsubMessage payload, Context context) throws Exception {
        String s = payload.getData().isEmpty() ? "No data" : new String(
            Base64.getDecoder().decode(payload.getData().toByteArray()),
            StandardCharsets.UTF_8
        );
        String t = String.valueOf(payload.getAttributesCount());
        logger.log(Level.INFO, String.format("Data: %s\nAttribute Count: %s", s, t));
    }
}
</code>```

Log Output

```<code>Data: No data
Attribute Count: 0
</code>```

Any idea what I'm missing here?

Update

I published message from cloud console pub/sub topic, but still didn't receive any data, which rules out the possiblity of issue being related to the publisher code.

答:
Eventually I fugured out the problem. I had to define my own class for function parameter instead of using com.google.pubsub.v1.PubsubMessage.

Defined below PubSubMessage class and used as public class OrderBillPdfGeneratorFunction implements BackgroundFunction<PubSubMessage>

```<code>public static class PubSubMessage {
    public String data;
    public Map<String, String> attributes;
    public String messageId;
    public String publishTime;
}
</code>```

This solved the issue.

EDIT

Here's the full working code.

```<code>package com.dsam.assignment02.functions;

import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import com.google.pubsub.v1.PubsubMessage;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;

public class OrderBillPdfGeneratorFunction implements BackgroundFunction<PubSubMessage> {
    private static final Logger logger = Logger.getLogger(OrderBillPdfGeneratorFunction.class.getName());

    @Override
    public void accept(PubSubMessage payload, Context context) throws Exception {
        String s = payload.getData().isEmpty() ? "No data" : new String(
            Base64.getDecoder().decode(payload.getData().toByteArray()),
            StandardCharsets.UTF_8
        );
        String t = String.valueOf(payload.getAttributesCount());
        logger.log(Level.INFO, String.format("Data: %s\nAttribute Count: %s", s, t));
    }

    public static class PubSubMessage {
        public String data;
        public Map<String, String> attributes;
        public String messageId;
        public String publishTime;
    }
}
</code>```

Body:
I'm trying to receive message to a topic and receive the message in the subscriber. But in the subscriber I don't receive any message, only an empty PubsubMessage.

Subscriber

package com.dsam.assignment02.functions;

import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import com.google.pubsub.v1.PubsubMessage;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;

public class OrderBillPdfGeneratorFunction implements BackgroundFunction<PubsubMessage> {
    private static final Logger logger = Logger.getLogger(OrderBillPdfGeneratorFunction.class.getName());

    @Override
    public void accept(PubsubMessage payload, Context context) throws Exception {
        String s = payload.getData().isEmpty() ? "No data" : new String(
            Base64.getDecoder().decode(payload.getData().toByteArray()),
            StandardCharsets.UTF_8
        );
        String t = String.valueOf(payload.getAttributesCount());
        logger.log(Level.INFO, String.format("Data: %s\nAttribute Count: %s", s, t));
    }
}

Log Output

Data: No data
Attribute Count: 0

Any idea what I'm missing here?

Update

I published message from cloud console pub/sub topic, but still didn't receive any data, which rules out the possiblity of issue being related to the publisher code.

Body:
Eventually I fugured out the problem. I had to define my own class for function parameter instead of using com.google.pubsub.v1.PubsubMessage.

Defined below PubSubMessage class and used as public class OrderBillPdfGeneratorFunction implements BackgroundFunction<PubSubMessage>

public static class PubSubMessage {
    public String data;
    public Map<String, String> attributes;
    public String messageId;
    public String publishTime;
}

This solved the issue.

EDIT

Here's the full working code.

package com.dsam.assignment02.functions;

import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import com.google.pubsub.v1.PubsubMessage;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;

public class OrderBillPdfGeneratorFunction implements BackgroundFunction<PubSubMessage> {
    private static final Logger logger = Logger.getLogger(OrderBillPdfGeneratorFunction.class.getName());

    @Override
    public void accept(PubSubMessage payload, Context context) throws Exception {
        String s = payload.getData().isEmpty() ? "No data" : new String(
            Base64.getDecoder().decode(payload.getData().toByteArray()),
            StandardCharsets.UTF_8
        );
        String t = String.valueOf(payload.getAttributesCount());
        logger.log(Level.INFO, String.format("Data: %s\nAttribute Count: %s", s, t));
    }

    public static class PubSubMessage {
        public String data;
        public Map<String, String> attributes;
        public String messageId;
        public String publishTime;
    }
}


问:
Compose Desktop projects: how to include API keys (or other secrets) without committing?
In Compose Desktop projects, how can we manage secret keys without committing?

In Android projects, Gradle has the buildConfigField() and resValue() functions. They will generate a BuildConfig.java during compile time, and we can use the values during runtime.

For example, in an Android project, first, we create two environment variables — RELEASE_API_KEY and STAGING_API_KEY (It can be either local computer, or a CI/CD environment).

Then in build.gradle file we can say:

```<code>android {
   buildTypes {
     release {
       buildConfigField("String", "API_KEY", "\"${System.getenv('RELEASE_API_KEY')}\"")
     }
     staging {
       buildConfigField("String", "API_KEY", "\"{System.getenv('STAGING_API_KEY')}\"")
     }
   }
}
</code>```

..and in the Kotlin code we can use:

val apiManager = ApiManager( BuildConfig.API_KEY )
```

Is there a similar approach in Compose Desktop projects so that:

I don't have to commit the secret to the source repository?

I can easily configure secrets in a CI/CD environment?

答:
So there are some Gradle plugins that were built to solve just a problem like this - inject build time constants into our runtime code. Here is the one that came up in a Google search:

https://github.com/gmazzo/gradle-buildconfig-plugin

And here is the one that came up when I swapped the c in config for a k (you know these Kotlin devs can't resist it right?)

https://github.com/yshrsmz/BuildKonfig

Of course - if you don't want to mess around with gradle plugins like this, the easy solution is to just create a file with your dev code where the same constants are nulled out or are empty strings, or reference an ignored file to get the value, and then just overwrite the file in CI using bash, replacing all the constants with what you want. This approach is very useful when you don't have access to gradle, like in a js project:

```<code>#!/usr/bin/env bash

AWS_FILE=<your aws credentials file here>
if [ -f "$AWS_FILE" ]; then
    echo "Injecting the AWS Credentials"
    echo "export const AWS_CREDENTIALS = {
    clientId: \"$AWS_CLIENT_ID\",
    secret: \"$AWS_CLIENT_SECRET\"}" > $AWS_FILE
else
    echo "$AWS_FILE doesn't exist."
    exit 1
fi
</code>```

Body:
In Compose Desktop projects, how can we manage secret keys without committing?

In Android projects, Gradle has the buildConfigField() and resValue() functions. They will generate a BuildConfig.java during compile time, and we can use the values during runtime.

For example, in an Android project, first, we create two environment variables — RELEASE_API_KEY and STAGING_API_KEY (It can be either local computer, or a CI/CD environment).

Then in build.gradle file we can say:

android {
   buildTypes {
     release {
       buildConfigField("String", "API_KEY", "\"${System.getenv('RELEASE_API_KEY')}\"")
     }
     staging {
       buildConfigField("String", "API_KEY", "\"{System.getenv('STAGING_API_KEY')}\"")
     }
   }
}

..and in the Kotlin code we can use:

val apiManager = ApiManager( BuildConfig.API_KEY )

Is there a similar approach in Compose Desktop projects so that:

I don't have to commit the secret to the source repository?

I can easily configure secrets in a CI/CD environment?

Body:
So there are some Gradle plugins that were built to solve just a problem like this - inject build time constants into our runtime code. Here is the one that came up in a Google search:

https://github.com/gmazzo/gradle-buildconfig-plugin

And here is the one that came up when I swapped the c in config for a k (you know these Kotlin devs can't resist it right?)

https://github.com/yshrsmz/BuildKonfig

Of course - if you don't want to mess around with gradle plugins like this, the easy solution is to just create a file with your dev code where the same constants are nulled out or are empty strings, or reference an ignored file to get the value, and then just overwrite the file in CI using bash, replacing all the constants with what you want. This approach is very useful when you don't have access to gradle, like in a js project:

#!/usr/bin/env bash

AWS_FILE=<your aws credentials file here>
if [ -f "$AWS_FILE" ]; then
    echo "Injecting the AWS Credentials"
    echo "export const AWS_CREDENTIALS = {
    clientId: \"$AWS_CLIENT_ID\",
    secret: \"$AWS_CLIENT_SECRET\"}" > $AWS_FILE
else
    echo "$AWS_FILE doesn't exist."
    exit 1
fi


问:
NextJS Prerender Error - Works fine in Dev, breaks in Build
I am building a NextJS application and everything is working fine locally. It pulls in all of the data and throws no error.

However, when I try to run npm run build, I get a Prerender Error. I have tried to follow the instructions in the documentation, but I didn't find it very helpful.

Could the problem be that I'm importing the posts using path.join(process.cwd(), './posts') and in this case, when it builds, the paths are somehow different than in development? I can't think of anything else that could be missing.

package.json

```<code>{
  ...
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  ....
}
</code>```

Full error:

Error occurred prerendering page "/blog/Blog". Read more: https://nextjs.org/docs/messages/prerender-error
TypeError: Cannot read property 'slug' of undefined
    at Post (/.next/server/chunks/2648.js:223:21)
    at d (/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:33:498)
    at bb (/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:36:16)
    at a.b.render (/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:42:43)
    at a.b.read (/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:41:83)
    at Object.exports.renderToString (/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:52:138)
    at renderPage (/node_modules/next/dist/server/render.js:736:46)
    at Object.ctx.renderPage (/.next/server/pages/_document.js:77:26)
    at Object.defaultGetInitialProps (/node_modules/next/dist/server/render.js:368:51)
    at Function.getInitialProps (/.next/server/chunks/6859.js:651:16)
postdirectory /posts
```
<p>Here is my file structure:</p>
```lib
 ┗ posts.js
pages
 ┣ blog
 ┃ ┣ Blog
 ┃ ┃ ┗ index.tsx
 ┃ ┣ Hero
 ┃ ┃ ┗ index.tsx
 ┃ ┗ [slug].tsx
 ┣ knowledge
 ┃ ┣ components
 ┃ ┃ ┣ BlogSection
 ┃ ┃ ┃ ┣ components
 ┃ ┃ ┃ ┃ ┗ ArticleBox
 ┃ ┃ ┃ ┃  ┗ ArticleBox.tsx
 ┃ ┃ ┃ ┗ index.tsx
 ┃ ┃ ┣ Hero
 ┃ ┃ ┃ ┗ index.tsx
 ┃ ┗ index.tsx
 ┣ _app.css
 ┣ _app.tsx
 ┣ _document.tsx
 ┗ index.tsx
posts
 ┣ post_1.md
 ┣ post_2.md
 ┣ post_3.md
```
<p>pages/blog/[slug].tsx</p>
<pre class="lang-js prettyprint-override"><code>import { getAllPostIds, getPostData, getSortedPostsData } from '../../lib/posts';
import React from 'react';
import Hero from './Hero';
import BlogSection from './Blog';

export interface Props {
    postData: {...},
    posts: {...}[]
}

const BlogArticle: React.FC<Props> = ({ postData, posts }) => {
    return (
        <>
            <Hero />
            <BlogSection postData={postData} posts={posts} />
        </>
    );
};

export default BlogArticle;

export async function getStaticPaths() {
    const paths = await getAllPostIds();
    return {
        paths,
        fallback: false
    }
}

export async function getStaticProps({ params }) {
    return {
        props: {
            postData: await getPostData(params.slug),
            posts: await getSortedPostsData()
        }
    }
}
</code>```

lib/posts.js

import fs from 'fs'
import path from 'path'
import matter from 'gray-matter'

const postsDirectory = path.join(process.cwd(), './posts')

export async function getSortedPostsData() {
    const fileNames = fs.readdirSync(postsDirectory)
    const allPostsData = fileNames.map(fileName => {
        const slug = fileName.replace(/\.md$/, '')

        const fullPath = path.join(postsDirectory, fileName)
        const fileContents = fs.readFileSync(fullPath, 'utf8')

        const matterResult = matter(fileContents)

        return {
            slug,
            ...matterResult.data
        }
    })
}

export async function getAllPostIds() {
    const fileNames = fs.readdirSync(postsDirectory)

    return fileNames.map(fileName => {
        return {
            params: {
                slug: fileName.replace(/\.md$/, '')
            }
        }
    })
}

export async function getPostData(slug) {
    const fullPath = path.join(postsDirectory, `${slug}.md`)
    const fileContents = fs.readFileSync(fullPath, 'utf8')
    const { data: frontmatter, content } = matter(fileContents)

    return {
        slug,
        content,
        frontmatter
    }
}
```

Thanks everyone!

答:
Thanks @TDiblik for pointing me in the right direction. As he mentioned, there is a good example from Vercel.

One thing that I noticed that I did not do was add a way to handle the situation in which the post data was not available. In this case, I needed to add the following within the default exports for each page / component that was receiving the data.

```<code>    const router = useRouter()
    if (!router.isFallback && !post) {
        return <ErrorPage statusCode={404} />
    }
</code>```

In this case, my pages/blog/[slug].tsx should look like:

```<code>import { getAllPostIds, getPostData, getSortedPostsData } from '../../lib/posts';
import React from 'react';
import Hero from './Hero';
import BlogSection from './Blog';
import { useRouter } from 'next/router'
import ErrorPage from 'next/error'

export interface Props {
    postData: {...},
    posts: {...}[]
}

const BlogArticle: React.FC<Props> = ({ postData, posts }) => {
    const router = useRouter()
    if (!router.isFallback && !postData && !posts) {
        return <ErrorPage statusCode={404} />
    }
    return (
        <>
            <Hero />
            <BlogSection postData={postData} posts={posts} />
        </>
    );
};

export default BlogArticle;

export async function getStaticPaths() {
    const paths = await getAllPostIds();
    return {
        paths,
        fallback: false
    }
}

export async function getStaticProps({ params }) {
    return {
        props: {
            postData: await getPostData(params.slug),
            posts: await getSortedPostsData()
        }
    }
}
</code>```

With this change, I was able to build the project.

Thanks again Tomas!

Body:
I am building a NextJS application and everything is working fine locally. It pulls in all of the data and throws no error.

However, when I try to run npm run build, I get a Prerender Error. I have tried to follow the instructions in the documentation, but I didn't find it very helpful.

Could the problem be that I'm importing the posts using path.join(process.cwd(), './posts') and in this case, when it builds, the paths are somehow different than in development? I can't think of anything else that could be missing.

package.json

{
  ...
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  ....
}

Full error:

Error occurred prerendering page "/blog/Blog". Read more: https://nextjs.org/docs/messages/prerender-error
TypeError: Cannot read property 'slug' of undefined
    at Post (/.next/server/chunks/2648.js:223:21)
    at d (/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:33:498)
    at bb (/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:36:16)
    at a.b.render (/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:42:43)
    at a.b.read (/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:41:83)
    at Object.exports.renderToString (/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:52:138)
    at renderPage (/node_modules/next/dist/server/render.js:736:46)
    at Object.ctx.renderPage (/.next/server/pages/_document.js:77:26)
    at Object.defaultGetInitialProps (/node_modules/next/dist/server/render.js:368:51)
    at Function.getInitialProps (/.next/server/chunks/6859.js:651:16)
postdirectory /posts

Here is my file structure:

lib
 ┗ posts.js
pages
 ┣ blog
 ┃ ┣ Blog
 ┃ ┃ ┗ index.tsx
 ┃ ┣ Hero
 ┃ ┃ ┗ index.tsx
 ┃ ┗ [slug].tsx
 ┣ knowledge
 ┃ ┣ components
 ┃ ┃ ┣ BlogSection
 ┃ ┃ ┃ ┣ components
 ┃ ┃ ┃ ┃ ┗ ArticleBox
 ┃ ┃ ┃ ┃  ┗ ArticleBox.tsx
 ┃ ┃ ┃ ┗ index.tsx
 ┃ ┃ ┣ Hero
 ┃ ┃ ┃ ┗ index.tsx
 ┃ ┗ index.tsx
 ┣ _app.css
 ┣ _app.tsx
 ┣ _document.tsx
 ┗ index.tsx
posts
 ┣ post_1.md
 ┣ post_2.md
 ┣ post_3.md

pages/blog/[slug].tsx

import { getAllPostIds, getPostData, getSortedPostsData } from '../../lib/posts';
import React from 'react';
import Hero from './Hero';
import BlogSection from './Blog';

export interface Props {
    postData: {...},
    posts: {...}[]
}

const BlogArticle: React.FC<Props> = ({ postData, posts }) => {
    return (
        <>
            <Hero />
            <BlogSection postData={postData} posts={posts} />
        </>
    );
};

export default BlogArticle;

export async function getStaticPaths() {
    const paths = await getAllPostIds();
    return {
        paths,
        fallback: false
    }
}

export async function getStaticProps({ params }) {
    return {
        props: {
            postData: await getPostData(params.slug),
            posts: await getSortedPostsData()
        }
    }
}

lib/posts.js

import fs from 'fs'
import path from 'path'
import matter from 'gray-matter'

const postsDirectory = path.join(process.cwd(), './posts')

export async function getSortedPostsData() {
    const fileNames = fs.readdirSync(postsDirectory)
    const allPostsData = fileNames.map(fileName => {
        const slug = fileName.replace(/\.md$/, '')

        const fullPath = path.join(postsDirectory, fileName)
        const fileContents = fs.readFileSync(fullPath, 'utf8')

        const matterResult = matter(fileContents)

        return {
            slug,
            ...matterResult.data
        }
    })
}

export async function getAllPostIds() {
    const fileNames = fs.readdirSync(postsDirectory)

    return fileNames.map(fileName => {
        return {
            params: {
                slug: fileName.replace(/\.md$/, '')
            }
        }
    })
}

export async function getPostData(slug) {
    const fullPath = path.join(postsDirectory, `${slug}.md`)
    const fileContents = fs.readFileSync(fullPath, 'utf8')
    const { data: frontmatter, content } = matter(fileContents)

    return {
        slug,
        content,
        frontmatter
    }
}

Thanks everyone!

Body:
Thanks @TDiblik for pointing me in the right direction. As he mentioned, there is a good example from Vercel.

One thing that I noticed that I did not do was add a way to handle the situation in which the post data was not available. In this case, I needed to add the following within the default exports for each page / component that was receiving the data.

    const router = useRouter()
    if (!router.isFallback && !post) {
        return <ErrorPage statusCode={404} />
    }

In this case, my pages/blog/[slug].tsx should look like:

import { getAllPostIds, getPostData, getSortedPostsData } from '../../lib/posts';
import React from 'react';
import Hero from './Hero';
import BlogSection from './Blog';
import { useRouter } from 'next/router'
import ErrorPage from 'next/error'

export interface Props {
    postData: {...},
    posts: {...}[]
}

const BlogArticle: React.FC<Props> = ({ postData, posts }) => {
    const router = useRouter()
    if (!router.isFallback && !postData && !posts) {
        return <ErrorPage statusCode={404} />
    }
    return (
        <>
            <Hero />
            <BlogSection postData={postData} posts={posts} />
        </>
    );
};

export default BlogArticle;

export async function getStaticPaths() {
    const paths = await getAllPostIds();
    return {
        paths,
        fallback: false
    }
}

export async function getStaticProps({ params }) {
    return {
        props: {
            postData: await getPostData(params.slug),
            posts: await getSortedPostsData()
        }
    }
}

With this change, I was able to build the project.

Thanks again Tomas!


问:
Spring: Why do we autowire the interface and not the implemented class?
Example

```<code>interface IA
{
  public void someFunction();
}

@Resource(name="b")
class B implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someBfunc()
  {
     //doing b things
  }
}

@Resource(name="c")
class C implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someCfunc()
  {
     //doing C things
  }
}

class MyRunner
{

  @Autowire
  @Qualifier("b")
  IA worker;

  worker.someFunction();
}
</code>```

Can someone explain this to me.

How does spring know which polymorphic type to use.

Do I need @Qualifier or @Resource?

Why do we autowire the interface and not the implemented class?

答:
It worked for me only when I declared following bean in my .XML configuration file because @Autowired is a post process

```<code><bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"></bean>
</code>```

Body:
Example

interface IA
{
  public void someFunction();
}

@Resource(name="b")
class B implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someBfunc()
  {
     //doing b things
  }
}

@Resource(name="c")
class C implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someCfunc()
  {
     //doing C things
  }
}

class MyRunner
{

  @Autowire
  @Qualifier("b")
  IA worker;

  worker.someFunction();
}

Can someone explain this to me.

How does spring know which polymorphic type to use.

Do I need @Qualifier or @Resource?

Why do we autowire the interface and not the implemented class?

Body:
It worked for me only when I declared following bean in my .XML configuration file because @Autowired is a post process

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"></bean>


问:
How to sort files and then populate a ListBox?
This code populate a ListBox with the file names of a specific folder

```<code>Dim DIRECTORY As String
DIRECTORY = Dir(myPath & "\*.xlsx", vbNormal)
Do Until DIRECTORY = ""
ListBox1.AddItem DIRECTORY
DIRECTORY = Dir()
Loop
</code>```

But I want a sorted list.

How can I sort the files firstly and then populate the ListBox.

btw sorting a listbox is (as I know) a long procedure.

答:
The DIR command always displays elements sorted alphabetically but by name, not type.
The correct thing would be to take advantage of the "vbDirectory" and "vbArchive" attributes and first create a list with vbDirectory and then another with vbArchive. The result is a single alphabetically sorted list that separates directories from files.

```<code>Private Sub ListarFunc()
Dim a As Integer
Dim strArchivo As String
Dim FileName As String
Dim TipoArchivo As String
Dim fso As Object, file As Object, folder As Object
Set fso = CreateObject("Scripting.FileSystemObject")

On Error Resume Next

    'If we are not in /root add a "\" to the PathExplorer
    If Mid(Me.BoxPathExplorer, 4, 1) <> "" Then Me.BoxPathExplorer = CurDir() & "\"
    Me.Lista1.ForeColor = RGB(25, 25, 100)
    Me.Lista1.RowSource = ""    'First, clear the list
    Me.Lista1.AddItem "___________________ TIPO ___________________" & ";" & "________________ " & _
        Dir(Me.BoxPathExplorer, vbVolume) & " ________________"

    strArchivo = Dir(Me.BoxPathExplorer, vbDirectory)
    While strArchivo <> ""
        Set folder = fso.GetFolder(strArchivo)
        If folder.Attributes And vbDirectory Then Me.Lista1.AddItem folder.Type & ";" & strArchivo
        strArchivo = Dir
        Set folder = Nothing
    Wend

    strArchivo = Dir(Me.BoxPathExplorer, vbArchive)
    While strArchivo <> ""
        Set file = fso.GetFile(strArchivo)
        If file.Attributes And vbArchive Then Me.Lista1.AddItem file.Type & ";" & strArchivo
        strArchivo = Dir
        Set file = Nothing
    Wend

    If Lista1.ItemData(1) = "." Then Me.Lista1.RemoveItem 1            'Delete the item '.'
    Me.Lista1 = "NoSelection"
End Sub
</code>```

Regards.

Body:
This code populate a ListBox with the file names of a specific folder

Dim DIRECTORY As String
DIRECTORY = Dir(myPath & "\*.xlsx", vbNormal)
Do Until DIRECTORY = ""
ListBox1.AddItem DIRECTORY
DIRECTORY = Dir()
Loop

But I want a sorted list.

How can I sort the files firstly and then populate the ListBox.

btw sorting a listbox is (as I know) a long procedure.

Body:
The DIR command always displays elements sorted alphabetically but by name, not type.
The correct thing would be to take advantage of the "vbDirectory" and "vbArchive" attributes and first create a list with vbDirectory and then another with vbArchive. The result is a single alphabetically sorted list that separates directories from files.

Private Sub ListarFunc()
Dim a As Integer
Dim strArchivo As String
Dim FileName As String
Dim TipoArchivo As String
Dim fso As Object, file As Object, folder As Object
Set fso = CreateObject("Scripting.FileSystemObject")

On Error Resume Next

    'If we are not in /root add a "\" to the PathExplorer
    If Mid(Me.BoxPathExplorer, 4, 1) <> "" Then Me.BoxPathExplorer = CurDir() & "\"
    Me.Lista1.ForeColor = RGB(25, 25, 100)
    Me.Lista1.RowSource = ""    'First, clear the list
    Me.Lista1.AddItem "___________________ TIPO ___________________" & ";" & "________________ " & _
        Dir(Me.BoxPathExplorer, vbVolume) & " ________________"

    strArchivo = Dir(Me.BoxPathExplorer, vbDirectory)
    While strArchivo <> ""
        Set folder = fso.GetFolder(strArchivo)
        If folder.Attributes And vbDirectory Then Me.Lista1.AddItem folder.Type & ";" & strArchivo
        strArchivo = Dir
        Set folder = Nothing
    Wend

    strArchivo = Dir(Me.BoxPathExplorer, vbArchive)
    While strArchivo <> ""
        Set file = fso.GetFile(strArchivo)
        If file.Attributes And vbArchive Then Me.Lista1.AddItem file.Type & ";" & strArchivo
        strArchivo = Dir
        Set file = Nothing
    Wend

    If Lista1.ItemData(1) = "." Then Me.Lista1.RemoveItem 1            'Delete the item '.'
    Me.Lista1 = "NoSelection"
End Sub

Regards.


问:
XMLHTTP and Special Characters (eg, accents)
I am using Microsoft.XMLHTTP via VBA to pull in the body of a web page. In doing so, characters such as é get replaced with "?" or something equally not useful.

Here's the basic code:

```<code>Set objHTTP = CreateObject("Microsoft.XMLHTTP")

objHTTP.Open "GET", ThisWebPage, False
objHTTP.setRequestHeader "Content-Type", _
      "application/x-www-form-urlencoded; charset=UTF-8"
objHTTP.Send ("")

strResponse = objHTTP.responseText
</code>```

Is there any way to retrieve the page with the special characters intact?

Note:
I have also tried using this request header with no success:

objHTTP.setRequestHeader "Content-Type", "content=text/html; charset=iso-8859-1"

Thanks in advance.

Solution

Thanks to Ben.Vineyard (and some cursory Googling), I'm able to pull accented characters with the following code:

```<code> ' Create the XMLHTTP object
  Set objHTTP = CreateObject("Microsoft.XMLHTTP")

 ' Send the request
 objHTTP.Open "GET", WhatWebPage, False
 objHTTP.Send ("")

 Dim BinaryStream
 Set BinaryStream = CreateObject("ADODB.Stream")

 With BinaryStream
    .Type = adTypeBinary
    .Open
    .Write objHTTP.ResponseBody

    'Change stream type To binary
    .Position = 0
    .Type = adTypeText

    'Specify charset For the source text (unicode) data.
    .Charset = "iso-8859-1"

    'Open the stream And get binary data from the object
    strResponse = .ReadText
End With
</code>```

答: The problem could be that you do not actually send the data encoded as utf-8. It might be in Ansi or whatever string/file encoding you use. And then it will not be able to use characters high than 127 in the ASCII code.  Are you sure that the original text stream is utf-8?  Have you tried other encoding like one of the iso-* formats?</p>

Body:
I am using Microsoft.XMLHTTP via VBA to pull in the body of a web page. In doing so, characters such as é get replaced with "?" or something equally not useful.

Here's the basic code:

Set objHTTP = CreateObject("Microsoft.XMLHTTP")

objHTTP.Open "GET", ThisWebPage, False
objHTTP.setRequestHeader "Content-Type", _
      "application/x-www-form-urlencoded; charset=UTF-8"
objHTTP.Send ("")

strResponse = objHTTP.responseText

Is there any way to retrieve the page with the special characters intact?

Note:
I have also tried using this request header with no success:

objHTTP.setRequestHeader "Content-Type", "content=text/html; charset=iso-8859-1"

Thanks in advance.

Solution

Thanks to Ben.Vineyard (and some cursory Googling), I'm able to pull accented characters with the following code:

 ' Create the XMLHTTP object
  Set objHTTP = CreateObject("Microsoft.XMLHTTP")

 ' Send the request
 objHTTP.Open "GET", WhatWebPage, False
 objHTTP.Send ("")

 Dim BinaryStream
 Set BinaryStream = CreateObject("ADODB.Stream")

 With BinaryStream
    .Type = adTypeBinary
    .Open
    .Write objHTTP.ResponseBody

    'Change stream type To binary
    .Position = 0
    .Type = adTypeText

    'Specify charset For the source text (unicode) data.
    .Charset = "iso-8859-1"

    'Open the stream And get binary data from the object
    strResponse = .ReadText
End With


问:
h5py file subset taking more space than parent file?
I have an existing h5py file that I downloaded which is ~18G in size. It has a number of nested datasets within it:

h5f = h5py.File('input.h5', 'r')
data = h5f['data']
latlong_data = data['lat_long'].value
```
<p>I want to be able to some basic min/max scaling of the numerical data within <code>latlong</code>, so i want to put it in its own h5py file for easier use and lower memory usage.</p>
<p>However, when i try to write it out to its own file:</p>
<pre class="lang-py prettyprint-override"><code>out = h5py.File('latlong_only.h5', 'w')
out.create_dataset('latlong', data=latlong)
out.close()
</code>```

The output file is incredibly large. It's still not done writing to disk and is ~85GB in space. Why is the data being written to the new file not compressed?

答:
Could be h5f['data/lat_long'] is using compression filters (and you aren't). To check the original dataset's compression settings, use this line:

```<code>print (h5f['data/latlong'].compression, h5f['data/latlong'].compression_opts)
</code>```

After writing my answer, it occurred to me that you don't need to copy the data to another file to reduce the memory footprint. Your code reads the dataset into an array, which is not necessary in most use cases. A h5py dataset object behaves similar to a NumPy array. Instead, use this line: ds = h5f1['data/latlong'] to create a dataset object (instead of an array)  and use it "like" it's a NumPy array. FYI, .value is a deprecated method to return the dataset as an array. Use this syntax instead arr = h5f1['data/latlong'][()]. Loading the dataset into an array also requires more memory than using an h5py object (which could be an issue with large datasets).

There are other ways to access the data. My suggestion to use dataset objects is 1 way. Your method (extracting data to a new file) is another way. I am not found of that approach because you now have 2 copies of the data; a bookkeeping nightmare. Another alternative is to create external links from the new file to the existing 18GB file. That way you have a small file that links to the big file (and no duplicate data). I describe that method in this post: [How can I combine multiple .h5 file?][1] Method 1: Create External Links.

If you still want to copy the data, here is what I would do. Your code reads the dataset into an array then writes the array to the new file (uncompressed). Instead, copy the dataset using h5py's group .copy() method, it will retain compression settings and attributes.
See below:

```<code>with h5py.File('input.h5', 'r') as h5f1, \
     h5py.File('latlong_only.h5', 'w') as h5f2:

    h5f1.copy(h5f1['data/latlong'], h5f2,'latlong')
</code>```

Body:
I have an existing h5py file that I downloaded which is ~18G in size. It has a number of nested datasets within it:

h5f = h5py.File('input.h5', 'r')
data = h5f['data']
latlong_data = data['lat_long'].value

I want to be able to some basic min/max scaling of the numerical data within latlong, so i want to put it in its own h5py file for easier use and lower memory usage.

However, when i try to write it out to its own file:

out = h5py.File('latlong_only.h5', 'w')
out.create_dataset('latlong', data=latlong)
out.close()

The output file is incredibly large. It's still not done writing to disk and is ~85GB in space. Why is the data being written to the new file not compressed?

Body:
Could be h5f['data/lat_long'] is using compression filters (and you aren't). To check the original dataset's compression settings, use this line:

print (h5f['data/latlong'].compression, h5f['data/latlong'].compression_opts)

After writing my answer, it occurred to me that you don't need to copy the data to another file to reduce the memory footprint. Your code reads the dataset into an array, which is not necessary in most use cases. A h5py dataset object behaves similar to a NumPy array. Instead, use this line: ds = h5f1['data/latlong'] to create a dataset object (instead of an array)  and use it "like" it's a NumPy array. FYI, .value is a deprecated method to return the dataset as an array. Use this syntax instead arr = h5f1['data/latlong'][()]. Loading the dataset into an array also requires more memory than using an h5py object (which could be an issue with large datasets).

There are other ways to access the data. My suggestion to use dataset objects is 1 way. Your method (extracting data to a new file) is another way. I am not found of that approach because you now have 2 copies of the data; a bookkeeping nightmare. Another alternative is to create external links from the new file to the existing 18GB file. That way you have a small file that links to the big file (and no duplicate data). I describe that method in this post: [How can I combine multiple .h5 file?][1] Method 1: Create External Links.

If you still want to copy the data, here is what I would do. Your code reads the dataset into an array then writes the array to the new file (uncompressed). Instead, copy the dataset using h5py's group .copy() method, it will retain compression settings and attributes.
See below:

with h5py.File('input.h5', 'r') as h5f1, \
     h5py.File('latlong_only.h5', 'w') as h5f2:

    h5f1.copy(h5f1['data/latlong'], h5f2,'latlong')


问:
Excel Return Table name using Formula?
I was wondering if there is anyway to return the name of the table using a formula?

I was working on a way to break down a few thousand addresses into there perspective column of information. ie.. #, Street, City, State, Zip-code and Phone#. The addresses are not in any consistent format that Text to Columns would work. I finally came up with the formulas to get the job done, but the are very long. In a post I found it suggested to use repeated parts of the formulas as a Defined Name. And it made it so much easier. Now Here is the problem.

A formula that has the table name "Table1" won't work in "Table2". Or any other table name. Column headers are the same for each table.

```<code>MAX(SEARCH(Table1[@State],Table1[@Origin]))
</code>```

A way to return the name of the table is needed. Via formula or formula as Defined Name.

```<code>MAX(SEARCH(GetTableName[@State],GetTableName[@Origin]))
</code>```

I prefer it to be a formula. I'm not sure if a VBA solution would be a correct answer to this question so I would not be able to choose it as THE answer, even if it does work. It will still be appreciated. I will ask in a separate post if I do not find a Formula Solution.

TY

I found this post that has a VBA solution, but I can't use it. I will post just so someone can maybe figure this out. Portland Runner Posted this CODE to get table name.

```<code>Function GetTableName(shtName As String) As String
    GetTableName = Worksheets(shtName).ListObjects(1).Name
End Function
</code>```

In that Function I enter My Defined Name formula named "SheetName"

```<code>=MID(CELL("filename"),FIND("]",CELL("filename"))+1,100)
</code>```

So I can use it like this.

```<code>=MAX(SEARCH(INDIRECT(GetTableName(SheetName)&"[@State]"),INDIRECT(GetTableName(SheetName)&"[@Origin]")))
</code>```

However I still need this to be Formula Only. While I can run Macros on My PC, they will not run in the PC that has all the data.

This is the last thing I got using a UDF. Unfortunately I still cant use it. Plus It gets the first Table's name and not the actual table the cell is in. Good if that is the only table in sheet or if the first table is the table you want.

```<code>Function GetTableName() As String
    GetTableName = Worksheets(ActiveSheet.Name).ListObjects(1).Name
End Function
</code>```

答:
Following formula returns table name, referenced in it:

```<code>=LET(x, Table1[#Headers], y, FORMULATEXT(INDIRECT(ADDRESS(ROW(),COLUMN()))), z, LEFT(y, FIND("[", y)-1), TRIM(RIGHT(z, LEN(z)-FIND("x", z)-1)))
</code>```

Note: you can use any part of the table, not only Table1[#Headers].

For example it could be: Table1[#All] or Table1[Column1] or Table1[[#Headers],[Column1]].

The last one is useful, because you can just click a cell with a column name to paste it.

Title: Excel Return Table name using Formula?

Body:
I was wondering if there is anyway to return the name of the table using a formula?

I was working on a way to break down a few thousand addresses into there perspective column of information. ie.. #, Street, City, State, Zip-code and Phone#. The addresses are not in any consistent format that Text to Columns would work. I finally came up with the formulas to get the job done, but the are very long. In a post I found it suggested to use repeated parts of the formulas as a Defined Name. And it made it so much easier. Now Here is the problem.

A formula that has the table name "Table1" won't work in "Table2". Or any other table name. Column headers are the same for each table.

MAX(SEARCH(Table1[@State],Table1[@Origin]))

A way to return the name of the table is needed. Via formula or formula as Defined Name.

MAX(SEARCH(GetTableName[@State],GetTableName[@Origin]))

I prefer it to be a formula. I'm not sure if a VBA solution would be a correct answer to this question so I would not be able to choose it as THE answer, even if it does work. It will still be appreciated. I will ask in a separate post if I do not find a Formula Solution.

TY

I found this post that has a VBA solution, but I can't use it. I will post just so someone can maybe figure this out. Portland Runner Posted this CODE to get table name.

Function GetTableName(shtName As String) As String
    GetTableName = Worksheets(shtName).ListObjects(1).Name
End Function

In that Function I enter My Defined Name formula named "SheetName"

=MID(CELL("filename"),FIND("]",CELL("filename"))+1,100)

So I can use it like this.

=MAX(SEARCH(INDIRECT(GetTableName(SheetName)&"[@State]"),INDIRECT(GetTableName(SheetName)&"[@Origin]")))

However I still need this to be Formula Only. While I can run Macros on My PC, they will not run in the PC that has all the data.

This is the last thing I got using a UDF. Unfortunately I still cant use it. Plus It gets the first Table's name and not the actual table the cell is in. Good if that is the only table in sheet or if the first table is the table you want.

Function GetTableName() As String
    GetTableName = Worksheets(ActiveSheet.Name).ListObjects(1).Name
End Function

Body:
Following formula returns table name, referenced in it:

=LET(x, Table1[#Headers], y, FORMULATEXT(INDIRECT(ADDRESS(ROW(),COLUMN()))), z, LEFT(y, FIND("[", y)-1), TRIM(RIGHT(z, LEN(z)-FIND("x", z)-1)))

Note: you can use any part of the table, not only Table1[#Headers].

For example it could be: Table1[#All] or Table1[Column1] or Table1[[#Headers],[Column1]].

The last one is useful, because you can just click a cell with a column name to paste it.