问:
php 8.1 - explode(): Passing null to parameter #2 ($string) of type string is deprecated
Coming across some deprecated errors with 8.1 I want to address.

PHP Deprecated:  explode(): Passing null to parameter #2 ($string) of type string is deprecated in...

```<code>//explode uids into an array
$comp_uids = explode(',', $result['comp_uids']);
</code>```

$result['comp_uids'] in this case is empty which is why the null error shows.  I'm not sure why they are deprecating this ability, but what is the recommended change to avoid this?  I'm seeing similar with strlen(): Passing null to parameter #1 ($string) of type string is deprecated and a few others using 8.1.

答:
There's no need to explode null, you know beforehand that it won't return matches. If you really want [''] as result, it's more intuitive to make it explicit:

```<code>$comp_uids = $result['comp_uids'] !== null
    ? explode(',', $result['comp_uids'])
    : [''];
</code>```

I still find this a bit counter-intuitive for your fellow programmers. IMHO, the no UIDs were found concept is better represented by an empty array and, if you can expect empty strings as well, they may well be handled together with null:

```<code>$comp_uids = $result['comp_uids'] != ''
    ? explode(',', $result['comp_uids'])
    : [];
</code>```

Body:
Coming across some deprecated errors with 8.1 I want to address.

PHP Deprecated:  explode(): Passing null to parameter #2 ($string) of type string is deprecated in...

//explode uids into an array
$comp_uids = explode(',', $result['comp_uids']);

$result['comp_uids'] in this case is empty which is why the null error shows.  I'm not sure why they are deprecating this ability, but what is the recommended change to avoid this?  I'm seeing similar with strlen(): Passing null to parameter #1 ($string) of type string is deprecated and a few others using 8.1.

Body:
There's no need to explode null, you know beforehand that it won't return matches. If you really want [''] as result, it's more intuitive to make it explicit:

$comp_uids = $result['comp_uids'] !== null
    ? explode(',', $result['comp_uids'])
    : [''];

I still find this a bit counter-intuitive for your fellow programmers. IMHO, the no UIDs were found concept is better represented by an empty array and, if you can expect empty strings as well, they may well be handled together with null:

$comp_uids = $result['comp_uids'] != ''
    ? explode(',', $result['comp_uids'])
    : [];


来源: stackexchange

问:
Where is stored a gl.CreateTexture?
When creating a new texture using createTexture from the Web GL context, where is it stored? And it uses purely the GPU?

In the memory or in the graphics card memory? How's the performance in terms of resources (specially CPU load)?

Thanks!

答: gl.createTexture provides you with a GPU resource id, when and if that texture is allocated in GPU memory is up to the GPU driver.

ContentLicense: CC BY-SA 4.0

Title: Where is stored a gl.CreateTexture?


问:
Golang namespaces of namespaces
I'm kinda new to go and from being a C++ background I really wonder if its possible to achieve something like this. Let's say I have a math library and i want to make a namespace a children of another namespace like this.

main package

math package

matrix package

...

And I want to call my code like this ;

```<code>math.matrix.CreateTranslation(mat4, 30, 50, 0)
</code>```

Is there a way to achieve this kind of behaviour in go?

答:
Is there a way to achieve this kind of behaviour in go?

No, not really.

You can import "module/math" and then do math.SomeFunc. Or you can import "module/math/matrix" and then do matrix.SomeOtherFunc. These are referred to as "qualified identifiers".

But you cannot import "module/math" or "module/math/matrix" and then use a nested "qualified identifier" a la math.matrix.SomeOtherFunc. It's just not part of the spec.

Technically speaking it is possible to do the following:

math.Matrix.CreateTranslation(mat4, 30, 50, 0)
```

where Matrix is an exported variable in the math package and whose type either has a CreateTranslation method in its method set, or whose type is a struct type that has a function field called CreateTranslation.

While possible, it would, obviously, be an attempt to force an organizational pattern on a language that does not support it.

Title: Golang namespaces of namespaces

Body:
I'm kinda new to go and from being a C++ background I really wonder if its possible to achieve something like this. Let's say I have a math library and i want to make a namespace a children of another namespace like this.

main package

math package

matrix package

...

And I want to call my code like this ;

math.matrix.CreateTranslation(mat4, 30, 50, 0)

Is there a way to achieve this kind of behaviour in go?

Body:
Is there a way to achieve this kind of behaviour in go?

No, not really.

You can import "module/math" and then do math.SomeFunc. Or you can import "module/math/matrix" and then do matrix.SomeOtherFunc. These are referred to as "qualified identifiers".

But you cannot import "module/math" or "module/math/matrix" and then use a nested "qualified identifier" a la math.matrix.SomeOtherFunc. It's just not part of the spec.

Technically speaking it is possible to do the following:

math.Matrix.CreateTranslation(mat4, 30, 50, 0)

where Matrix is an exported variable in the math package and whose type either has a CreateTranslation method in its method set, or whose type is a struct type that has a function field called CreateTranslation.

While possible, it would, obviously, be an attempt to force an organizational pattern on a language that does not support it.


问:
How to compute the mean with null treated as zero
In Snowflake how can I return the mean of a column, where null values are treated as zero. So, if we have 3 values: 1, 2, NULL, I would like to return 1, not 1.5 as returned by AVG function.</p>

答:
You have several options, choose one of the following:

SELECT AVG(v) AS "avg"
     , AVG(COALESCE(v, 0)) AS "avg_with_coalesce"
     , AVG(CASE WHEN v IS NULL THEN 0 ELSE v END) AS "avg_with_case"
     , AVG(IFF(v IS NULL, 0, v)) AS "avg_with_iff"
     , AVG(IFNULL(v, 0)) AS "avg_with_ifnull"
     , AVG(ZEROIFNULL(v)) AS "avg_with_zeroifnull"
  FROM VALUES (1), (2), (NULL) AS t(v);
```

Result:

avg
avg_coalesce
avg_case
avg_iff
avg_ifnull
avg_zeroifnull

1.500000
1.000000
1.000000
1.000000
1.000000
1.000000

Body:
You have several options, choose one of the following:

SELECT AVG(v) AS "avg"
     , AVG(COALESCE(v, 0)) AS "avg_with_coalesce"
     , AVG(CASE WHEN v IS NULL THEN 0 ELSE v END) AS "avg_with_case"
     , AVG(IFF(v IS NULL, 0, v)) AS "avg_with_iff"
     , AVG(IFNULL(v, 0)) AS "avg_with_ifnull"
     , AVG(ZEROIFNULL(v)) AS "avg_with_zeroifnull"
  FROM VALUES (1), (2), (NULL) AS t(v);

Result:

avg
avg_coalesce
avg_case
avg_iff
avg_ifnull
avg_zeroifnull

1.500000
1.000000
1.000000
1.000000
1.000000
1.000000


问:
when I use the word async in webpack-3 the function not work
I was using async: false in ajax. I want to have the equivalent of this command in fetch. Apparently using async helps. But when I use the word async in the webpack, it does not work.
i use webbpack 3.8.1 and in webpack.config.js:

```<code>const path = require('path');
const webpack = require('webpack');

const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractCSS = new ExtractTextPlugin('allstyles_for_store_details_naghashi.css'/*'allstyles_for_store_details.css'*//*'allstyles.css'*/);

module.exports = {
    entry: {
         'main': './wwwroot/source/app_for_store_details_naghashi.js' ,
     },

    output: {
        path: path.resolve(__dirname, 'wwwroot/dist'),
        filename: 'bundle_for_store_details_naghashi.js' ,
        publicPath: 'dist/',
    },
    plugins: [
        extractCSS,
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',
            Popper: ['popper.js', 'default']
        }),
        new webpack.optimize.UglifyJsPlugin(),
    ],
    module: {
        rules: [
            {
                test: /\.css$/, use: extractCSS.extract(['css-loader?minimize'])
            },
            {
                test: /\.js?$/,
                use: {
                    loader: 'babel-loader', options: {
                        presets:
                            ['@babel/preset-react', '@babel/preset-env']
                    }
                }
            },
        ]
    }
};
</code>```

in my file :

```<code>async function f12() {
    alert('13579-1122');
}
f12();
</code>```

It does not work when I use the word async.
(I want the program to wait for the fetch command to complete when the fetch command is running. I was using async: false in ajax)

答:
Have a function that just fetches the data, and call that function from an async function that awaits the response (JSON, presumably), parses it, and then you can do what you want with it.

A bit like this:

function getData(url) {
  return fetch(url);
}

async function main() {
  try {
    const response = await getData('https://example.com');
    const data = await response.json();
    console.log(data);
  } catch(err) {
    console.log(err);
  }
}

main();```

Additional documentation

async/await

fetch

Body:
I was using async: false in ajax. I want to have the equivalent of this command in fetch. Apparently using async helps. But when I use the word async in the webpack, it does not work.
i use webbpack 3.8.1 and in webpack.config.js:

const path = require('path');
const webpack = require('webpack');

const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractCSS = new ExtractTextPlugin('allstyles_for_store_details_naghashi.css'/*'allstyles_for_store_details.css'*//*'allstyles.css'*/);

module.exports = {
    entry: {
         'main': './wwwroot/source/app_for_store_details_naghashi.js' ,
     },

    output: {
        path: path.resolve(__dirname, 'wwwroot/dist'),
        filename: 'bundle_for_store_details_naghashi.js' ,
        publicPath: 'dist/',
    },
    plugins: [
        extractCSS,
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',
            Popper: ['popper.js', 'default']
        }),
        new webpack.optimize.UglifyJsPlugin(),
    ],
    module: {
        rules: [
            {
                test: /\.css$/, use: extractCSS.extract(['css-loader?minimize'])
            },
            {
                test: /\.js?$/,
                use: {
                    loader: 'babel-loader', options: {
                        presets:
                            ['@babel/preset-react', '@babel/preset-env']
                    }
                }
            },
        ]
    }
};

in my file :

async function f12() {
    alert('13579-1122');
}
f12();

It does not work when I use the word async.
(I want the program to wait for the fetch command to complete when the fetch command is running. I was using async: false in ajax)

Body:
Have a function that just fetches the data, and call that function from an async function that awaits the response (JSON, presumably), parses it, and then you can do what you want with it.

A bit like this:

function getData(url) {
  return fetch(url);
}

async function main() {
  try {
    const response = await getData('https://example.com');
    const data = await response.json();
    console.log(data);
  } catch(err) {
    console.log(err);
  }
}

main();

Additional documentation

async/await

fetch


问:
What’s the meaning of `Duration: 30.18s, Total samples = 26.26s (87.00%)` in go pprof?
As my understanding, pprof stops and samples go program at every 10ms. So a 30s program should got 3000 samples, but what’s the meaning of the 26.26s? How can the samples count be shown as time duration?

What’s more, I even ever got such output shows that the sample time is bigger than wall time, how could it be such result?

Duration: 5.13s, Total samples = 5.57s (108.58%)

答:
That confusing wording was reported in google/pprof issue 128

The "Total samples" part is confusing.

Milliseconds are continuous, but samples are discrete — they're individual points, so how can you sum them up into a quantity of milliseconds?

The "sum" is the sum of a discrete number (a quantity of samples), not a continuous range (a time interval).

Reporting the sums makes perfect sense, but reporting discrete numbers using continuous units is just plain confusing.

Please update the formatting of the Duration line to give a clearer indication of what a quantity of samples reported in milliseconds actually means.

Raul Silvera's answer:

Each callstack in a profile is associated to a set of values. What is reported here is the sum of these values for all the callstacks in the profile, and is useful to understand the weight of individual frames over the full profile.

We're reporting the sum using the unit described in the profile.

Would you have a concrete suggestion for this example?

Maybe just a rewording would help, like:

```<code>Duration: 1.60s, Samples account for 14.50ms (0.9%)
</code>```

There are still pprof improvements discussed for pprof in golang/go issue 36821

pprof CPU profiles lack accuracy (closeness to the ground truth) and precision (repeatability across different runs).

The issue is with the use of OS timers used for sampling; OS timers are coarse-grained and have a high skid.

I will propose a design to extend CPU profiling by sampling CPU Performance Monitoring Unit (PMU) aka hardware performance counters

It includes examples where Total samples exceeds duration.

Dependence on the number of cores and length of test execution:

The results of goroutine.go test depend on the number of CPU cores available.

On a multi-core CPU, if you set GOMAXPROCS=1, goroutine.go will not show a huge variation, since each goroutine runs for several seconds.

However, if you set GOMAXPROCS to a larger value, say 4, you will notice a significant measurement attribution problem.

One reason for this problem is that the itimer samples on Linux are not guaranteed to be delivered to the thread whose timer expired.

Since Go 1.17 (and improved in Go 1.18), you can add pprof labels to know more:

A cool feature of Go's CPU profiler is that you can attach arbitrary key value pairs to a goroutine. These labels will be inherited by any goroutine spawned from that goroutine and show up in the resulting profile.

Let's consider the example below that does some CPU work() on behalf of a user.

By using the pprof.Labels() and pprof.Do() API, we can associate the user with the goroutine that is executing the work() function.

Additionally the labels are automatically inherited by any goroutine spawned within the same code block, for example the backgroundWork() goroutine.

func work(ctx context.Context, user string) {
  labels := pprof.Labels("user", user)
  pprof.Do(ctx, labels, func(_ context.Context) {
      go backgroundWork()
      directWork()
  })
}
```

How you use these labels is up to you.

You might include things such as user ids, request ids, http endpoints, subscription plan or other data that can allow you to get a better understanding of what types of requests are causing high CPU utilization, even when they are being processed by the same code paths.

That being said, using labels will increase the size of your pprof files. So you should probably start with low cardinality labels such as endpoints before moving on to high cardinality labels once you feel confident that they don't impact the performance of your application.

Body:
That confusing wording was reported in google/pprof issue 128

The "Total samples" part is confusing.

Milliseconds are continuous, but samples are discrete — they're individual points, so how can you sum them up into a quantity of milliseconds?

The "sum" is the sum of a discrete number (a quantity of samples), not a continuous range (a time interval).

Reporting the sums makes perfect sense, but reporting discrete numbers using continuous units is just plain confusing.

Please update the formatting of the Duration line to give a clearer indication of what a quantity of samples reported in milliseconds actually means.

Raul Silvera's answer:

Each callstack in a profile is associated to a set of values. What is reported here is the sum of these values for all the callstacks in the profile, and is useful to understand the weight of individual frames over the full profile.

We're reporting the sum using the unit described in the profile.

Would you have a concrete suggestion for this example?

Maybe just a rewording would help, like:

Duration: 1.60s, Samples account for 14.50ms (0.9%)

There are still pprof improvements discussed for pprof in golang/go issue 36821

pprof CPU profiles lack accuracy (closeness to the ground truth) and precision (repeatability across different runs).

The issue is with the use of OS timers used for sampling; OS timers are coarse-grained and have a high skid.

I will propose a design to extend CPU profiling by sampling CPU Performance Monitoring Unit (PMU) aka hardware performance counters

It includes examples where Total samples exceeds duration.

Dependence on the number of cores and length of test execution:

The results of goroutine.go test depend on the number of CPU cores available.

On a multi-core CPU, if you set GOMAXPROCS=1, goroutine.go will not show a huge variation, since each goroutine runs for several seconds.

However, if you set GOMAXPROCS to a larger value, say 4, you will notice a significant measurement attribution problem.

One reason for this problem is that the itimer samples on Linux are not guaranteed to be delivered to the thread whose timer expired.

Since Go 1.17 (and improved in Go 1.18), you can add pprof labels to know more:

A cool feature of Go's CPU profiler is that you can attach arbitrary key value pairs to a goroutine. These labels will be inherited by any goroutine spawned from that goroutine and show up in the resulting profile.

Let's consider the example below that does some CPU work() on behalf of a user.

By using the pprof.Labels() and pprof.Do() API, we can associate the user with the goroutine that is executing the work() function.

Additionally the labels are automatically inherited by any goroutine spawned within the same code block, for example the backgroundWork() goroutine.

func work(ctx context.Context, user string) {
  labels := pprof.Labels("user", user)
  pprof.Do(ctx, labels, func(_ context.Context) {
      go backgroundWork()
      directWork()
  })
}

How you use these labels is up to you.

You might include things such as user ids, request ids, http endpoints, subscription plan or other data that can allow you to get a better understanding of what types of requests are causing high CPU utilization, even when they are being processed by the same code paths.

That being said, using labels will increase the size of your pprof files. So you should probably start with low cardinality labels such as endpoints before moving on to high cardinality labels once you feel confident that they don't impact the performance of your application.


问:
passing command line arguments by reference to a function
I want to process command line parameters in seperate function but couldnt pass them. What is the right declaration and definition? And any resource about passing parameters, writing function definition/declaration?

I will use getopt() function in cmd_line() function.

```<code>...
...
void cmd_line(*int, *char[]);

int main(int argc, char *argv[]){
    cmd_line(&argc, argv);
    return 0;
}

void cmd_line(int *argc, char *argv[]){
...
...
}
</code>```

答:
Tried to find a duplicate, but did not find any in this context. To make it searchable, here is the relevant error:

```<code>main.c:1:15: error: expected declaration specifiers or ‘...’ before ‘*’ token
    1 | void cmd_line(*int, *char[]);
      |               ^
main.c:1:21: error: expected declaration specifiers or ‘...’ before ‘*’ token
    1 | void cmd_line(*int, *char[]);
      |
</code>```

The problem is that

```<code>void cmd_line(*int, *char[]);
</code>```

should be

```<code>void cmd_line(int*, char*[]);
</code>```

Body:
I want to process command line parameters in seperate function but couldnt pass them. What is the right declaration and definition? And any resource about passing parameters, writing function definition/declaration?

I will use getopt() function in cmd_line() function.

...
...
void cmd_line(*int, *char[]);

int main(int argc, char *argv[]){
    cmd_line(&argc, argv);
    return 0;
}

void cmd_line(int *argc, char *argv[]){
...
...
}

Body:
Tried to find a duplicate, but did not find any in this context. To make it searchable, here is the relevant error:

main.c:1:15: error: expected declaration specifiers or ‘...’ before ‘*’ token
    1 | void cmd_line(*int, *char[]);
      |               ^
main.c:1:21: error: expected declaration specifiers or ‘...’ before ‘*’ token
    1 | void cmd_line(*int, *char[]);
      |

The problem is that

void cmd_line(*int, *char[]);

should be

void cmd_line(int*, char*[]);


问:
How do I convert string to object type without using eval() in for loop?
class Testclass:

```<code>def change(self, obj):
    if(self.ball):
        self.ball=False
        obj.ball=True
</code>```

main():

```<code>A=Testclass()
B=Testclass()
seq=["AB", "BA", "AB"]
for val in seq:
    obj1, obj2=list(val)    #to split "AB" into A, B
    eval(obj1).change(eval(obj2))
</code>```

.change() method changes object's boolean value to the other object's value. Just for the test.

How can I avoid using eval in this loop? Without eval(), following error appears:
'str' object has no attribute 'change'

I'm using python 3.10

答:
One option would be to use tuples instead of strings:

```<code>A = Testclass()
B = Testclass()
seq=[(A, B), (B, A), (A, B)]
for val in seq:
    obj1, obj2=list(val)    #to split "AB" into A, B
    obj1.change(obj2)
</code>```

Or, combining the unpacking directly with the for loop:

```<code>A = Testclass()
B = Testclass()
seq=[(A, B), (B, A), (A, B)]
for obj1, obj2 in seq:
    obj1.change(obj2)
</code>```

Generally speaking, you'd only use strings if you need to write and read the data to and from a file (or a database or some other external system) or for display on the screen; while it's inside the program, keep things as objects (or numbers etc), don't convert back and forth.

Body:
class Testclass:

def change(self, obj):
    if(self.ball):
        self.ball=False
        obj.ball=True

main():

A=Testclass()
B=Testclass()
seq=["AB", "BA", "AB"]
for val in seq:
    obj1, obj2=list(val)    #to split "AB" into A, B
    eval(obj1).change(eval(obj2))

.change() method changes object's boolean value to the other object's value. Just for the test.

How can I avoid using eval in this loop? Without eval(), following error appears:
'str' object has no attribute 'change'

I'm using python 3.10

Body:
One option would be to use tuples instead of strings:

A = Testclass()
B = Testclass()
seq=[(A, B), (B, A), (A, B)]
for val in seq:
    obj1, obj2=list(val)    #to split "AB" into A, B
    obj1.change(obj2)

Or, combining the unpacking directly with the for loop:

A = Testclass()
B = Testclass()
seq=[(A, B), (B, A), (A, B)]
for obj1, obj2 in seq:
    obj1.change(obj2)

Generally speaking, you'd only use strings if you need to write and read the data to and from a file (or a database or some other external system) or for display on the screen; while it's inside the program, keep things as objects (or numbers etc), don't convert back and forth.


问:
Tcl: test for nested list
How can I efficiently test whether a Tcl list is nested (i.e. contains lists as elements)?

Based on https://wiki.tcl-lang.org/page/Depth+of+a+list I constructed the following proc:

```<code>proc isNestedList {l} {
    return [expr ![string equal $l [concat {*}$l]]]
}
</code>```

This gives the desired behavior (except for the case {A} which generally cannot be handled differently as far as I know, see https://stackoverflow.com/a/66799916/3852630):

% isNestedList A
0
% isNestedList {A}
0
% isNestedList {{A}}
1
% isNestedList {A B}
0
% isNestedList {{A B}}
1
% isNestedList {A {B C}}
1
```

However, for long lists which are not nested, isNestedList is slow, probably due to the conversion from list to string. I tried a different version where I compare $l and [concat {*}$l] by ::struct::list equal (https://tools.ietf.org/doc/tcllib/html/struct_list.html) to avoid this conversion, but that is even slower.

Thanks a lot for your help!

答:
To avoid the slowdown you mention, you need to stick to list operations, not string operations.  Here's one way:

```<code>proc isNestedList l {
    return [llength [lmap a $l {expr {[llength $a] > 1 ? 1 : [continue]}}]]
}
</code>```

This uses lmap to filter the list down to only those elements which can themselves be treated as a list of more than one element, then checks if the resulting list is non-empty.

Title: Tcl: test for nested list

Body:
How can I efficiently test whether a Tcl list is nested (i.e. contains lists as elements)?

Based on https://wiki.tcl-lang.org/page/Depth+of+a+list I constructed the following proc:

proc isNestedList {l} {
    return [expr ![string equal $l [concat {*}$l]]]
}

This gives the desired behavior (except for the case {A} which generally cannot be handled differently as far as I know, see https://stackoverflow.com/a/66799916/3852630):

% isNestedList A
0
% isNestedList {A}
0
% isNestedList {{A}}
1
% isNestedList {A B}
0
% isNestedList {{A B}}
1
% isNestedList {A {B C}}
1

However, for long lists which are not nested, isNestedList is slow, probably due to the conversion from list to string. I tried a different version where I compare $l and [concat {*}$l] by ::struct::list equal (https://tools.ietf.org/doc/tcllib/html/struct_list.html) to avoid this conversion, but that is even slower.

Thanks a lot for your help!

Body:
To avoid the slowdown you mention, you need to stick to list operations, not string operations.  Here's one way:

proc isNestedList l {
    return [llength [lmap a $l {expr {[llength $a] > 1 ? 1 : [continue]}}]]
}

This uses lmap to filter the list down to only those elements which can themselves be treated as a list of more than one element, then checks if the resulting list is non-empty.


问:
How to destructure objects with keys names that are numbers?
I have props that need to be destructured in a component. As it comes from API, it is actually an object from which I would like to take objects from 0 to 39. However, when I try to destructure them this way:

```<code> const { 0, ...39: weatherData } = this.props;
</code>```

VSCode gives me an error of unexpected token because of the comma. How can I destructure the props without having to enumerate every single object?

答:
I had a similar case where I couldn't easily avoid an object with numerical keys.

This was my solution, adapted to your situation:

const props = { 1:'first', 2:'second', /** imagine the keys continue*/ 39: 'thirty-ninth', 40: 'do not want after this', /** imagine the keys continue further*/};
const weatherProps = Object.entries(props).flatMap(([key, value]) => (parseInt(key, 10) <=39 ? [value] : []) );
```

Using flatMap is equivalent to a filter (reject keys over 39) followed by map (from an array to an integer) by (ab)using the fact that empty arrays are 'flattened' out of existence. You could have easily used reduce and accumulated only the values you wanted from each entry,  or Object.values(props).slice(0,39)  iff you can guarantee the right number of keys.

Body:
I have props that need to be destructured in a component. As it comes from API, it is actually an object from which I would like to take objects from 0 to 39. However, when I try to destructure them this way:

 const { 0, ...39: weatherData } = this.props;

VSCode gives me an error of unexpected token because of the comma. How can I destructure the props without having to enumerate every single object?

Body:
I had a similar case where I couldn't easily avoid an object with numerical keys.

This was my solution, adapted to your situation:

const props = { 1:'first', 2:'second', /** imagine the keys continue*/ 39: 'thirty-ninth', 40: 'do not want after this', /** imagine the keys continue further*/};
const weatherProps = Object.entries(props).flatMap(([key, value]) => (parseInt(key, 10) <=39 ? [value] : []) );

Using flatMap is equivalent to a filter (reject keys over 39) followed by map (from an array to an integer) by (ab)using the fact that empty arrays are 'flattened' out of existence. You could have easily used reduce and accumulated only the values you wanted from each entry,  or Object.values(props).slice(0,39)  iff you can guarantee the right number of keys.


问:
How to fetch data in json format from realtime-database (Firebase)?
I am trying to make a search functionality in my app which basically filter the json data (for eg. product list) according to the query of user(like any product name) and shows the nearest results. I have succesfully implemented this search bar and logic of filtering but it is working on the local json data of my product list I have in my app. What I want is to fetch the json data from Network call (http call) and then filter it .
But I have the data in my realtime-database and I do not know how to retrieve them as in json format. I could setup the cloud functions(node js) to return the json data to the client but I am not sure about what should be the logic in the cloud functions to connect it to realtime-database and return the response

My data in Firebase:

Now how can I fetch this data from my app through the cloud functions ?

答:
I am not sure about what should be the logic in the cloud functions to
connect it to realtime-database and return the response. .... how can
I fetch this data from my app through the cloud functions ?

I understand that you want to use an HTTPS Cloud Function as a REST API endpoint (You write "What I want is to fetch the json data from Network call (http call)").

You can write a Cloud Function along the following lines:

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.getRTDBData = functions.https.onRequest(async (req, res) => {

    const rtdbRootRef = admin.database().ref();

    const noticesDataSnapshot = await rtdbRootRef.child('notices').get();

    res.status(200).send(noticesDataSnapshot.val());

});
</code>```

When calling this HTTPS Cloud Function with an http call you will get the entire noticesRTDB node. If necessary, it's up to you to adapt the RTDB query, for example by filtering data, as explained in the doc.

In addition, I would suggest you watch this video for more info on how to deal with errors in your HTTPS Cloud Function.

Body:
I am not sure about what should be the logic in the cloud functions to
connect it to realtime-database and return the response. .... how can
I fetch this data from my app through the cloud functions ?

I understand that you want to use an HTTPS Cloud Function as a REST API endpoint (You write "What I want is to fetch the json data from Network call (http call)").

You can write a Cloud Function along the following lines:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.getRTDBData = functions.https.onRequest(async (req, res) => {

    const rtdbRootRef = admin.database().ref();

    const noticesDataSnapshot = await rtdbRootRef.child('notices').get();

    res.status(200).send(noticesDataSnapshot.val());

});

When calling this HTTPS Cloud Function with an http call you will get the entire noticesRTDB node. If necessary, it's up to you to adapt the RTDB query, for example by filtering data, as explained in the doc.

In addition, I would suggest you watch this video for more info on how to deal with errors in your HTTPS Cloud Function.


问:
Canceling the scrolling animation when keyboard pops up on iphone
I have a UIViewController that contains UITextField. I set the inputAccessory of the textfield to a UIToolbar that I create.
My ViewController's view is inside a UIScrollView (To handle the events of keyboard popping up)

Before:

Now, when the keyboard pops up, suddenly my ScrollView is setting it's contentOffset.y to 64 with animation, so part of my view is pushed above the top of the screen:

After:

This is done by the framework because I'm using a toolbar for inputAccessoryView.
If i'm dropping the toolbar there is no animation and no content offset.

Is anyone knows how can I disable this automatic animation and scrolling?

Thank you!

答: You can use a combination of boolean flags and your UIScrollViewDelegate to prevent the scrolling from taking place. Scroll view delegates can be used to detect when scrolling is taking place, modify the type of scrolling, and also simply prevent it from happening, so your best approach is probably to look into detecting when the keyboard goes up (via a notification or text field delegate, whichever is more appropriate) and using that in combination with your scroll view delegate.

ContentLicense: CC BY-SA 3.0


问:
Understanding npm packages inside github actions
Here is my idea: build a static web page template, over time add .md files to a /posts directory and build a CI job to convert the .md files to html (with the showdownjs/showdown package).
Is there a need to install the package on every push? Seems like a waste, but uploading /node-modules is incorrect as well. Is there a way to install the package once, and let github action just work with it (run the md to html converter on newly added files)?</p>

答:
You have 2 options:

Recommened: Use caching action to cache dependencies for your project - using a hash from package-lock.json as a key to make sure it rebuild when depenendencies has changed:

```<code>- name: Cache node modules
  uses: actions/cache@v2
  env:
     cache-name: cache-node-modules
     with:
     # npm cache files are stored in `~/.npm` on Linux/macOS
     path: ~/.npm
     key: ${{ hashFiles('**/package-lock.json') }}

- name: Install Dependencies
  run: npm install
</code>```

Push your node_modules to Git repository so it's checkout together with everything else

For optimising a need to run your converted you can use this action:

https://github.com/tj-actions/changed-files/
and detect if any files were modified at certain path

Body:
You have 2 options:

Recommened: Use caching action to cache dependencies for your project - using a hash from package-lock.json as a key to make sure it rebuild when depenendencies has changed:

- name: Cache node modules
  uses: actions/cache@v2
  env:
     cache-name: cache-node-modules
     with:
     # npm cache files are stored in `~/.npm` on Linux/macOS
     path: ~/.npm
     key: ${{ hashFiles('**/package-lock.json') }}

- name: Install Dependencies
  run: npm install

Push your node_modules to Git repository so it's checkout together with everything else

For optimising a need to run your converted you can use this action:

https://github.com/tj-actions/changed-files/
and detect if any files were modified at certain path


问:
Select first rank if RANK()+1 overflows with JOINS
I have a table called loop_msg with msg_id and content. I have a second table called loop_msg_status with channel and msg_id. This is used to post messages as round-robin in different channels, so I need to keep track of which msg_id has been posted last in each channel.

```<code>SELECT
  a.msg_id,
  b.content,
  b.rank,
  b.rank + 1,
  c.rank,
  c.content as next_content
FROM
  loop_msg_status as a
  LEFT JOIN (
    SELECT
      *,
      RANK() OVER (
        ORDER BY
          msg_id ASC
      ) as rank
    FROM
      loop_msg
  ) b ON a.msg_id = b.msg_id
  LEFT JOIN (
    SELECT
      *,
      RANK() OVER (
        ORDER BY
          msg_id ASC
      ) as rank
    FROM
      loop_msg
  ) c ON b.rank + 1 = c.rank
</code>```

With this query I'm able to get the current msg_id and its content from every channel. I'm also getting that msg_id's rank from table loop_msg. I also get its rank+1 and get rank+1's content, if that makes sense. And it works. However, if rank is the highest one, then rank+1 doesn't exist and I get a NULL next_content. I would like in that case to SELECT the lowest rank from loop_msg which is 1 and get its content as next_content instead. Should I add a IF() and if so, where? Or is there a better way to do this?

```<code>SELECT version();
> 10.5.13-MariaDB
</code>```

Full SQL example:

```<code>CREATE TABLE `loop_msg` (
  `msg_id` int(11) NOT NULL,
  `content` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `loop_msg` (`msg_id`, `content`) VALUES
(2, 'Content 2'),
(3, 'Content 3'),
(4, 'Content 4'),
(6, 'Content 6'),
(7, 'Content 7'),
(8, 'Content 8');

CREATE TABLE `loop_msg_status` (
  `channel` bigint(20) NOT NULL,
  `msg_id` int(11) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `loop_msg_status` (`channel`, `msg_id`) VALUES
(316757642527768577, 4),
(384071823261696010, 6),
(939746456632438804, 8);

ALTER TABLE `loop_msg`
  ADD PRIMARY KEY (`msg_id`);

ALTER TABLE `loop_msg_status`
  ADD PRIMARY KEY (`channel`);

ALTER TABLE `loop_msg`
  MODIFY `msg_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
COMMIT;
</code>```

Expected result

```<code>channel            | nextContent
--------------------------------
316757642527768577 | Content 6
384071823261696010 | Content 7
939746456632438804 | Content 2
</code>```

答:
Final SQL with the schema (and expected result) given in the question:

The final fiddle

WITH cte AS (
        SELECT loop_msg.msg_id
             , channel
             , COALESCE(
                           LEAD(content)        OVER w1
                         , FIRST_VALUE(content) OVER w1
                       ) AS content_next
          FROM      loop_msg
          LEFT JOIN loop_msg_status
            ON loop_msg.msg_id = loop_msg_status.msg_id
          WINDOW w1 AS (ORDER BY loop_msg.msg_id)
     )
SELECT channel, content_next
  FROM cte
 WHERE channel IS NOT NULL
;
```
<p>The result:</p>
<pre class="lang-none prettyprint-override"><code>+--------------------+--------------+
| channel            | content_next |
+--------------------+--------------+
| 316757642527768577 | Content 6    |
| 384071823261696010 | Content 7    |
| 939746456632438804 | Content 2    |
+--------------------+--------------+
</code>```

To also see the current and next msg_id, here's the adjusted SQL:

The adjusted fiddle

WITH cte AS (
        SELECT loop_msg.msg_id
             , channel
             , ROW_NUMBER() OVER w1 as rankx
             , COALESCE(
                           LEAD(loop_msg.msg_id)        OVER w1
                         , FIRST_VALUE(loop_msg.msg_id) OVER w1
                       ) AS msgid_next
             , COALESCE(
                           LEAD(content)        OVER w1
                         , FIRST_VALUE(content) OVER w1
                       ) AS content_next
          FROM      loop_msg
          LEFT JOIN loop_msg_status
            ON loop_msg.msg_id = loop_msg_status.msg_id
          WINDOW w1 AS (ORDER BY loop_msg.msg_id)
     )
SELECT channel, content_next, msg_id, msgid_next
  FROM cte
 WHERE channel IS NOT NULL
;
```
<p>The result:</p>
<pre class="lang-none prettyprint-override"><code>+--------------------+--------------+--------+------------+
| channel            | content_next | msg_id | msgid_next |
+--------------------+--------------+--------+------------+
| 316757642527768577 | Content 6    |      4 |          6 |
| 384071823261696010 | Content 7    |      6 |          7 |
| 939746456632438804 | Content 2    |      8 |          2 |
+--------------------+--------------+--------+------------+
</code>```

More detail:

You could try something like this.  In this case, we can use ROW_NUMBER instead of RANK, since msg_id is unique and no two messages will have the same msg_id which would have the same RANK.  Feel free to replace with RANK, if you wish.

The fiddle

Later, we can partition by channel to do this for each channel separately.  Your question wasn't entirely clear about how you wanted to use channel.

SELECT *
     , ROW_NUMBER() OVER (ORDER BY msg_id ASC) as rankx
     , COALESCE(
                   LEAD(msg_id)        OVER (ORDER BY msg_id ASC)
                 , FIRST_VALUE(msg_id) OVER (ORDER BY msg_id ASC)
               ) AS msgid_next
     , COALESCE(
                   LEAD(content)        OVER (ORDER BY msg_id ASC)
                 , FIRST_VALUE(content) OVER (ORDER BY msg_id ASC)
               ) AS content_next
  FROM loop_msg
;
```
<p>The result:</p>
<pre class="lang-none prettyprint-override"><code>+--------+---------+-------+------------+--------------+
| msg_id | content | rankx | msgid_next | content_next |
+--------+---------+-------+------------+--------------+
|      1 | c1      |     1 |          2 | c2           |
|      2 | c2      |     2 |          3 | c3           |
|      3 | c3      |     3 |          4 | c4           |
|      4 | c4      |     4 |          5 | c5           |
|      5 | c5      |     5 |          6 | c6           |
|      6 | c6      |     6 |          7 | c7           |
|      7 | c7      |     7 |          1 | c1           |
+--------+---------+-------+------------+--------------+
</code>```

The setup:

CREATE TABLE loop_msg (
     msg_id  int  auto_increment primary key
   , content varchar(20)
);

INSERT INTO loop_msg (content) VALUES
   ('c1'), ('c2'), ('c3'), ('c4'), ('c5'), ('c6'), ('c7')
;
```
<p><strong>Test cast #2, processing per channel:</strong></p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE loop_msg (
      msg_id  int  auto_increment primary key
    , chan    varchar(20)
    , content varchar(20)
);

INSERT INTO loop_msg (content, chan) VALUES
   ('c1', 'chan1')
 , ('c2', 'chan1')
 , ('c3', 'chan1')
 , ('c4', 'chan1')
 , ('c5', 'chan1')
 , ('c6', 'chan1')
 , ('c7', 'chan1')
 , ('d2', 'chan2')
 , ('d3', 'chan2')
 , ('d4', 'chan2')
 , ('d5', 'chan2')
 , ('d6', 'chan2')
 , ('d7', 'chan2')
 , ('d8', 'chan2')
;

SELECT *
     , ROW_NUMBER() OVER (PARTITION BY chan ORDER BY msg_id ASC) as rankx
     , COALESCE(
                   LEAD(msg_id)        OVER (PARTITION BY chan ORDER BY msg_id)
                 , FIRST_VALUE(msg_id) OVER (PARTITION BY chan ORDER BY msg_id)
               ) AS msgid_next
     , COALESCE(
                   LEAD(content)        OVER (PARTITION BY chan ORDER BY msg_id)
                 , FIRST_VALUE(content) OVER (PARTITION BY chan ORDER BY msg_id)
               ) AS content_next
  FROM loop_msg
;
</code>```

The result:

+--------+-------+---------+-------+------------+--------------+
| msg_id | chan  | content | rankx | msgid_next | content_next |
+--------+-------+---------+-------+------------+--------------+
|      1 | chan1 | c1      |     1 |          2 | c2           |
|      2 | chan1 | c2      |     2 |          3 | c3           |
|      3 | chan1 | c3      |     3 |          4 | c4           |
|      4 | chan1 | c4      |     4 |          5 | c5           |
|      5 | chan1 | c5      |     5 |          6 | c6           |
|      6 | chan1 | c6      |     6 |          7 | c7           |
|      7 | chan1 | c7      |     7 |          1 | c1           |
|      8 | chan2 | d2      |     1 |          9 | d3           |
|      9 | chan2 | d3      |     2 |         10 | d4           |
|     10 | chan2 | d4      |     3 |         11 | d5           |
|     11 | chan2 | d5      |     4 |         12 | d6           |
|     12 | chan2 | d6      |     5 |         13 | d7           |
|     13 | chan2 | d7      |     6 |         14 | d8           |
|     14 | chan2 | d8      |     7 |          8 | d2           |
+--------+-------+---------+-------+------------+--------------+
```
<p><strong>Finally:</strong></p>
<p>We can also define a window clause to avoid rewriting the specification each time:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT *
     , ROW_NUMBER() OVER w1 as rankx
     , COALESCE(
                   LEAD(msg_id)        OVER w1
                 , FIRST_VALUE(msg_id) OVER w1
               ) AS msgid_next
     , COALESCE(
                   LEAD(content)        OVER w1
                 , FIRST_VALUE(content) OVER w1
               ) AS content_next
  FROM loop_msg
  WINDOW w1 AS (PARTITION BY chan ORDER BY msg_id)
;
</code>```

Result:

+--------+-------+---------+-------+------------+--------------+
| msg_id | chan  | content | rankx | msgid_next | content_next |
+--------+-------+---------+-------+------------+--------------+
|      1 | chan1 | c1      |     1 |          2 | c2           |
|      2 | chan1 | c2      |     2 |          3 | c3           |
|      3 | chan1 | c3      |     3 |          4 | c4           |
|      4 | chan1 | c4      |     4 |          5 | c5           |
|      5 | chan1 | c5      |     5 |          6 | c6           |
|      6 | chan1 | c6      |     6 |          7 | c7           |
|      7 | chan1 | c7      |     7 |          1 | c1           |
|      8 | chan2 | d2      |     1 |          9 | d3           |
|      9 | chan2 | d3      |     2 |         10 | d4           |
|     10 | chan2 | d4      |     3 |         11 | d5           |
|     11 | chan2 | d5      |     4 |         12 | d6           |
|     12 | chan2 | d6      |     5 |         13 | d7           |
|     13 | chan2 | d7      |     6 |         14 | d8           |
|     14 | chan2 | d8      |     7 |          8 | d2           |
+--------+-------+---------+-------+------------+--------------+
```

Body:
I have a table called loop_msg with msg_id and content. I have a second table called loop_msg_status with channel and msg_id. This is used to post messages as round-robin in different channels, so I need to keep track of which msg_id has been posted last in each channel.

SELECT
  a.msg_id,
  b.content,
  b.rank,
  b.rank + 1,
  c.rank,
  c.content as next_content
FROM
  loop_msg_status as a
  LEFT JOIN (
    SELECT
      *,
      RANK() OVER (
        ORDER BY
          msg_id ASC
      ) as rank
    FROM
      loop_msg
  ) b ON a.msg_id = b.msg_id
  LEFT JOIN (
    SELECT
      *,
      RANK() OVER (
        ORDER BY
          msg_id ASC
      ) as rank
    FROM
      loop_msg
  ) c ON b.rank + 1 = c.rank

With this query I'm able to get the current msg_id and its content from every channel. I'm also getting that msg_id's rank from table loop_msg. I also get its rank+1 and get rank+1's content, if that makes sense. And it works. However, if rank is the highest one, then rank+1 doesn't exist and I get a NULL next_content. I would like in that case to SELECT the lowest rank from loop_msg which is 1 and get its content as next_content instead. Should I add a IF() and if so, where? Or is there a better way to do this?

SELECT version();
> 10.5.13-MariaDB

Full SQL example:

CREATE TABLE `loop_msg` (
  `msg_id` int(11) NOT NULL,
  `content` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `loop_msg` (`msg_id`, `content`) VALUES
(2, 'Content 2'),
(3, 'Content 3'),
(4, 'Content 4'),
(6, 'Content 6'),
(7, 'Content 7'),
(8, 'Content 8');

CREATE TABLE `loop_msg_status` (
  `channel` bigint(20) NOT NULL,
  `msg_id` int(11) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `loop_msg_status` (`channel`, `msg_id`) VALUES
(316757642527768577, 4),
(384071823261696010, 6),
(939746456632438804, 8);

ALTER TABLE `loop_msg`
  ADD PRIMARY KEY (`msg_id`);

ALTER TABLE `loop_msg_status`
  ADD PRIMARY KEY (`channel`);

ALTER TABLE `loop_msg`
  MODIFY `msg_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
COMMIT;

Expected result

channel            | nextContent
--------------------------------
316757642527768577 | Content 6
384071823261696010 | Content 7
939746456632438804 | Content 2

Body:
Final SQL with the schema (and expected result) given in the question:

The final fiddle

WITH cte AS (
        SELECT loop_msg.msg_id
             , channel
             , COALESCE(
                           LEAD(content)        OVER w1
                         , FIRST_VALUE(content) OVER w1
                       ) AS content_next
          FROM      loop_msg
          LEFT JOIN loop_msg_status
            ON loop_msg.msg_id = loop_msg_status.msg_id
          WINDOW w1 AS (ORDER BY loop_msg.msg_id)
     )
SELECT channel, content_next
  FROM cte
 WHERE channel IS NOT NULL
;

The result:

+--------------------+--------------+
| channel            | content_next |
+--------------------+--------------+
| 316757642527768577 | Content 6    |
| 384071823261696010 | Content 7    |
| 939746456632438804 | Content 2    |
+--------------------+--------------+

To also see the current and next msg_id, here's the adjusted SQL:

The adjusted fiddle

WITH cte AS (
        SELECT loop_msg.msg_id
             , channel
             , ROW_NUMBER() OVER w1 as rankx
             , COALESCE(
                           LEAD(loop_msg.msg_id)        OVER w1
                         , FIRST_VALUE(loop_msg.msg_id) OVER w1
                       ) AS msgid_next
             , COALESCE(
                           LEAD(content)        OVER w1
                         , FIRST_VALUE(content) OVER w1
                       ) AS content_next
          FROM      loop_msg
          LEFT JOIN loop_msg_status
            ON loop_msg.msg_id = loop_msg_status.msg_id
          WINDOW w1 AS (ORDER BY loop_msg.msg_id)
     )
SELECT channel, content_next, msg_id, msgid_next
  FROM cte
 WHERE channel IS NOT NULL
;

The result:

+--------------------+--------------+--------+------------+
| channel            | content_next | msg_id | msgid_next |
+--------------------+--------------+--------+------------+
| 316757642527768577 | Content 6    |      4 |          6 |
| 384071823261696010 | Content 7    |      6 |          7 |
| 939746456632438804 | Content 2    |      8 |          2 |
+--------------------+--------------+--------+------------+

More detail:

You could try something like this.  In this case, we can use ROW_NUMBER instead of RANK, since msg_id is unique and no two messages will have the same msg_id which would have the same RANK.  Feel free to replace with RANK, if you wish.

The fiddle

Later, we can partition by channel to do this for each channel separately.  Your question wasn't entirely clear about how you wanted to use channel.

SELECT *
     , ROW_NUMBER() OVER (ORDER BY msg_id ASC) as rankx
     , COALESCE(
                   LEAD(msg_id)        OVER (ORDER BY msg_id ASC)
                 , FIRST_VALUE(msg_id) OVER (ORDER BY msg_id ASC)
               ) AS msgid_next
     , COALESCE(
                   LEAD(content)        OVER (ORDER BY msg_id ASC)
                 , FIRST_VALUE(content) OVER (ORDER BY msg_id ASC)
               ) AS content_next
  FROM loop_msg
;

The result:

+--------+---------+-------+------------+--------------+
| msg_id | content | rankx | msgid_next | content_next |
+--------+---------+-------+------------+--------------+
|      1 | c1      |     1 |          2 | c2           |
|      2 | c2      |     2 |          3 | c3           |
|      3 | c3      |     3 |          4 | c4           |
|      4 | c4      |     4 |          5 | c5           |
|      5 | c5      |     5 |          6 | c6           |
|      6 | c6      |     6 |          7 | c7           |
|      7 | c7      |     7 |          1 | c1           |
+--------+---------+-------+------------+--------------+

The setup:

CREATE TABLE loop_msg (
     msg_id  int  auto_increment primary key
   , content varchar(20)
);

INSERT INTO loop_msg (content) VALUES
   ('c1'), ('c2'), ('c3'), ('c4'), ('c5'), ('c6'), ('c7')
;

Test cast #2, processing per channel:

CREATE TABLE loop_msg (
      msg_id  int  auto_increment primary key
    , chan    varchar(20)
    , content varchar(20)
);

INSERT INTO loop_msg (content, chan) VALUES
   ('c1', 'chan1')
 , ('c2', 'chan1')
 , ('c3', 'chan1')
 , ('c4', 'chan1')
 , ('c5', 'chan1')
 , ('c6', 'chan1')
 , ('c7', 'chan1')
 , ('d2', 'chan2')
 , ('d3', 'chan2')
 , ('d4', 'chan2')
 , ('d5', 'chan2')
 , ('d6', 'chan2')
 , ('d7', 'chan2')
 , ('d8', 'chan2')
;

SELECT *
     , ROW_NUMBER() OVER (PARTITION BY chan ORDER BY msg_id ASC) as rankx
     , COALESCE(
                   LEAD(msg_id)        OVER (PARTITION BY chan ORDER BY msg_id)
                 , FIRST_VALUE(msg_id) OVER (PARTITION BY chan ORDER BY msg_id)
               ) AS msgid_next
     , COALESCE(
                   LEAD(content)        OVER (PARTITION BY chan ORDER BY msg_id)
                 , FIRST_VALUE(content) OVER (PARTITION BY chan ORDER BY msg_id)
               ) AS content_next
  FROM loop_msg
;

The result:

+--------+-------+---------+-------+------------+--------------+
| msg_id | chan  | content | rankx | msgid_next | content_next |
+--------+-------+---------+-------+------------+--------------+
|      1 | chan1 | c1      |     1 |          2 | c2           |
|      2 | chan1 | c2      |     2 |          3 | c3           |
|      3 | chan1 | c3      |     3 |          4 | c4           |
|      4 | chan1 | c4      |     4 |          5 | c5           |
|      5 | chan1 | c5      |     5 |          6 | c6           |
|      6 | chan1 | c6      |     6 |          7 | c7           |
|      7 | chan1 | c7      |     7 |          1 | c1           |
|      8 | chan2 | d2      |     1 |          9 | d3           |
|      9 | chan2 | d3      |     2 |         10 | d4           |
|     10 | chan2 | d4      |     3 |         11 | d5           |
|     11 | chan2 | d5      |     4 |         12 | d6           |
|     12 | chan2 | d6      |     5 |         13 | d7           |
|     13 | chan2 | d7      |     6 |         14 | d8           |
|     14 | chan2 | d8      |     7 |          8 | d2           |
+--------+-------+---------+-------+------------+--------------+

Finally:

We can also define a window clause to avoid rewriting the specification each time:

SELECT *
     , ROW_NUMBER() OVER w1 as rankx
     , COALESCE(
                   LEAD(msg_id)        OVER w1
                 , FIRST_VALUE(msg_id) OVER w1
               ) AS msgid_next
     , COALESCE(
                   LEAD(content)        OVER w1
                 , FIRST_VALUE(content) OVER w1
               ) AS content_next
  FROM loop_msg
  WINDOW w1 AS (PARTITION BY chan ORDER BY msg_id)
;

Result:

+--------+-------+---------+-------+------------+--------------+
| msg_id | chan  | content | rankx | msgid_next | content_next |
+--------+-------+---------+-------+------------+--------------+
|      1 | chan1 | c1      |     1 |          2 | c2           |
|      2 | chan1 | c2      |     2 |          3 | c3           |
|      3 | chan1 | c3      |     3 |          4 | c4           |
|      4 | chan1 | c4      |     4 |          5 | c5           |
|      5 | chan1 | c5      |     5 |          6 | c6           |
|      6 | chan1 | c6      |     6 |          7 | c7           |
|      7 | chan1 | c7      |     7 |          1 | c1           |
|      8 | chan2 | d2      |     1 |          9 | d3           |
|      9 | chan2 | d3      |     2 |         10 | d4           |
|     10 | chan2 | d4      |     3 |         11 | d5           |
|     11 | chan2 | d5      |     4 |         12 | d6           |
|     12 | chan2 | d6      |     5 |         13 | d7           |
|     13 | chan2 | d7      |     6 |         14 | d8           |
|     14 | chan2 | d8      |     7 |          8 | d2           |
+--------+-------+---------+-------+------------+--------------+


问:
Mocking @pnp/logging in Jest
I'm working in a Spfx project.

I have my own Logger class which is a wrapper around the @pnp/logging/Logger.

```<code>import * as pnpLogging from '@pnp/logging';
export class Logger {
    public static debug(message: string, notify = false, caller: string = null): void {
        pnpLogging.Logger.log( ... )
    }
</code>```

This logger is then used in various other classes, components and hooks.

```<code>import { Logger } from "./logging";
Logger.debug('some debug message);
</code>```

When creating tests for one of those other classes, jest throws a non-supported exception when importing the @pnp/logging.

I was able to overcome this issue with office-ui-fabric-react by using their commonjs libraries.

```<code>"office-ui-fabric-react/lib/(.*)$": "office-ui-fabric-react/lib-commonjs/$1",
</code>```

However, I don't see this option with @pnp/logging.

I also tried to mock it but without success.

```<code>import { nameof } from './utils';
const mockedPnpLogger = { error: (message) => { } };
jest.mock('@pnp/logging', () => ({
  ...jest.requireActual('@pnp/logging') as any,
  Logger: mockedPnpLogger
}));
describe('utils', () => { ... }
</code>```

But that's still throwing an error of export

```<code>SyntaxError: Unexpected token 'export'

  3 | const mockedPnpLogger = { error: (message) => { } };
  4 | jest.mock('@pnp/logging', () => ({
> 5 |     ...jest.requireActual('@pnp/logging') as any,
    |             ^
  6 |     Logger: mockedPnpLogger
  7 | }));
  8 |
</code>```

I'm a little lost now with options. Anyone has some insight or can help me in the right direction?

The full error message

```<code>Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

Details:

C:\Development\Projects\Skan\Applications\FuhrPark\src\client\node_modules\@pnp\logging\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export * from "./logger.js";
                                                                                ^^^^^^

SyntaxError: Unexpected token 'export'

> 1 | import * as pnpLogging from '@pnp/logging';
</code>```

Jest Configuration

```<code>"jest": {
    "moduleFileExtensions": [
        "ts",
        "tsx",
        "js"
    ],
    "moduleDirectories": [
        "node_modules"
    ],
    "moduleNameMapper": {
        "\\.(css|less|scss|sass)$": "identity-obj-proxy",
        "office-ui-fabric-react/lib/(.*)$": "office-ui-fabric-react/lib-commonjs/$1",
        "^@fuhrpark/(.*)": "<rootDir>/src/webparts/fuhrpark/$1",
        "^@shared/(.*)": "<rootDir>/src/shared/$1"
    },
    "transform": {
        "^.+\\.(ts|tsx)$": "ts-jest"
    },
    "transformIgnorePatterns": [
        "node_modules/(?!office-ui-fabric-react)"
    ],
    "testMatch": [
        "**/src/**/*.tests.+(ts|tsx)"
    ],
    "setupFiles": [
        "<rootDir>/src/webparts/fuhrpark/tests/tests-setup.ts"
    ],
    "testEnvironment": "node",
    "collectCoverage": true,
    "coverageReporters": [
        "json",
        "lcov",
        "text",
        "cobertura"
    ],
    "coverageDirectory": "<rootDir>/test-results",
    "reporters": [
        "default",
        "jest-junit"
    ],
    "coverageThreshold": {
        "global": {
            "branches": 0,
            "functions": 0,
            "lines": 0,
            "statements": 0
        }
    }
},
"jest-junit": {
    "output": "./test-results/summary-jest-junit.xml"
}
</code>```

TypeScript config

```<code>{
  "extends": "./node_modules/@microsoft/rush-stack-compiler-4.2/includes/tsconfig-web.json",
  "compilerOptions": {
    "target": "es5",
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "jsx": "react",
    "declaration": true,
    "sourceMap": true,
    "experimentalDecorators": true,
    "skipLibCheck": true,
    "outDir": "lib",
    "inlineSources": false,
    "strictNullChecks": false,
    "noUnusedLocals": false,
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "typeRoots": [
      "./node_modules/@types",
      "./node_modules/@microsoft"
    ],
    "types": [
      "webpack-env",
      "jest",
      "node"
    ],
    "lib": [
      "es6",
      "dom",
      "es2015.collection",
      "es2015.promise"
    ],
    "baseUrl": "src",
    "paths": {
      "@fuhrpark/*": [
        "webparts/fuhrpark/*"
      ],
      "@shared/*": [
        "shared/*"
      ]
    }
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx"
  ]
}
</code>```

答:
I wrapped the get method on the web object in a function and finally I got it right by creating the mock below. My wrapper is using a .then pattern which is the reason for the double promise resolve in the mock.

IMPORTANT the mock can't be inside a it/test or describe, it must be on the top level as also stated in the docs

I also mocked the sp.setup function in the same mock as that was throwing an error otherwise. Accordingly - you need to set up a double as per my finding. I have tried ts-sinon/ts-mockito etc but nothing took me all the way.

jest.mock('@pnp/sp', () => {
    return {
        __esModule: true,
        sp: {
            setup: jest.fn(),
            web: {
                get: () => Promise.resolve(Promise.resolve({ Title: 'Contoso Web Title' }))
            }
        }
    };
});
```
<p>edit: adding an example including a "select" - this also has to be mocked/stubbed</p>
<pre class="lang-js prettyprint-override"><code>jest.mock('@pnp/sp', () => {
    return {
        __esModule: true,
        sp: {
            setup: jest.fn(),
            web: {
                select: () => {
                    return {
                        get: () => Promise.resolve(Promise.resolve({ Title: 'Contoso Web Title' }))
                    };
                }
            }
        }
    };
});
</code>```

Title: Mocking @pnp/logging in Jest

Body:
I'm working in a Spfx project.

I have my own Logger class which is a wrapper around the @pnp/logging/Logger.

import * as pnpLogging from '@pnp/logging';
export class Logger {
    public static debug(message: string, notify = false, caller: string = null): void {
        pnpLogging.Logger.log( ... )
    }

This logger is then used in various other classes, components and hooks.

import { Logger } from "./logging";
Logger.debug('some debug message);

When creating tests for one of those other classes, jest throws a non-supported exception when importing the @pnp/logging.

I was able to overcome this issue with office-ui-fabric-react by using their commonjs libraries.

"office-ui-fabric-react/lib/(.*)$": "office-ui-fabric-react/lib-commonjs/$1",

However, I don't see this option with @pnp/logging.

I also tried to mock it but without success.

import { nameof } from './utils';
const mockedPnpLogger = { error: (message) => { } };
jest.mock('@pnp/logging', () => ({
  ...jest.requireActual('@pnp/logging') as any,
  Logger: mockedPnpLogger
}));
describe('utils', () => { ... }

But that's still throwing an error of export

SyntaxError: Unexpected token 'export'

  3 | const mockedPnpLogger = { error: (message) => { } };
  4 | jest.mock('@pnp/logging', () => ({
> 5 |     ...jest.requireActual('@pnp/logging') as any,
    |             ^
  6 |     Logger: mockedPnpLogger
  7 | }));
  8 |

I'm a little lost now with options. Anyone has some insight or can help me in the right direction?

The full error message

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

Details:

C:\Development\Projects\Skan\Applications\FuhrPark\src\client\node_modules\@pnp\logging\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export * from "./logger.js";
                                                                                ^^^^^^

SyntaxError: Unexpected token 'export'

> 1 | import * as pnpLogging from '@pnp/logging';

Jest Configuration

"jest": {
    "moduleFileExtensions": [
        "ts",
        "tsx",
        "js"
    ],
    "moduleDirectories": [
        "node_modules"
    ],
    "moduleNameMapper": {
        "\\.(css|less|scss|sass)$": "identity-obj-proxy",
        "office-ui-fabric-react/lib/(.*)$": "office-ui-fabric-react/lib-commonjs/$1",
        "^@fuhrpark/(.*)": "<rootDir>/src/webparts/fuhrpark/$1",
        "^@shared/(.*)": "<rootDir>/src/shared/$1"
    },
    "transform": {
        "^.+\\.(ts|tsx)$": "ts-jest"
    },
    "transformIgnorePatterns": [
        "node_modules/(?!office-ui-fabric-react)"
    ],
    "testMatch": [
        "**/src/**/*.tests.+(ts|tsx)"
    ],
    "setupFiles": [
        "<rootDir>/src/webparts/fuhrpark/tests/tests-setup.ts"
    ],
    "testEnvironment": "node",
    "collectCoverage": true,
    "coverageReporters": [
        "json",
        "lcov",
        "text",
        "cobertura"
    ],
    "coverageDirectory": "<rootDir>/test-results",
    "reporters": [
        "default",
        "jest-junit"
    ],
    "coverageThreshold": {
        "global": {
            "branches": 0,
            "functions": 0,
            "lines": 0,
            "statements": 0
        }
    }
},
"jest-junit": {
    "output": "./test-results/summary-jest-junit.xml"
}

TypeScript config

{
  "extends": "./node_modules/@microsoft/rush-stack-compiler-4.2/includes/tsconfig-web.json",
  "compilerOptions": {
    "target": "es5",
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "jsx": "react",
    "declaration": true,
    "sourceMap": true,
    "experimentalDecorators": true,
    "skipLibCheck": true,
    "outDir": "lib",
    "inlineSources": false,
    "strictNullChecks": false,
    "noUnusedLocals": false,
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "typeRoots": [
      "./node_modules/@types",
      "./node_modules/@microsoft"
    ],
    "types": [
      "webpack-env",
      "jest",
      "node"
    ],
    "lib": [
      "es6",
      "dom",
      "es2015.collection",
      "es2015.promise"
    ],
    "baseUrl": "src",
    "paths": {
      "@fuhrpark/*": [
        "webparts/fuhrpark/*"
      ],
      "@shared/*": [
        "shared/*"
      ]
    }
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx"
  ]
}

Body:
I wrapped the get method on the web object in a function and finally I got it right by creating the mock below. My wrapper is using a .then pattern which is the reason for the double promise resolve in the mock.

IMPORTANT the mock can't be inside a it/test or describe, it must be on the top level as also stated in the docs

I also mocked the sp.setup function in the same mock as that was throwing an error otherwise. Accordingly - you need to set up a double as per my finding. I have tried ts-sinon/ts-mockito etc but nothing took me all the way.

jest.mock('@pnp/sp', () => {
    return {
        __esModule: true,
        sp: {
            setup: jest.fn(),
            web: {
                get: () => Promise.resolve(Promise.resolve({ Title: 'Contoso Web Title' }))
            }
        }
    };
});

edit: adding an example including a "select" - this also has to be mocked/stubbed

jest.mock('@pnp/sp', () => {
    return {
        __esModule: true,
        sp: {
            setup: jest.fn(),
            web: {
                select: () => {
                    return {
                        get: () => Promise.resolve(Promise.resolve({ Title: 'Contoso Web Title' }))
                    };
                }
            }
        }
    };
});


问:
Export dynamically generated webbrowser control content to excel
I have a windows application in which an html report is displayed using the webbrowser control. The content of webbrrowser control is generated dynamically and provided as below

```<code> webbrowser1.DocumentText=htmlString;
</code>```

Now I want to export the webbrowser control content to excel on clicking the "Export to Excel button".

答:
First thing you can do is to create an excel template. Than you can open this template edit it and save it to a different location . This sample snippet can help you.

```<code>        using System;
        using Excel = Microsoft.Office.Interop.Excel;

        class Program
        {
            static void Main(string[] args)
            {
                var excelApplication = new Excel.Application { Visible = false, DisplayAlerts = false };
                Excel.Workbook excelWorkBook = excelApplication.Workbooks.Open(Filename: @"C:\temp\YourTemplate.xlsx");
                Excel.Worksheet targetedExcelSheet = (Excel.Worksheet)excelApplication.ActiveWorkbook.Sheets[1];
                Excel.Range ATrialRange = targetedExcelSheet.Range["F4", Type.Missing];
                ATrialRange.Value2 = "The values that you have parsed from your html string";
                excelWorkBook.SaveAs(Filename: @"C:\temp\YourNewlyGenerated.xlsx");
                excelWorkBook.Close();
                excelApplication.Quit();
            }
        }
</code>```

You can use html agility pack to parse your html.

Body:
I have a windows application in which an html report is displayed using the webbrowser control. The content of webbrrowser control is generated dynamically and provided as below

 webbrowser1.DocumentText=htmlString;

Now I want to export the webbrowser control content to excel on clicking the "Export to Excel button".

Body:
First thing you can do is to create an excel template. Than you can open this template edit it and save it to a different location . This sample snippet can help you.

        using System;
        using Excel = Microsoft.Office.Interop.Excel;

        class Program
        {
            static void Main(string[] args)
            {
                var excelApplication = new Excel.Application { Visible = false, DisplayAlerts = false };
                Excel.Workbook excelWorkBook = excelApplication.Workbooks.Open(Filename: @"C:\temp\YourTemplate.xlsx");
                Excel.Worksheet targetedExcelSheet = (Excel.Worksheet)excelApplication.ActiveWorkbook.Sheets[1];
                Excel.Range ATrialRange = targetedExcelSheet.Range["F4", Type.Missing];
                ATrialRange.Value2 = "The values that you have parsed from your html string";
                excelWorkBook.SaveAs(Filename: @"C:\temp\YourNewlyGenerated.xlsx");
                excelWorkBook.Close();
                excelApplication.Quit();
            }
        }

You can use html agility pack to parse your html.


问:
How do I find hostname in AWS?
I recently opened a database instance on AWS using RDS. I can't find the IP or hostname to the database. Can somebody help? I'm using MariaDB version 10.5.13. If anymore info is needed, just tell me. I'm new to this so I'm not exactly sure whats needed.</p>

答:
There is no specific IP adress shown to user in AWS Console, but you can find the hostname and FQDN of the DB under connectivity and security tab of the RDS Database.

Reference : https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ConnectToInstance.html

Title: How do I find hostname in AWS?


问:
Vue how to search all properties of array
In my vue-app I want to add a search component, so that I can search for different topics.

here is an example of the data:

```<code>persons: [
   {
    name: 'Mr.X',
    gender: 'Male',
    location: {
      address: 'some streetname',
      zipcode: '12345',
      city: 'Berlin',
      lng: 'longitude',
      lat: 'latitude',
    },
    skills: [
     { label: 'foo' },
     { label: 'bar' },
    ],
  },
 ...etc
]
</code>```

Then in my component I use a computed value:

```<code>computed: {
   filteredList() {
     return this.persons.filter((person) => {
       return person.name.toLowerCase().includes(this.search.toLowerCase())
     })
   },
}
</code>```

the HTML is:

```<code><input type="text" v-model="search" />

<div v-for="(person, index) in filteredList" :key="index">
    <p>{{ person.name }}</p>
</div>
</code>```

This of course only searches and returns the name. How can I search on all properties? For example If I search for "Berlin" it should also return the object data.

答:
If I understand your requirement correctly, you want to filter out with all the nested properties you have in the object with the search keyword.

Working Demo :

var vm = new Vue({
  el: '#vue-instance',
  data: {
    persons: [
       {
        name: 'Mr.X',
        gender: 'Male',
        location: {
          address: 'some streetname',
          zipcode: '12345',
          city: 'Berlin',
          lng: 'longitude',
          lat: 'latitude',
        }
      }, {
        name: 'Mrs.Y',
        gender: 'Female',
        location: {
          address: 'address 2',
          zipcode: '12345',
          city: 'alpha',
          lng: 'longitude',
          lat: 'latitude',
        }
      }
    ],
    search: ''
  },
  computed: {
    filteredList() {
       return this.persons.filter((person) => {
        const computedObj = { ...person,
            address: person.location.address,
            zipcode: person.location.zipcode,
            city: person.location.city,
            lng: person.location.lng,
            lat: person.location.lat
        }
         return Object.keys(computedObj)
              .some(key => ('' + computedObj[key]).toLowerCase().includes(this.search.toLowerCase()))
       })
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="vue-instance">
  <input type="text" v-model="search" />

  <div v-for="person in filteredList" :key="person.name">
      <p>{{ person.name }}</p>
  </div>
</div></code>```

Body:
In my vue-app I want to add a search component, so that I can search for different topics.

here is an example of the data:

persons: [
   {
    name: 'Mr.X',
    gender: 'Male',
    location: {
      address: 'some streetname',
      zipcode: '12345',
      city: 'Berlin',
      lng: 'longitude',
      lat: 'latitude',
    },
    skills: [
     { label: 'foo' },
     { label: 'bar' },
    ],
  },
 ...etc
]

Then in my component I use a computed value:

computed: {
   filteredList() {
     return this.persons.filter((person) => {
       return person.name.toLowerCase().includes(this.search.toLowerCase())
     })
   },
}

the HTML is:

<input type="text" v-model="search" />

{{ person.name }}

This of course only searches and returns the name. How can I search on all properties? For example If I search for "Berlin" it should also return the object data.

Body:
If I understand your requirement correctly, you want to filter out with all the nested properties you have in the object with the search keyword.

Working Demo :

var vm = new Vue({
  el: '#vue-instance',
  data: {
    persons: [
       {
        name: 'Mr.X',
        gender: 'Male',
        location: {
          address: 'some streetname',
          zipcode: '12345',
          city: 'Berlin',
          lng: 'longitude',
          lat: 'latitude',
        }
      }, {
        name: 'Mrs.Y',
        gender: 'Female',
        location: {
          address: 'address 2',
          zipcode: '12345',
          city: 'alpha',
          lng: 'longitude',
          lat: 'latitude',
        }
      }
    ],
    search: ''
  },
  computed: {
    filteredList() {
       return this.persons.filter((person) => {
        const computedObj = { ...person,
            address: person.location.address,
            zipcode: person.location.zipcode,
            city: person.location.city,
            lng: person.location.lng,
            lat: person.location.lat
        }
         return Object.keys(computedObj)
              .some(key => ('' + computedObj[key]).toLowerCase().includes(this.search.toLowerCase()))
       })
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="vue-instance">
  <input type="text" v-model="search" />

  <div v-for="person in filteredList" :key="person.name">
      <p>{{ person.name }}</p>
  </div>
</div>


问:
Creating your own header file in C
Can anyone explain how to create a header file in C with a simple example from beginning to end.</p>

答:
```<code>#ifndef MY_HEADER_H
# define MY_HEADER_H

//put your function headers here

#endif
</code>```

MY_HEADER_H serves as a double-inclusion guard.

For the function declaration, you only need to define the signature, that is, without parameter names, like this:

```<code>int foo(char*);
</code>```

If you really want to, you can also include the parameter's identifier, but it's not necessary because the identifier would only be used in a function's body (implementation), which in case of a header (parameter signature), it's missing.

This declares the function foo which accepts a char* and returns an int.

In your source file, you would have:

```<code>#include "my_header.h"

int foo(char* name) {
   //do stuff
   return 0;
}
</code>```

Title: Creating your own header file in C

Body:
#ifndef MY_HEADER_H
# define MY_HEADER_H

//put your function headers here

#endif

MY_HEADER_H serves as a double-inclusion guard.

For the function declaration, you only need to define the signature, that is, without parameter names, like this:

int foo(char*);

If you really want to, you can also include the parameter's identifier, but it's not necessary because the identifier would only be used in a function's body (implementation), which in case of a header (parameter signature), it's missing.

This declares the function foo which accepts a char* and returns an int.

In your source file, you would have:

#include "my_header.h"

int foo(char* name) {
   //do stuff
   return 0;
}


问:
Getting crazy around weird error on Java with JavaFx
Here is my code:

```<code>    public void start(Stage stage) throws Exception {
        DemoView appView = new DemoView();
        Scene scene = new Scene(appView.getView());
        final String uri = getClass().getResource("app.css").toExternalForm();
        scene.getStylesheets().add(uri);

        stage.setScene(scene);
        stage.setResizable(true);
        stage.setTitle("Character Generator");
        stage.show();
    }
</code>```

It throws an epic combos of errors like:

```<code>Exception in Application start method
java.lang.reflect.InvocationTargetException
</code>```

What am I doing wrong?
The compiler reports me that the code I wrote is the one who needs to be fixed.
If I run it with Java 1.8 everything works, but when I compile it and run with Java 17 it crashes.
If I try to run it from Java 10 to upper, it neither compiles it, just crashes with this error.
The incriminated line should be:

```<code>        Scene scene = new Scene(appView.getView());
</code>```

答:
The use of reflection in Java has been restricted in Java 17.

Take a look into this Oracle blog post for further information.
A peek into Java 17: Encapsulating the Java runtime internals

To figure out the cruel pit of your code, extract the nested Exception using

```<code>try {
    Scene scene = new Scene(appView.getView());
}
catch (InvocationTargetException ex) {
    System.err.println(ex.getCause());
}
</code>```

Body:
Here is my code:

    public void start(Stage stage) throws Exception {
        DemoView appView = new DemoView();
        Scene scene = new Scene(appView.getView());
        final String uri = getClass().getResource("app.css").toExternalForm();
        scene.getStylesheets().add(uri);

        stage.setScene(scene);
        stage.setResizable(true);
        stage.setTitle("Character Generator");
        stage.show();
    }

It throws an epic combos of errors like:

Exception in Application start method
java.lang.reflect.InvocationTargetException

What am I doing wrong?
The compiler reports me that the code I wrote is the one who needs to be fixed.
If I run it with Java 1.8 everything works, but when I compile it and run with Java 17 it crashes.
If I try to run it from Java 10 to upper, it neither compiles it, just crashes with this error.
The incriminated line should be:

        Scene scene = new Scene(appView.getView());

Body:
The use of reflection in Java has been restricted in Java 17.

Take a look into this Oracle blog post for further information.
A peek into Java 17: Encapsulating the Java runtime internals

To figure out the cruel pit of your code, extract the nested Exception using

try {
    Scene scene = new Scene(appView.getView());
}
catch (InvocationTargetException ex) {
    System.err.println(ex.getCause());
}


问:
In an object nesting key-value pairs, how to convert a single-value array into just the value itself?
Given an array that nests inner objects which have key-value pairs, I want to convert single-element-arrays to just the value itself.

So let's say that we have the following albums array:

const albums = [
    {
        "band": ["beetles"],
        "album": ["yellow_submarine"],
        "year": [1969]
    },
    {
        "band": [ "coldplay"],
        "album": ["Parachutes"],
        "year": [2000]
    },
    {
        "band": ["nirvana"],
        "album": ["nevermind"],
        "year": [1991]
    }
]
```
<p>Since all the arrays are single-values, I would like to convert this entire <code>albums</code> object to:</p>
<pre class="lang-js prettyprint-override"><code>// desired output
[
    {
        "band": "beetles",
        "album": "yellow_submarine",
        "year": 1969
    },
    {
        "band": "coldplay",
        "album": "Parachutes",
        "year": 2000
    },
    {
        "band": "nirvana",
        "album": "nevermind",
        "year": 1991
    }
]
</code>```

I've seem lots of posts discussing the opposite (i.e., how to convert a single value into an array), but could not find an answer to this current question. Maybe I'm not using the correct search terms...

答:
If you want to create a new array of new objects, you'd use map along with creating new objects unwrapping their values. You have a couple of options for how to handle the objects. You could use Object.fromEntries and Object.entries:

```<code>const updatedAlbums = albums.map(album =>
    Object.fromEntries(
        Object.entries(album).map(([key, value]) => [key, value[0]])
    )
);
</code>```

Live Example:

const albums = [
    {
        "band": ["beetles"],
        "album": ["yellow_submarine"],
        "year": [1969]
    },
    {
        "band": [ "coldplay"],
        "album": ["Parachutes"],
        "year": [2000]
    },
    {
        "band": ["nirvana"],
        "album": ["nevermind"],
        "year": [1991]
    }
];

const updatedAlbums = albums.map(album =>
    Object.fromEntries(
        Object.entries(album).map(([key, value]) => [key, value[0]])
    )
);

console.log(updatedAlbums);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
    max-height: 100% !important;
}</code>```

Or you could use an inner loop to avoid intermediary arrays:

```<code>const updatedAlbums = albums.map(album => {
    const newAlbum = {};
    for (const key in album) {
        if (Object.hasOwn(album, key)) {
            newAlbum[key] = album[key][0]; // Unwrapping the value
        }
    }
    return newAlbum;
});
</code>```

Live Example:

const albums = [
    {
        "band": ["beetles"],
        "album": ["yellow_submarine"],
        "year": [1969]
    },
    {
        "band": [ "coldplay"],
        "album": ["Parachutes"],
        "year": [2000]
    },
    {
        "band": ["nirvana"],
        "album": ["nevermind"],
        "year": [1991]
    }
];

// Quick-and-dirty polyfill for environments that don't have `Object.hasOwn` yet
if (!Object.hasOwn) {
    Object.hasOwn = Function.prototype.call.bind(Object.prototype.hasOwnProperty);
}

const updatedAlbums = albums.map(album => {
    const newAlbum = {};
    for (const key in album) {
        if (Object.hasOwn(album, key)) {
            newAlbum[key] = album[key][0]; // Unwrapping the value
        }
    }
    return newAlbum;
});

console.log(updatedAlbums);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
    max-height: 100% !important;
}</code>```

Body:
Given an array that nests inner objects which have key-value pairs, I want to convert single-element-arrays to just the value itself.

So let's say that we have the following albums array:

const albums = [
    {
        "band": ["beetles"],
        "album": ["yellow_submarine"],
        "year": [1969]
    },
    {
        "band": [ "coldplay"],
        "album": ["Parachutes"],
        "year": [2000]
    },
    {
        "band": ["nirvana"],
        "album": ["nevermind"],
        "year": [1991]
    }
]

Since all the arrays are single-values, I would like to convert this entire albums object to:

// desired output
[
    {
        "band": "beetles",
        "album": "yellow_submarine",
        "year": 1969
    },
    {
        "band": "coldplay",
        "album": "Parachutes",
        "year": 2000
    },
    {
        "band": "nirvana",
        "album": "nevermind",
        "year": 1991
    }
]

I've seem lots of posts discussing the opposite (i.e., how to convert a single value into an array), but could not find an answer to this current question. Maybe I'm not using the correct search terms...

Body:
If you want to create a new array of new objects, you'd use map along with creating new objects unwrapping their values. You have a couple of options for how to handle the objects. You could use Object.fromEntries and Object.entries:

const updatedAlbums = albums.map(album =>
    Object.fromEntries(
        Object.entries(album).map(([key, value]) => [key, value[0]])
    )
);

Live Example:

const albums = [
    {
        "band": ["beetles"],
        "album": ["yellow_submarine"],
        "year": [1969]
    },
    {
        "band": [ "coldplay"],
        "album": ["Parachutes"],
        "year": [2000]
    },
    {
        "band": ["nirvana"],
        "album": ["nevermind"],
        "year": [1991]
    }
];

const updatedAlbums = albums.map(album =>
    Object.fromEntries(
        Object.entries(album).map(([key, value]) => [key, value[0]])
    )
);

console.log(updatedAlbums);

.as-console-wrapper {
    max-height: 100% !important;
}

Or you could use an inner loop to avoid intermediary arrays:

const updatedAlbums = albums.map(album => {
    const newAlbum = {};
    for (const key in album) {
        if (Object.hasOwn(album, key)) {
            newAlbum[key] = album[key][0]; // Unwrapping the value
        }
    }
    return newAlbum;
});

Live Example:

const albums = [
    {
        "band": ["beetles"],
        "album": ["yellow_submarine"],
        "year": [1969]
    },
    {
        "band": [ "coldplay"],
        "album": ["Parachutes"],
        "year": [2000]
    },
    {
        "band": ["nirvana"],
        "album": ["nevermind"],
        "year": [1991]
    }
];

// Quick-and-dirty polyfill for environments that don't have `Object.hasOwn` yet
if (!Object.hasOwn) {
    Object.hasOwn = Function.prototype.call.bind(Object.prototype.hasOwnProperty);
}

const updatedAlbums = albums.map(album => {
    const newAlbum = {};
    for (const key in album) {
        if (Object.hasOwn(album, key)) {
            newAlbum[key] = album[key][0]; // Unwrapping the value
        }
    }
    return newAlbum;
});

console.log(updatedAlbums);

.as-console-wrapper {
    max-height: 100% !important;
}


问:
tailwindcss not working in create-react-app
I am using tailwindcss for the first time and especially in a react app. I followed the documentation, read some articles and watched some videos. I have my react-app running but tailwindcss classes do not reflect on the application. I have restarted the project from scratch severally but I still face the same issue.
Here is my package.json

答:
I was only able to solve this issue by installing these into the dependencies:

```<code>npm install tailwindcss postcss autoprefixer
</code>```

Body:
I was only able to solve this issue by installing these into the dependencies:

npm install tailwindcss postcss autoprefixer


问:
Elasticsearch get unique values from a text value
I have k8s log data collected from fluentbit and sent to elasticsearch with the format such as

{"log": "job_id: 1", "kubernetes.host":"minikube", ... },
{"log": "job_id: 2", "kubernetes.host":"minikube", ... }
{"log": "job_id: 3", "kubernetes.host":"minikube", ... }
{"log": "job_id: 1", "kubernetes.host":"minikube", ... }
```
<p>and I would like to write a elasticsearch get query such that it returns unique job_ids as</p>
<pre class="lang-json prettyprint-override"><code>["1", "2", "3"]
</code>```

Any help would be appreciated

答:
You can use a terms aggregation ,to return the list of unique job ids

{
    "size": 0,
    "aggs": {
        "unique-job-id": {
            "terms": {
                "field": "log.keyword"
            }
        }
    }
}
```
<p>The search response will be</p>
<pre class="lang-json prettyprint-override"><code>"aggregations": {
        "unique-job-id": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
                {
                    "key": "job_id: 1",
                    "doc_count": 2
                },
                {
                    "key": "job_id: 2",
                    "doc_count": 1
                },
                {
                    "key": "job_id: 3",
                    "doc_count": 1
                }
            ]
        }
    }
</code>```

Body:
I have k8s log data collected from fluentbit and sent to elasticsearch with the format such as

{"log": "job_id: 1", "kubernetes.host":"minikube", ... },
{"log": "job_id: 2", "kubernetes.host":"minikube", ... }
{"log": "job_id: 3", "kubernetes.host":"minikube", ... }
{"log": "job_id: 1", "kubernetes.host":"minikube", ... }

and I would like to write a elasticsearch get query such that it returns unique job_ids as

["1", "2", "3"]

Any help would be appreciated

Body:
You can use a terms aggregation ,to return the list of unique job ids

{
    "size": 0,
    "aggs": {
        "unique-job-id": {
            "terms": {
                "field": "log.keyword"
            }
        }
    }
}

The search response will be

"aggregations": {
        "unique-job-id": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
                {
                    "key": "job_id: 1",
                    "doc_count": 2
                },
                {
                    "key": "job_id: 2",
                    "doc_count": 1
                },
                {
                    "key": "job_id: 3",
                    "doc_count": 1
                }
            ]
        }
    }