问:
Object is of type 'unknown'.ts(2571) in generic component
I have a Table component with generics and I use a static component inside the Table to compose columns, also with generics.

The problem is that I would like the Column component to inherit the generic type passed to the Table when executing the data function, which gets the result passed to it.

I know typing explicitly will work, for example:

<Table.Column<TableItem> data={(item) => item.name} />

The real question is: Is it possible to perform this type inference from my Table component and pass it to the static Column component? So that I don't have to add the type explicitly to each column...

SANDBOX TO REPRODUCE, ONLY TABLE AND COLUMN COMPONENTS:

https://codesandbox.io/s/generic-table-column-r54lh?file=/src/App.tsx

答:
There is an issue in your typing of children, namely that you are using ReactElement which does not include typing for the actual JSX function, just the returned element. You can see this in your example, by noting that the following covariant and contravariant children both pass, notwithstanding your children typing:

const MyDiv = (props:{myProp:string})=>
{props.myProp}

const App = () => {
  return (
    <Table<TableItem> keyExtractor={(item) => item.id} values={items}>

 item.name} />

 item.surname} />
      <MyDiv myProp="me" />

  );
};
```

BUT... I don't think that's really your underlying issue.  The problem really is that you want Typescript to check that your children components are actually created via specific JSX with specific props, but, in fact, all Typescript will currently do is check that your JSX returns a valid JSX.Element.  It won't check that the function that generated that JSX.Element satisfies a particular type or that the return type of that function is a specific kind of element with specific props.

This is a design limitation that is discussed in this open issue.

I think you could work around this by essentially defining your own custom prop that took in the props for Table.Column and then passed them to Table.Column inside your Table component. E.g, something like columnProps: ColumnProps<T> as a prop of Table.  I'm not sure that would be any easier than just providing the explicit type to Table.Column, however.

Body:
There is an issue in your typing of children, namely that you are using ReactElement which does not include typing for the actual JSX function, just the returned element. You can see this in your example, by noting that the following covariant and contravariant children both pass, notwithstanding your children typing:

const MyDiv = (props:{myProp:string})=><div>{props.myProp}</div>

const App = () => {
  return (
    <Table<TableItem> keyExtractor={(item) => item.id} values={items}>
      <Table.Column header="Name" data={(item) => item.name} />
      <Table.Column header="Surname" data={(item) => item.surname} />
      <MyDiv myProp="me" />
      <div />
    </Table>
  );
};

BUT... I don't think that's really your underlying issue.  The problem really is that you want Typescript to check that your children components are actually created via specific JSX with specific props, but, in fact, all Typescript will currently do is check that your JSX returns a valid JSX.Element.  It won't check that the function that generated that JSX.Element satisfies a particular type or that the return type of that function is a specific kind of element with specific props.

This is a design limitation that is discussed in this open issue.

I think you could work around this by essentially defining your own custom prop that took in the props for Table.Column and then passed them to Table.Column inside your Table component. E.g, something like columnProps: ColumnProps<T> as a prop of Table.  I'm not sure that would be any easier than just providing the explicit type to Table.Column, however.


来源: stackexchange

问:
How do i solve General error: 1364 - Laravel
Screenshot of the error page

How do i go about this please? I created another table in my db where i generate OTPs and send to the users. in my table i made user_id and id(primary) but due to the nature of my code and how i want the site to function, i set user_id as a reference of id so that whenever OTP is generated, it will be the current user's ID

It seems there's no default value for user_id so i did ;

```<code>UserOTP::create(["user_id"=> auth()->id()]);
</code>```

but its not working, what is wrong with my code please?

```<code>    <?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUserOtpsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {

        Schema::create('user_otps', function (Blueprint $table) {

            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->integer('code');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();

        });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('user_otps');
    }
}
</code>```

This is the db migration file

答:
Okay so i found it. Instead of keeping the answer to myself, i wanna share to whoever that may have this issue in the future.

so i made a function called rules where i forgot to add user_opts to code .

```<code> public function rules()
{
    return [
        'otpcode' => ['required','numeric',Rule::exists('user_otps','code')->where(function($query){
            $query->whereUserId(auth()->id());
        })]
    ];
</code>```

adding user_otps to code actually solved it and everything is working now. The main problem wasnt this but rather, as the previous answers were saying. My user_id field wasnt receiving a value on submit.

Happy to resolve this issue and thanks to whoever helped

ContentLicense: CC BY-SA 4.0

Body:
Screenshot of the error page

How do i go about this please? I created another table in my db where i generate OTPs and send to the users. in my table i made user_id and id(primary) but due to the nature of my code and how i want the site to function, i set user_id as a reference of id so that whenever OTP is generated, it will be the current user's ID

It seems there's no default value for user_id so i did ;

UserOTP::create(["user_id"=> auth()->id()]);

but its not working, what is wrong with my code please?

    <?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUserOtpsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {

        Schema::create('user_otps', function (Blueprint $table) {

            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->integer('code');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();

        });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('user_otps');
    }
}

This is the db migration file

Body:
Okay so i found it. Instead of keeping the answer to myself, i wanna share to whoever that may have this issue in the future.

so i made a function called rules where i forgot to add user_opts to code .

 public function rules()
{
    return [
        'otpcode' => ['required','numeric',Rule::exists('user_otps','code')->where(function($query){
            $query->whereUserId(auth()->id());
        })]
    ];

adding user_otps to code actually solved it and everything is working now. The main problem wasnt this but rather, as the previous answers were saying. My user_id field wasnt receiving a value on submit.

Happy to resolve this issue and thanks to whoever helped


问:
Convert RGB to RGBA at 0.9 alpha in string
I need to take the color gradient and dynamically change rgb to rgba and add 0.9 alpha, or some other number. Of course div id="gradient" can have more than three rgb and rgba colors. I tried replace ((')', ', 0.9)'). Replace ('rgb', 'rgba'); but it does not work.  How do I do this?

The result should look like:

linear-gradient(90deg, rgba(205, 55, 55, 0.7) 11%, rgba(80, 55, 205, 0.9) 45%, rgba(55, 205, 73, 0.5) 79%)

function myFunction() {
  var gradient = document.getElementById("gradient").style.background;
  document.getElementById("demo").innerHTML = gradient.replace(')', ', 0.9)').replace('rgb', 'rgba');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="gradient" style="background: linear-gradient(
90deg
, rgba(215, 45, 45, 0.7) 11%, rgb(73, 45, 215) 45%, rgba(45, 215, 65, 0.5) 79%);"></div>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p></code>```

Body:
I need to take the color gradient and dynamically change rgb to rgba and add 0.9 alpha, or some other number. Of course div id="gradient" can have more than three rgb and rgba colors. I tried replace ((')', ', 0.9)'). Replace ('rgb', 'rgba'); but it does not work.  How do I do this?

The result should look like:

linear-gradient(90deg, rgba(205, 55, 55, 0.7) 11%, rgba(80, 55, 205, 0.9) 45%, rgba(55, 205, 73, 0.5) 79%)

function myFunction() {
  var gradient = document.getElementById("gradient").style.background;
  document.getElementById("demo").innerHTML = gradient.replace(')', ', 0.9)').replace('rgb', 'rgba');
}

<button onclick="myFunction()">Click me</button>

Body:
Can also be:

// a regular expression with named capturing group "rgb" that captures the RGB values: "rgb(1, 20, 140)" -> "1, 20, 140"
const r = /rgb\((?<rgb>\d+\s*,\s*\d+\s*,\s*\d+)\)/;

let style = 'linear-gradient(90deg, rgb(205, 55, 55) 11%, rgb(80, 55, 205) 45%, rgb(55, 205, 73) 79%)';

// now we can change the values 1 by 1

style = style.replace(r, "rgba($1, 0.7)");
// linear-gradient(90deg, rgba(205, 55, 55, 0.7) 11%, rgb(80, 55, 205) 45%, rgb(55, 205, 73) 79%)

style = style.replace(r, "rgba($1, 0.9)");
// linear-gradient(90deg, rgba(205, 55, 55, 0.7) 11%, rgba(80, 55, 205, 0.9) 45%, rgb(55, 205, 73) 79%)

style = style.replace(r, "rgba($1, 0.5)");
// linear-gradient(90deg, rgba(205, 55, 55, 0.7) 11%, rgba(80, 55, 205, 0.9) 45%, rgba(55, 205, 73, 0.5) 79%)

console.log(style);

// linear-gradient(90deg, rgba(205, 55, 55, 0.7) 11%, rgba(80, 55, 205, 0.9) 45%, rgba(55, 205, 73, 0.5) 79%)


问:
Config block returns not found, in hyperledger fabric
Trying to fetch config block to create a config update.
I'm using the test network in fabric samples with default settings (no CA)
even after starting the network I cannot fetch any blocks. not latest or oldest either

This is the output I'm getting

peer channel fetch config

2022-02-08 11:09:47.306 +03 [channelCmd] InitCmdFactory -> INFO 001 Endorser and orderer connections initialized
2022-02-08 11:09:47.309 +03 [cli.common] readBlock -> INFO 002 Expect block, but got status: &{NOT_FOUND}
Error: can't read the block: &{NOT_FOUND}

答:
I think you need to specify the channel, for example:

```<code>peer channel fetch config -c mychannel
</code>```

That works for me with the default test network channel, and I get the same error you saw without the -c option.

It's also worth having a look at the test network scripts since they are meant to be a sample themselves. In this case configUpdate.sh does a config update.

Body:
I think you need to specify the channel, for example:

peer channel fetch config -c mychannel

That works for me with the default test network channel, and I get the same error you saw without the -c option.

It's also worth having a look at the test network scripts since they are meant to be a sample themselves. In this case configUpdate.sh does a config update.


问:
Mocha: bail on one specific describe only
I use mocha/chai to test my graphql endpoints for a nodejs/express server - which works fine. However, in the first test, I check if any .env variables have been set correctly.
If not, all further tests will be affected anyways. So I would like to terminate all further tests when any test in this block fails (preferably finishing the block to capture all 'missing' variables).

So can I somehow terminate the entire test, when a certain describe-block fails?

Note: I found the bail flag/config option, but this determines the whole test on any error, which is not what I'm looking for.

答:
You can try add after hook and add a condition there

```<code>after('Fail for some describe', function () {
            if(this.test.parent.title.startsWith('Describe title that should fail') && this.test.parent.isFailed())
                this.test.parent._bail = true
        });
</code>```

This could be tricky since this context may contain several layers of parents so if not sure you can always log the keys for current this.test object. Also, bear in mind that the following describe might have different this context with overriden _bail value. This solution is good when it comes to tracking specific critical it failures.

Body:
You can try add after hook and add a condition there

after('Fail for some describe', function () {
            if(this.test.parent.title.startsWith('Describe title that should fail') && this.test.parent.isFailed())
                this.test.parent._bail = true
        });

This could be tricky since this context may contain several layers of parents so if not sure you can always log the keys for current this.test object. Also, bear in mind that the following describe might have different this context with overriden _bail value. This solution is good when it comes to tracking specific critical it failures.


问:
How to populate mongoose with obejectId which is defined as Number?
I'm trying to populate my user requests.profileId but it returns only nulls.

I have the following schemas:

First Schema:

```<code>const profileSchema = new mongoose.Schema({
  _id: { type: Number }, //<- _id is defined as a number which represents mobile number (easier for me to handle)
  first: { type: String },
  second: { type: String },
});

module.exports = mongoose.model('Profile', profileSchema, 'profiles');
</code>```

Second Schema:

```<code>const userSchema = new mongoose.Schema({
  firstName: { type: String },
  lastName: { type: String },
  requests: [
    {
      profileId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Profile',
      },
      requestTime: { type: Date, default: Date.now },
    },
  ],
});

module.exports = mongoose.model('User', userSchema, 'users');
</code>```

Here is my code:

```<code>const user = await User.findById(req.user).populate('requests.profileId');
console.log(user.requests);
</code>```

Here is the output:

```<code>[
  {
    _id: 6201633869648e2b74c00a10,
    profileId: null,
    requestTime: 2022-02-07T18:21:44.722Z
  },
  {
    _id: 6201633b69648e2b74c00a11,
    profileId: null,
    requestTime: 2022-02-07T18:21:47.238Z
  },
  {
    _id: 620238f9d2b5dd3dee6c41a2,
    profileId: null,
    requestTime: 2022-02-08T09:33:45.176Z
  },
  {
    _id: 620239253220343dfd7cfdd9,
    profileId: null,
    requestTime: 2022-02-08T09:34:29.780Z
  }
]
</code>```

Here is the output without populate:

```<code>[
  {
    _id: 6201633869648e2b74c00a10,
    profileId: 393732353235303134343330, //<- typeof profileId is obeject
    requestTime: 2022-02-07T18:21:44.722Z
  },
  {
    _id: 6201633b69648e2b74c00a11,
    profileId: 393732353435353333313131,
    requestTime: 2022-02-07T18:21:47.238Z
  },
  {
    _id: 620238f9d2b5dd3dee6c41a2,
    profileId: 393732353435353333313131,
    requestTime: 2022-02-08T09:33:45.176Z
  },
  {
    _id: 620239253220343dfd7cfdd9,
    profileId: 393732353435353333313131,
    requestTime: 2022-02-08T09:34:29.780Z
  }
]
</code>```

Currently Profile.findById(mobileNumber) works fine.

Any ideas what went wrong?

Will greatly appreciate your assistance.

Thanks in advance :)

答:
Try this might work let me know if it doesn't</p>
```<code>const user = await User.findById(req.user).populate('Profile');
console.log(user.requests);
</code>```

Body:
I'm trying to populate my user requests.profileId but it returns only nulls.

I have the following schemas:

First Schema:

const profileSchema = new mongoose.Schema({
  _id: { type: Number }, //<- _id is defined as a number which represents mobile number (easier for me to handle)
  first: { type: String },
  second: { type: String },
});

module.exports = mongoose.model('Profile', profileSchema, 'profiles');

Second Schema:

const userSchema = new mongoose.Schema({
  firstName: { type: String },
  lastName: { type: String },
  requests: [
    {
      profileId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Profile',
      },
      requestTime: { type: Date, default: Date.now },
    },
  ],
});

module.exports = mongoose.model('User', userSchema, 'users');

Here is my code:

const user = await User.findById(req.user).populate('requests.profileId');
console.log(user.requests);

Here is the output:

[
  {
    _id: 6201633869648e2b74c00a10,
    profileId: null,
    requestTime: 2022-02-07T18:21:44.722Z
  },
  {
    _id: 6201633b69648e2b74c00a11,
    profileId: null,
    requestTime: 2022-02-07T18:21:47.238Z
  },
  {
    _id: 620238f9d2b5dd3dee6c41a2,
    profileId: null,
    requestTime: 2022-02-08T09:33:45.176Z
  },
  {
    _id: 620239253220343dfd7cfdd9,
    profileId: null,
    requestTime: 2022-02-08T09:34:29.780Z
  }
]

Here is the output without populate:

[
  {
    _id: 6201633869648e2b74c00a10,
    profileId: 393732353235303134343330, //<- typeof profileId is obeject
    requestTime: 2022-02-07T18:21:44.722Z
  },
  {
    _id: 6201633b69648e2b74c00a11,
    profileId: 393732353435353333313131,
    requestTime: 2022-02-07T18:21:47.238Z
  },
  {
    _id: 620238f9d2b5dd3dee6c41a2,
    profileId: 393732353435353333313131,
    requestTime: 2022-02-08T09:33:45.176Z
  },
  {
    _id: 620239253220343dfd7cfdd9,
    profileId: 393732353435353333313131,
    requestTime: 2022-02-08T09:34:29.780Z
  }
]

Currently Profile.findById(mobileNumber) works fine.

Any ideas what went wrong?

Will greatly appreciate your assistance.

Thanks in advance :)

Body:
Try this might work let me know if it doesn't

const user = await User.findById(req.user).populate('Profile');
console.log(user.requests);


问:
Adding condition when counting NA value by a group
I am counting row-based Na values according to col1 variable in the data set. I want to add a condition to this query:

When calculating the number of NA,
For col2 = a and b, also look at col4 column, for col2 = c, do not look at col4 column

```<code># creating a dataframe
data_frame <- data.frame(col1 = sample(6:9, 9 , replace = TRUE),
                        col2 = letters[1:3],
                        col3 = c(1,NA,NA,1,NA,NA,2,NA,2),
                        col4 = c(1,4,NA,1,NA,NA,NA,1,2))

data_frame = data_frame %>%
   rowwise() %>%
   mutate(Count_NA = sum(is.na(cur_data()))) %>%
   ungroup

#print (data_frame)

data_frame %>% group_by(col1) %>%
   summarize(Sum_Count_NA=sum(Count_NA))
</code>```

The output I want is;

col1
col2
col3
col4
Count_NA

8
a
1
1
0

6
b
NA
4
1

8
c
NA
NA
2

7
a
1
1
0

8
b
NA
NA
2

8
c
NA
NA
2

8
a
2
NA
1

8
b
NA
1
1

9
c
2
2
0

After adding the condition, the output I want is;
Counting Na in col4 for col2 = c

col1
col2
col3
col4
Count_NA

8
a
1
1
0

6
b
NA
4
1

8
c
NA
NA
1

7
a
1
1
0

8
b
NA
NA
2

8
c
NA
NA
1

8
a
2
NA
1

8
b
NA
1
1

9
c
2
2
0

答:
You can do this:

library(dplyr)
data_frame %>%
  mutate(sum = rowSums(is.na(select(., contains("col3")))) + (col2 == "c" & is.na(col4)))

  col1 col2 col3 col4 sum
1    8    a    1    1   0
2    6    b   NA    4   1
3    9    c   NA   NA   2
4    8    a    1    1   0
5    7    b   NA   NA   1
6    7    c   NA   NA   2
7    7    a    2   NA   0
8    9    b   NA    1   1
9    7    c    2    2   0
```
<p><strong>data</strong></p>
```data_frame <- structure(list(col1 = c(8L, 6L, 9L, 8L, 7L, 7L, 7L, 9L, 7L),
    col2 = c("a", "b", "c", "a", "b", "c", "a", "b", "c"), col3 = c(1,
    NA, NA, 1, NA, NA, 2, NA, 2), col4 = c(1, 4, NA, 1, NA, NA,
    NA, 1, 2)), class = "data.frame", row.names = c(NA, -9L))
```

Body:
I am counting row-based Na values according to col1 variable in the data set. I want to add a condition to this query:

When calculating the number of NA,
For col2 = a and b, also look at col4 column, for col2 = c, do not look at col4 column

# creating a dataframe
data_frame <- data.frame(col1 = sample(6:9, 9 , replace = TRUE),
                        col2 = letters[1:3],
                        col3 = c(1,NA,NA,1,NA,NA,2,NA,2),
                        col4 = c(1,4,NA,1,NA,NA,NA,1,2))

data_frame = data_frame %>%
   rowwise() %>%
   mutate(Count_NA = sum(is.na(cur_data()))) %>%
   ungroup

#print (data_frame)

data_frame %>% group_by(col1) %>%
   summarize(Sum_Count_NA=sum(Count_NA))

The output I want is;

col1
col2
col3
col4
Count_NA

8
a
1
1
0

6
b
NA
4
1

8
c
NA
NA
2

7
a
1
1
0

8
b
NA
NA
2

8
c
NA
NA
2

8
a
2
NA
1

8
b
NA
1
1

9
c
2
2
0

After adding the condition, the output I want is;
Counting Na in col4 for col2 = c

col1
col2
col3
col4
Count_NA

8
a
1
1
0

6
b
NA
4
1

8
c
NA
NA
1

7
a
1
1
0

8
b
NA
NA
2

8
c
NA
NA
1

8
a
2
NA
1

8
b
NA
1
1

9
c
2
2
0

Body:
You can do this:

library(dplyr)
data_frame %>%
  mutate(sum = rowSums(is.na(select(., contains("col3")))) + (col2 == "c" & is.na(col4)))

  col1 col2 col3 col4 sum
1    8    a    1    1   0
2    6    b   NA    4   1
3    9    c   NA   NA   2
4    8    a    1    1   0
5    7    b   NA   NA   1
6    7    c   NA   NA   2
7    7    a    2   NA   0
8    9    b   NA    1   1
9    7    c    2    2   0

data

data_frame <- structure(list(col1 = c(8L, 6L, 9L, 8L, 7L, 7L, 7L, 9L, 7L),
    col2 = c("a", "b", "c", "a", "b", "c", "a", "b", "c"), col3 = c(1,
    NA, NA, 1, NA, NA, 2, NA, 2), col4 = c(1, 4, NA, 1, NA, NA,
    NA, 1, 2)), class = "data.frame", row.names = c(NA, -9L))


问:
Is there any way to represent any number as sum of 4 squares?
Is there any way to represent any number as sum of 4 squares.

For example 29 can be represented as 5^2+2^2+0^2+0^2

I tried the following code but some numbers giving 5terms for example 23 as 4^2+2^2+1^2+1^2+1^2

the code i tried is :

```<code> x=0;
 while(num!=0){
          x=(int)Math.floor(Math.sqrt(num));
         num=num-(x*x);
}
</code>```

答:
Unlike what Bohemian said, I solved 23 in 4 terms as follows:

```<code>23 = 3^2 + 3^2 + 2^2 + 1^2
</code>```

And 29 as follows:

```<code>29 = 4^2 + 3^2 + 2^2 + 0^2
</code>```

My logic would start as:

Start with the square root of the number - 1. E.g. SQRT(29) = 5 - 1 = 4; This is now our first term.

Take value from point 1), square it and add to it again the squared value from point 1) and see if it's greater than N. If it is, decrement the 2nd sum term by 1 and add it the squared value to value from 1).

If the previous squared value terms sums are less than N, find next value term and repeat 2) until you have all 4 terms that adds up to N.

Note: This is for your simple case. For complex case like e.g. 323, this might not work.

```<code>323 = 17^2 + 4^2 + 3^2 + 3^2
</code>```

Bear in mind, as you find the x term, the term's value is less than or equal to the x-1 (previous) term's value.

ContentLicense: CC BY-SA 3.0

Body:
Is there any way to represent any number as sum of 4 squares.

For example 29 can be represented as 5^2+2^2+0^2+0^2

I tried the following code but some numbers giving 5terms for example 23 as 4^2+2^2+1^2+1^2+1^2

the code i tried is :

 x=0;
 while(num!=0){
          x=(int)Math.floor(Math.sqrt(num));
         num=num-(x*x);
}

Body:
Unlike what Bohemian said, I solved 23 in 4 terms as follows:

23 = 3^2 + 3^2 + 2^2 + 1^2

And 29 as follows:

29 = 4^2 + 3^2 + 2^2 + 0^2

My logic would start as:

Start with the square root of the number - 1. E.g. SQRT(29) = 5 - 1 = 4; This is now our first term.

Take value from point 1), square it and add to it again the squared value from point 1) and see if it's greater than N. If it is, decrement the 2nd sum term by 1 and add it the squared value to value from 1).

If the previous squared value terms sums are less than N, find next value term and repeat 2) until you have all 4 terms that adds up to N.

Note: This is for your simple case. For complex case like e.g. 323, this might not work.

323 = 17^2 + 4^2 + 3^2 + 3^2

Bear in mind, as you find the x term, the term's value is less than or equal to the x-1 (previous) term's value.


问:
CSS Flex item spanning two rows without fixed height
I am trying to create a flex container layout whereby one of the flex items should span two rows. See image below for a better explanation:

Here is my markup:

```<code><div class="container">
    <div class="item item-1">ITEM 1</div>
    <div class="item item-2">ITEM 2</div>
    <div class="item item-3">ITEM 3</div>
</div>
</code>```

I cannot seem to achieve this, I have tried using flex-wrap and different combinations of the flex property.

I was able to achieve this by putting ITEM 1 & ITEM 2 in a separate
, but this presents a problem on a smaller screen, whereby ITEM 3 needs to appear BETWEEN ITEM 1 & ITEM 2. So I would rather keep the markup as is and use the order property to move things around as necessary.

答:
You can't achieve it using flexbox. Instead, you should have two parents which are better.

Use Css-grid. Actually, css-grid is the best option in this case.

Flex-Box

* {
  color: #fff;
}

.flex {
  display: flex;
  justify-content: center;
  align-items: center;
}

.child {
  border-radius: 10px;
}

.container {
  display: flex;
  width: 500px;
  height: 200px;
  border: 1px solid #ff0000;
}

.container .first-item {
  flex-direction: column;
  justify-content: space-between;
  align-items: start;
  width: 50%;
  height: 100%;
  margin-right: 10px;
}

.first-item .child {
  width: 100%;
  height: 50%;
  background-color: blue;
}

.first-item .child:first-child {
  margin-bottom: 10px;
}

.container .second-item {
  width: 50%;
  height: 100%;
}

.second-item .child {
  width: 100%;
  height: 100%;
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="first-item flex">
    <div class="child flex">Item 1</div>
    <div class="child flex">Item 2</div>
  </div>
  <div class="second-item flex">
    <div class="child flex">Item 3</div>
  </div>
</div></code>```

Grid

.flex {
  display: flex;
  justify-content: center;
  align-items: center;
}

.child {
  background-color: blue;
  border-radius: 10px;
}

.container {
  display: grid;
  grid-template-columns: 1fr 10px 1fr;
  grid-template-rows: 1fr 10px 1fr;
  grid-template-areas: "c1 . c3"
                       ".  . c3"
                       "c2 . c3";
 width: 500px;
  height: 300px;
  border: 1px solid red;
}

.container .child {
  border: 1px solid blue;
}

.child1 {
  grid-area: c1;
}

.child2 {
  grid-area: c2;
}

.child3 {
  grid-area: c3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="child child1 flex">Item 1</div>
  <div class="child child3 flex">Item 3</div>
  <div class="child child2 flex">Item 2</div>
</div></code>```

Body:
I am trying to create a flex container layout whereby one of the flex items should span two rows. See image below for a better explanation:

Here is my markup:

ITEM 1

ITEM 2

ITEM 3

I cannot seem to achieve this, I have tried using flex-wrap and different combinations of the flex property.

I was able to achieve this by putting ITEM 1 & ITEM 2 in a separate
, but this presents a problem on a smaller screen, whereby ITEM 3 needs to appear BETWEEN ITEM 1 & ITEM 2. So I would rather keep the markup as is and use the order property to move things around as necessary.

Body:
You can't achieve it using flexbox. Instead, you should have two parents which are better.

Use Css-grid. Actually, css-grid is the best option in this case.

Flex-Box

* {
  color: #fff;
}

.flex {
  display: flex;
  justify-content: center;
  align-items: center;
}

.child {
  border-radius: 10px;
}

.container {
  display: flex;
  width: 500px;
  height: 200px;
  border: 1px solid #ff0000;
}

.container .first-item {
  flex-direction: column;
  justify-content: space-between;
  align-items: start;
  width: 50%;
  height: 100%;
  margin-right: 10px;
}

.first-item .child {
  width: 100%;
  height: 50%;
  background-color: blue;
}

.first-item .child:first-child {
  margin-bottom: 10px;
}

.container .second-item {
  width: 50%;
  height: 100%;
}

.second-item .child {
  width: 100%;
  height: 100%;
  background-color: blue;
}

<div class="container">
  <div class="first-item flex">
    <div class="child flex">Item 1</div>
    <div class="child flex">Item 2</div>
  </div>
  <div class="second-item flex">
    <div class="child flex">Item 3</div>
  </div>
</div>

Grid

.flex {
  display: flex;
  justify-content: center;
  align-items: center;
}

.child {
  background-color: blue;
  border-radius: 10px;
}

.container {
  display: grid;
  grid-template-columns: 1fr 10px 1fr;
  grid-template-rows: 1fr 10px 1fr;
  grid-template-areas: "c1 . c3"
                       ".  . c3"
                       "c2 . c3";
 width: 500px;
  height: 300px;
  border: 1px solid red;
}

.container .child {
  border: 1px solid blue;
}

.child1 {
  grid-area: c1;
}

.child2 {
  grid-area: c2;
}

.child3 {
  grid-area: c3;
}

<div class="container">
  <div class="child child1 flex">Item 1</div>
  <div class="child child3 flex">Item 3</div>
  <div class="child child2 flex">Item 2</div>
</div>


问:
How can I add pagination in Lumen 8 collection?
I am using Lumen to create api where I integrate collection. All code details are given below. I want to add pagination according to my code. How I add paginator in my code?

In Controller:

```<code>//To get all Employee Type
public function getAllEmployeeTypes(){

    $employeeType = OsEmployeeType::where('status',1)->orderBy('priority', 'DESC')->get();
    return new OsEmployeeTypeCollection($employeeType);
}
</code>```

In Collection it looks like

```<code>public function toArray($request)
{
    return [
        'data' => $this->collection->map(function($data) {
            return [
                'id' => $data->id,
                'name' => $data->name,
                'priority' => $data->priority,
                'status' => $data->status,
            ];
        })
    ];
}

public function with($request)
{
    return [
        'success' => true,
        'status' => 200
    ];
}
</code>```

and the response that I got

```<code>{
"data": [
    {
        "id": 3,
        "name": "Type 3",
        "priority": 3,
        "status": 1
    },
    {
        "id": 2,
        "name": "Type 2",
        "priority": 2,
        "status": 1
    },
    {
        "id": 1,
        "name": "Type 1",
        "priority": 1,
        "status": 1
    }
],
"success": true,
"status": 200
</code>```

}

How can I paginate my API response?

答:
Paginate is the same as Laravel in Lumen. You will do just the same as in Laravel.</p>
```<code>    $employeeType = OsEmployeeType::where('status',1)->orderBy('priority', 'DESC')->skip(10)->take(5)->get();
</code>```

Body:
I am using Lumen to create api where I integrate collection. All code details are given below. I want to add pagination according to my code. How I add paginator in my code?

In Controller:

//To get all Employee Type
public function getAllEmployeeTypes(){

    $employeeType = OsEmployeeType::where('status',1)->orderBy('priority', 'DESC')->get();
    return new OsEmployeeTypeCollection($employeeType);
}

In Collection it looks like

public function toArray($request)
{
    return [
        'data' => $this->collection->map(function($data) {
            return [
                'id' => $data->id,
                'name' => $data->name,
                'priority' => $data->priority,
                'status' => $data->status,
            ];
        })
    ];
}

public function with($request)
{
    return [
        'success' => true,
        'status' => 200
    ];
}

and the response that I got

{
"data": [
    {
        "id": 3,
        "name": "Type 3",
        "priority": 3,
        "status": 1
    },
    {
        "id": 2,
        "name": "Type 2",
        "priority": 2,
        "status": 1
    },
    {
        "id": 1,
        "name": "Type 1",
        "priority": 1,
        "status": 1
    }
],
"success": true,
"status": 200

}

How can I paginate my API response?

Body:
Paginate is the same as Laravel in Lumen. You will do just the same as in Laravel.

    $employeeType = OsEmployeeType::where('status',1)->orderBy('priority', 'DESC')->skip(10)->take(5)->get();


问:
Powershell Get and Use XML Content from URL
I can query the VPN users of our firewall via API-Call in Chrome.

https://knowledgebase.paloaltonetworks.com/KCSArticleDetail?id=kA10g000000Clor

I would like to use result.content as XML in Powershell to work with the objects.

```<code>$url=https://localfirewall.domain.tld/api/?type=op&cmd=<show><global-protect-gateway><current-user></current-user></global-protect-gateway></show>&verysecretapikey=
$result=invoke-webrequest -uri $url -skipcertificatechek -method:get -contenttype "application/xml
$result.content
</code>```

In PaloAlto's KB article you can see the output of the call in the browser.

答:
A string containing well-formed xml is implicitly parsed if you simply convert it to the [xml] type:

```<code># using the `-as` conversion operator
# this will silently return $null on failure to parse the document
$xmlDocument = $result.content -as [xml]

# using a cast operation
# this will throw on failure to parse the document
$xmlDocument = [xml]$result.content
</code>```

Body:
I can query the VPN users of our firewall via API-Call in Chrome.

https://knowledgebase.paloaltonetworks.com/KCSArticleDetail?id=kA10g000000Clor

I would like to use result.content as XML in Powershell to work with the objects.

$url=https://localfirewall.domain.tld/api/?type=op&cmd=<show><global-protect-gateway><current-user></current-user></global-protect-gateway></show>&verysecretapikey=
$result=invoke-webrequest -uri $url -skipcertificatechek -method:get -contenttype "application/xml
$result.content

In PaloAlto's KB article you can see the output of the call in the browser.

Body:
A string containing well-formed xml is implicitly parsed if you simply convert it to the [xml] type:

# using the `-as` conversion operator
# this will silently return $null on failure to parse the document
$xmlDocument = $result.content -as [xml]

# using a cast operation
# this will throw on failure to parse the document
$xmlDocument = [xml]$result.content


问:
React/node => image display not allowed to load local ressource
I'm on a react/node website project. Pretty simple website with a crud.
My crud worked but my pictures doesn't appears (they are upload on a folder public/uploads/news/ and their path is save in mongoDb) For my news I can see the title, message, date but the picture is broken and I've only the alt.
When I go to the console and go on the element, the patch is OK "c:/users/......... /public/uploads/news/nameofmypicture.jpg".
I just got an error message "not allowed to load local resources"

import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { dateParser, isEmpty } from "../../../general/utils/Utils";
import { updateNews } from "../../../../store/actions/news.actions";
import DeleteCard from "./DeleteCard";
import Loader from "../../../general/utils/Loading";

const Card = ({ news }) => {
    const [isLoading, setIsLoading] = useState(true);
    const [isUpdated, setIsUpdated] = useState(false);
    const [textUpdate, setTextUpdate] = useState(null);
    const newsData = useSelector((state) => state.newsReducer);
    const dispatch = useDispatch();

    const updateItem = () => {
        if (textUpdate) {
            dispatch(updateNews(news._id, textUpdate));
        }
        setIsUpdated(false);
    };

    useEffect(() => {
        !isEmpty(newsData[0]) && setIsLoading(false);
    }, [newsData]);

    return (

            {isLoading ? (
                <Loader />
            ) : (
                <>

                        {isUpdated === false &&
{news.title}
}
                        {isUpdated && (

                                <textarea
                                    defaultValue={news.title}
                                    onChange={(e) => setTextUpdate(e.target.value)}
                                />

                        )}
                            {dateParser(news.createdAt)}

                        {isUpdated === false &&
{news.message}
}
                        {isUpdated && (

                                <textarea
                                    defaultValue={news.message}
                                    onChange={(e) => setTextUpdate(e.target.value)}
                                />

                                    <button className="btn btn-success" onClick={updateItem}>
                                        Valider modification
                                    </button>

                        )}
                        {news.picture && (

                        )}
                        {news.video && (

                        )}

                            <button className="btn btn-primary" onClick={() => setIsUpdated(!isUpdated)}>Edit</button>
                            <DeleteCard id={news._id} />

                </>
            )}

    );
};

export default Card;```

If someone wants the full code
https://github.com/macath/AJC-modelism
If you have more questions, ask me. I'm on this problem since 4 days, I really don't understand why it's don't work.
I specify that this project will be put online so I need a valid solution on a server and not only local

Ps : sorry for my English I'm French

答:
please check this answer

How to upload, display and save images using node.js and express

Body:
I'm on a react/node website project. Pretty simple website with a crud.
My crud worked but my pictures doesn't appears (they are upload on a folder public/uploads/news/ and their path is save in mongoDb) For my news I can see the title, message, date but the picture is broken and I've only the alt.
When I go to the console and go on the element, the patch is OK "c:/users/......... /public/uploads/news/nameofmypicture.jpg".
I just got an error message "not allowed to load local resources"

import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { dateParser, isEmpty } from "../../../general/utils/Utils";
import { updateNews } from "../../../../store/actions/news.actions";
import DeleteCard from "./DeleteCard";
import Loader from "../../../general/utils/Loading";

const Card = ({ news }) => {
    const [isLoading, setIsLoading] = useState(true);
    const [isUpdated, setIsUpdated] = useState(false);
    const [textUpdate, setTextUpdate] = useState(null);
    const newsData = useSelector((state) => state.newsReducer);
    const dispatch = useDispatch();

    const updateItem = () => {
        if (textUpdate) {
            dispatch(updateNews(news._id, textUpdate));
        }
        setIsUpdated(false);
    };

    useEffect(() => {
        !isEmpty(newsData[0]) && setIsLoading(false);
    }, [newsData]);

    return (

            {isLoading ? (
                <Loader />
            ) : (
                <>

                        {isUpdated === false &&
{news.title}
}
                        {isUpdated && (

                                <textarea
                                    defaultValue={news.title}
                                    onChange={(e) => setTextUpdate(e.target.value)}
                                />

                        )}
                            {dateParser(news.createdAt)}

                        {isUpdated === false &&
{news.message}
}
                        {isUpdated && (

                                <textarea
                                    defaultValue={news.message}
                                    onChange={(e) => setTextUpdate(e.target.value)}
                                />

                                    <button className="btn btn-success" onClick={updateItem}>
                                        Valider modification
                                    </button>

                        )}
                        {news.picture && (

                        )}
                        {news.video && (

                        )}

                            <button className="btn btn-primary" onClick={() => setIsUpdated(!isUpdated)}>Edit</button>
                            <DeleteCard id={news._id} />

                </>
            )}

    );
};

export default Card;

If someone wants the full code
https://github.com/macath/AJC-modelism
If you have more questions, ask me. I'm on this problem since 4 days, I really don't understand why it's don't work.
I specify that this project will be put online so I need a valid solution on a server and not only local

Ps : sorry for my English I'm French


问:
Got a "401 - Unauthorized" when trying my WCF Data service on IIS
I developed a WCF Data Service, which runs fine, I can do every operation I want through.

I developed a small c# client which tests all functions: adding, removing, modifying, retrieving data.

Everything works fine on my visual studio server, but once I'm on the IIS Server:

I can add/retrieve data

I cannot edit data

When I try to edit data I get this error:

System.Data.Services.Client.DataServiceRequestException was unhandled

  Message=Une erreur s'est produite lors du traitement de cette
  requête.

  Source=System.Data.Services.Client

  StackTrace:

  à System.Data.Services.Client.DataServiceContext.SaveResult.HandleBatchResponse()

  à System.Data.Services.Client.DataServiceContext.SaveResult.EndRequest()

  à System.Data.Services.Client.DataServiceContext.SaveChanges(SaveChangesOptions
  options)

  à System.Data.Services.Client.DataServiceContext.SaveChanges()

  à WSTester.Program.ModifySomeThings(Entities entities) dans
  D:\Workspace\10067.GfK

  Telecontrol.TOM\Release\V3.1\WSTester\Program.cs:ligne 90

  à WSTester.Program.Main(String[] args) dans
  D:\Workspace\10067.GfK
  Telecontrol.TOM\Release\V3.1\WSTester\Program.cs:ligne 23

  à System.AppDomain._nExecuteAssembly(RuntimeAssembly
  assembly, String[] args)

  à System.AppDomain.ExecuteAssembly(String assemblyFile,
  Evidence assemblySecurity, String[] args)

  à Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()

  à System.Threading.ThreadHelper.ThreadStart_Context(Object
  state)

  à System.Threading.ExecutionContext.Run(ExecutionContext
  executionContext, ContextCallback callback, Object state, Boolean
  ignoreSyncCtx)

  à System.Threading.ExecutionContext.Run(ExecutionContext
  executionContext, ContextCallback callback, Object state)

  à System.Threading.ThreadHelper.ThreadStart()

  InnerException:

  System.Data.Services.Client.DataServiceClientException

  Message=
  Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

      401 - Unauthorized: Access is denied due to invalid
  credentials.

.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
      -->

Server Error

401 - Unauthorized: Access is denied due to invalid
  credentials.

You do not have permission to view this directory or page
  using the credentials that you supplied.

Source=System.Data.Services.Client

  StatusCode=401

  StackTrace:

  à System.Data.Services.Client.DataServiceContext.SaveResult.d__1e.MoveNext()

  InnerException:

Which is strange, because I've all rights in my WCF Data service(and it works with visual studio), and I'm in anonymous mode in IIS, so I should have all rights to runs this query. IIS_USR has FULL CONTROL on the web folder, so I really don't see what can be the problem

答:
I made it run with a custom user and now it works, so if you have this problem, you can try the following on your IIS Server:

Create a windows user;

Give it read/write/modify/execute/... rights on your WCF data service folder;

Create a new app pool with .NET 4, integrated mode, and this user;

On the authentication of the website, enable only the anonymous mode, and set the user to "Application Pool identity".


问:
function to delete elements selected linked list C
Hi I'm creating a program for school where I have to:

Create structures

Create functions to print my linked list

Create functions to insert an ordered element

Delete elements with a minor year less than the year selected
I created all a part the last one step.
Can you help me to know what is the right way?
This is my code:

STRUCTURE:

```<code>typedef struct dimension {
    int height;
    int length;
} DIMENSION;

typedef struct pic {
    DIMENSION d;
    char name[50];
    int year;
} PIC;

typedef struct node {
    PIC p;
    struct node *next;
} NODE;
</code>```

PRINT LIST:

```<code>void printPic(PIC p) {
    printf("Autor: %s\nDimension\nHeight: %d\nLength: %d\nYear: %d\n", p.name, p.d.height, p.d.length, p.year);
}

void printList(NODE *head) {
    if(head->next==NULL) {
        printf("No element in the list!\n");
    } else {
        while(head->next != NULL) {
            head = head->next;
            printPic(head->p);
        }
    }
}
</code>```

NEW PIC(ORDERED WITH AREA DIMENSION)

```<code>int area(PIC p) {
    return (p.d.height * p.d.length);
}

PIC createPic() {
    PIC newPic;

    printf("Author: ");
    fgets(newPic.name, 50, stdin);
    newPic.name[strlen(newPic.name)-1] = '\0';
    printf("Height: ");
    scanf("%d", &newPic.d.height);
    printf("\n");
    printf("Length: ");
    scanf("%d", &newPic.d.length);
    printf("\n");
    printf("Year: ");
    scanf("%d", &newPic.year);
    printf("\n");
    printf("\n");

    return newPic;

}

void insertPic(NODE *head) {

    NODE* newNode = malloc(sizeof(NODE));
    newNode->p = createPic();
    newNode->next = NULL;

    if(head==NULL) {
        head = newNode;
    } else {
        if(area(newNode->p) < area(head->p)) {
            newNode->next = head;
            head = newNode;
        } else {
            while(head->next != NULL && (area(newNode->p) > area(head->next->p))) {
                head = head->next;
            }
            newNode->next = head->next;
            head->next = newNode;
        }
    }

}
</code>```

DELETE ELEMENTS WITH A MINOR YEAR THAN SELECTED YEAR:

Edited and now it works:

```<code>    void deletePic(NODE *head, int year) {
    if(head==NULL) {
        printf("No element in the list!\n");
    } else {
        while(head->next != NULL) {
            if(head->next->p.year < year) {
                NODE *p = head->next;
                head->next = p->next;
                free(p);
            } else {
                head = head->next;
            }
        }
    }
}
</code>```

MAIN:

```<code>int main() {

    NODE *head = malloc(sizeof(NODE));
    head->next = NULL;
    int choice = -1;

    while(choice != 0) {
        printf("Select an action:\n");
        printf("Press 1 --> See list\n");
        printf("Press 2 --> Insert a new element\n");
        printf("Press 3 --> Delete elements with a minor year\n");
        printf("Press 0 --> Stop program\n");
        scanf("%d%*c", &choice);

        if(choice==1) {
            printList(head);
        }
        else if(choice==2) {
            insertPic(head);
        }
        else if(choice==3) {
            int year;
            printf("Choose an year\nAll elements with a smaller year will be eliminated\n");
            scanf("%d", &year);
            deletePic(head, year);
        }
        else if(choice==0) {
            printf("See you soon ;)\n");
        }
    }

}
</code>```

答:
Your deletePic function is broken in multiple places. Among them:

Dereferencing an indeterminate pointer, yearNode

Incorrect comparator (should use < ; not !=

free'ing an indeterminate pointer.

The first and last of those are a recipe for disaster. If that function does what the menu claims it should, I think what you want is this:

```<code>void deletePic(NODE *head, int year)
{
    if (head == NULL)
    {
        printf("No element in the list!\n");
    }
    else
    {
        while (head->next != NULL)
        {
            if (head->next->p.year < year)
            {
                NODE *p = head->next;
                head->next = p->next;
                free(p);
            }
            else
            {
                head = head->next;
            }
        }
    }
}
</code>```

Body:
Hi I'm creating a program for school where I have to:

Create structures

Create functions to print my linked list

Create functions to insert an ordered element

Delete elements with a minor year less than the year selected
I created all a part the last one step.
Can you help me to know what is the right way?
This is my code:

STRUCTURE:

typedef struct dimension {
    int height;
    int length;
} DIMENSION;

typedef struct pic {
    DIMENSION d;
    char name[50];
    int year;
} PIC;

typedef struct node {
    PIC p;
    struct node *next;
} NODE;

PRINT LIST:

void printPic(PIC p) {
    printf("Autor: %s\nDimension\nHeight: %d\nLength: %d\nYear: %d\n", p.name, p.d.height, p.d.length, p.year);
}

void printList(NODE *head) {
    if(head->next==NULL) {
        printf("No element in the list!\n");
    } else {
        while(head->next != NULL) {
            head = head->next;
            printPic(head->p);
        }
    }
}

NEW PIC(ORDERED WITH AREA DIMENSION)

int area(PIC p) {
    return (p.d.height * p.d.length);
}

PIC createPic() {
    PIC newPic;

    printf("Author: ");
    fgets(newPic.name, 50, stdin);
    newPic.name[strlen(newPic.name)-1] = '\0';
    printf("Height: ");
    scanf("%d", &newPic.d.height);
    printf("\n");
    printf("Length: ");
    scanf("%d", &newPic.d.length);
    printf("\n");
    printf("Year: ");
    scanf("%d", &newPic.year);
    printf("\n");
    printf("\n");

    return newPic;

}

void insertPic(NODE *head) {

    NODE* newNode = malloc(sizeof(NODE));
    newNode->p = createPic();
    newNode->next = NULL;

    if(head==NULL) {
        head = newNode;
    } else {
        if(area(newNode->p) < area(head->p)) {
            newNode->next = head;
            head = newNode;
        } else {
            while(head->next != NULL && (area(newNode->p) > area(head->next->p))) {
                head = head->next;
            }
            newNode->next = head->next;
            head->next = newNode;
        }
    }

}

DELETE ELEMENTS WITH A MINOR YEAR THAN SELECTED YEAR:

Edited and now it works:

    void deletePic(NODE *head, int year) {
    if(head==NULL) {
        printf("No element in the list!\n");
    } else {
        while(head->next != NULL) {
            if(head->next->p.year < year) {
                NODE *p = head->next;
                head->next = p->next;
                free(p);
            } else {
                head = head->next;
            }
        }
    }
}

MAIN:

int main() {

    NODE *head = malloc(sizeof(NODE));
    head->next = NULL;
    int choice = -1;

    while(choice != 0) {
        printf("Select an action:\n");
        printf("Press 1 --> See list\n");
        printf("Press 2 --> Insert a new element\n");
        printf("Press 3 --> Delete elements with a minor year\n");
        printf("Press 0 --> Stop program\n");
        scanf("%d%*c", &choice);

        if(choice==1) {
            printList(head);
        }
        else if(choice==2) {
            insertPic(head);
        }
        else if(choice==3) {
            int year;
            printf("Choose an year\nAll elements with a smaller year will be eliminated\n");
            scanf("%d", &year);
            deletePic(head, year);
        }
        else if(choice==0) {
            printf("See you soon ;)\n");
        }
    }

}

Body:
Your deletePic function is broken in multiple places. Among them:

Dereferencing an indeterminate pointer, yearNode

Incorrect comparator (should use < ; not !=

free'ing an indeterminate pointer.

The first and last of those are a recipe for disaster. If that function does what the menu claims it should, I think what you want is this:

void deletePic(NODE *head, int year)
{
    if (head == NULL)
    {
        printf("No element in the list!\n");
    }
    else
    {
        while (head->next != NULL)
        {
            if (head->next->p.year < year)
            {
                NODE *p = head->next;
                head->next = p->next;
                free(p);
            }
            else
            {
                head = head->next;
            }
        }
    }
}


问:
Looking up a deactivated widget's ancestor is unsafe
I am new in Flutter and I am trying receive data with a Dialog.
When a click in textField the error of image2 appear...

```<code>show(BuildContext context){

    var dialog = Dialog(
      child: Container(
        margin: EdgeInsets.all(8.0),
        child: Form(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              TextFormField(
                decoration: InputDecoration(
                    labelText: "Insira o número de telefone",
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(2.0)))),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  FlatButton(
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                      child: Text("Cancelar")),
                  FlatButton(
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                      child: Text("Aceitar"))
                ],
              )
            ],
          ),
        ),
      ),
    );

    showDialog(context: context,builder: (context){
      return dialog;
    });
  }
</code>```

This is my code.

```<code>I/flutter (31032): Looking up a deactivated widget's ancestor is unsafe.
I/flutter (31032): At this point the state of the widget's element tree is no longer stable. To safely refer to a
I/flutter (31032): widget's ancestor in its dispose() method, save a reference to the ancestor by calling
I/flutter (31032): inheritFromWidgetOfExactType() in the widget's didChangeDependencies() method.
I/flutter (31032):
</code>```

答:
declare dialog and set in initState

```<code>  late Dialog dialog;

  @override
  void initState() {
    super.initState();

    dialog = Dialog(
      ...
    );
  }
</code>```

Body:
I am new in Flutter and I am trying receive data with a Dialog.
When a click in textField the error of image2 appear...

show(BuildContext context){

    var dialog = Dialog(
      child: Container(
        margin: EdgeInsets.all(8.0),
        child: Form(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              TextFormField(
                decoration: InputDecoration(
                    labelText: "Insira o número de telefone",
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(2.0)))),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  FlatButton(
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                      child: Text("Cancelar")),
                  FlatButton(
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                      child: Text("Aceitar"))
                ],
              )
            ],
          ),
        ),
      ),
    );

    showDialog(context: context,builder: (context){
      return dialog;
    });
  }

This is my code.

I/flutter (31032): Looking up a deactivated widget's ancestor is unsafe.
I/flutter (31032): At this point the state of the widget's element tree is no longer stable. To safely refer to a
I/flutter (31032): widget's ancestor in its dispose() method, save a reference to the ancestor by calling
I/flutter (31032): inheritFromWidgetOfExactType() in the widget's didChangeDependencies() method.
I/flutter (31032):

Body:
declare dialog and set in initState

  late Dialog dialog;

  @override
  void initState() {
    super.initState();

    dialog = Dialog(
      ...
    );
  }


问:
NSMutableArray Init troubles
I have this method dealing with a couple array that I can't seem to get right.  Something related to the alloc and init.  </p>

```<code>- (void)addBookmark
{
    // Get the user defaults object
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    // Load your bookmarks (editable array)
    NSMutableArray *bookmarks = [[NSMutableArray alloc]init];
    NSArray *bookmarksLoaded = [userDefaults arrayForKey:@"bookmarks"];
    if (bookmarksLoaded != nil) {
        [bookmarks initWithArray:bookmarksLoaded];
    } else {
        [bookmarks init];
    }

    // Add a bookmark
    NSMutableDictionary *bookmark = [NSMutableDictionary new];
    [bookmark setValue:@"value" forKey:@"name"];
    [bookmark setValue:@"value" forKey:@"description"];
    [bookmark setValue:@"value" forKey:@"code"];
    [bookmarks addObject:bookmark];

    // Save your (updated) bookmarks
    [userDefaults setObject:bookmarks forKey:@"bookmarks"];
    [userDefaults synchronize];

    // Memory cleanup
    [bookmarks release];
}
</code>```

答:
You're right - it is your use of alloc/init. You should only init an object once. You want something like this:

```<code>// Load your bookmarks (editable array)
NSMutableArray *bookmarks = nil; // we'll initialize it later
NSArray *bookmarksLoaded = [userDefaults arrayForKey:@"bookmarks"];
if (bookmarksLoaded) { // shortcut for bookmarksLoaded != nil
    bookmarks = [[NSMutableArray alloc] initWithArray:bookmarksLoaded];
} else {
    bookmarks = [[NSMutableArray alloc] init];
}

// Add a bookmark
NSMutableDictionary *bookmark = [NSMutableDictionary dictionary];
</code>```

If you use dictionary instead of new, you get an autoreleased object that you don't have to worry about (new isn't used in Cocoa). As you have it, you're leaking memory.

Title: NSMutableArray Init troubles

Body:
I have this method dealing with a couple array that I can't seem to get right.  Something related to the alloc and init.

- (void)addBookmark
{
    // Get the user defaults object
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    // Load your bookmarks (editable array)
    NSMutableArray *bookmarks = [[NSMutableArray alloc]init];
    NSArray *bookmarksLoaded = [userDefaults arrayForKey:@"bookmarks"];
    if (bookmarksLoaded != nil) {
        [bookmarks initWithArray:bookmarksLoaded];
    } else {
        [bookmarks init];
    }

    // Add a bookmark
    NSMutableDictionary *bookmark = [NSMutableDictionary new];
    [bookmark setValue:@"value" forKey:@"name"];
    [bookmark setValue:@"value" forKey:@"description"];
    [bookmark setValue:@"value" forKey:@"code"];
    [bookmarks addObject:bookmark];

    // Save your (updated) bookmarks
    [userDefaults setObject:bookmarks forKey:@"bookmarks"];
    [userDefaults synchronize];

    // Memory cleanup
    [bookmarks release];
}

Body:
You're right - it is your use of alloc/init. You should only init an object once. You want something like this:

// Load your bookmarks (editable array)
NSMutableArray *bookmarks = nil; // we'll initialize it later
NSArray *bookmarksLoaded = [userDefaults arrayForKey:@"bookmarks"];
if (bookmarksLoaded) { // shortcut for bookmarksLoaded != nil
    bookmarks = [[NSMutableArray alloc] initWithArray:bookmarksLoaded];
} else {
    bookmarks = [[NSMutableArray alloc] init];
}

// Add a bookmark
NSMutableDictionary *bookmark = [NSMutableDictionary dictionary];

If you use dictionary instead of new, you get an autoreleased object that you don't have to worry about (new isn't used in Cocoa). As you have it, you're leaking memory.


问:
How to configure gce to route paths (rewrite-target in Nginx)
I had a Kibana that was previously running behind the NGINX ingress controller using this Ingress configuration:

```<code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: es-kibana-ing
  annotations:
    nginx.ingress.kubernetes.io/backend-protocol: HTTPS
    nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
  rules:
    - host: "example.com"
      http:
        paths:
          - path: /kibana(/|$)(.*)
            pathType: Prefix
            backend:
              serviceName: es-kibana-svc
              servicePort: 443
  tls:
    - hosts:
      - example.com
      secretName: example-tls
</code>```

With this configuration you had to go to www.example.com/kibana to access the kibana.
Since then we migrated to GCP and now I'm trying to achieve the same using the GCE ingress controller. For now I figured how to serve the kibana on path "/*" :

```<code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: es-kibana-ing
  annotations:
    kubernetes.io/ingress.class: gce
    kubernetes.io/ingress.global-static-ip-name: kibana-static-ip
    networking.gke.io/managed-certificates: managed-cert
spec:
  rules:
    - host: "example.com"
      http:
        paths:
          - path: /*
            pathType: ImplementationSpecific
            backend:
              service:
                name: es-kibana-svc
                port:
                  number: 443
</code>```

Instead I would like to serve the Kibana on the /kibana (as in the previous Nginx configuration), but I can't find an equivalent to rewrite-target for the gce controller. Any idea how this can be done?

答:
If I understand what you want to achieve, you cannot do this using GCE Ingress, you would need to enforce Nginx Ingress.

Rewrite behavior of Nginx Ingress cannot be replicated by GCE Ingress. As I mentioned in the comment section, Nginx Ingress contains much more features than GCE Ingress, for example rewrite/capture groups or service type requirement (NodePort in GCE, ClusterIP or NodePort in Nginx).

With GCE Ingress you can achieve some static path rules like in this example. Something like that:

```<code>  rules:
    - http:
        paths:
        - path: /hello
          backend:
            serviceName: hello-svc
            servicePort: 8080
        - path: /hello-v2
          backend:
            serviceName: hello-v2-svc
            servicePort: 8080
        - path: /kibana
          backend:
            serviceName: kibana
            servicePort: 443
        - path: /randomsvc
          backend:
            serviceName: randomsvc
            servicePort: 8080
</code>```

However, as I understand by your comment:

I just want to replicate the behavior that I described for Nginx Ingress, that was allowing me to access my application through '/kibana' using the rewrite-target feature.

Rewrite behavior is specific which cannot be replicated on GCE Ingress. There is a request to add a rewrite feature to GCE Ingress since 2018 but it's still open. More details about it you can find here.

You can find some differences between both Ingress in this guide.

Body:
I had a Kibana that was previously running behind the NGINX ingress controller using this Ingress configuration:

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: es-kibana-ing
  annotations:
    nginx.ingress.kubernetes.io/backend-protocol: HTTPS
    nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
  rules:
    - host: "example.com"
      http:
        paths:
          - path: /kibana(/|$)(.*)
            pathType: Prefix
            backend:
              serviceName: es-kibana-svc
              servicePort: 443
  tls:
    - hosts:
      - example.com
      secretName: example-tls

With this configuration you had to go to www.example.com/kibana to access the kibana.
Since then we migrated to GCP and now I'm trying to achieve the same using the GCE ingress controller. For now I figured how to serve the kibana on path "/*" :

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: es-kibana-ing
  annotations:
    kubernetes.io/ingress.class: gce
    kubernetes.io/ingress.global-static-ip-name: kibana-static-ip
    networking.gke.io/managed-certificates: managed-cert
spec:
  rules:
    - host: "example.com"
      http:
        paths:
          - path: /*
            pathType: ImplementationSpecific
            backend:
              service:
                name: es-kibana-svc
                port:
                  number: 443

Instead I would like to serve the Kibana on the /kibana (as in the previous Nginx configuration), but I can't find an equivalent to rewrite-target for the gce controller. Any idea how this can be done?

Body:
If I understand what you want to achieve, you cannot do this using GCE Ingress, you would need to enforce Nginx Ingress.

Rewrite behavior of Nginx Ingress cannot be replicated by GCE Ingress. As I mentioned in the comment section, Nginx Ingress contains much more features than GCE Ingress, for example rewrite/capture groups or service type requirement (NodePort in GCE, ClusterIP or NodePort in Nginx).

With GCE Ingress you can achieve some static path rules like in this example. Something like that:

  rules:
    - http:
        paths:
        - path: /hello
          backend:
            serviceName: hello-svc
            servicePort: 8080
        - path: /hello-v2
          backend:
            serviceName: hello-v2-svc
            servicePort: 8080
        - path: /kibana
          backend:
            serviceName: kibana
            servicePort: 443
        - path: /randomsvc
          backend:
            serviceName: randomsvc
            servicePort: 8080

However, as I understand by your comment:

I just want to replicate the behavior that I described for Nginx Ingress, that was allowing me to access my application through '/kibana' using the rewrite-target feature.

Rewrite behavior is specific which cannot be replicated on GCE Ingress. There is a request to add a rewrite feature to GCE Ingress since 2018 but it's still open. More details about it you can find here.

You can find some differences between both Ingress in this guide.


问:
Retrieve auto-gen id value after SQL Insert in ColdFusion
I've seen similar questions asked here many times but none pertaining to ColdFusion. Based on some of the answers, this is the code I'm trying to run:

```<code><cfquery name="getTest" datasource="POW" result="result">
    INSERT INTO myStuff (Stuff)
    VALUES ('My test 3')
</cfquery>
<cfdump var="#result#" >
</code>```

and this is what I get:

```<code>struct

CACHED  false

EXECUTIONTIME   47

RECORDCOUNT 1

SQL INSERT INTO myStuff (Stuff) VALUES ('My test 3')
</code>```

If I switch to result = result.GeneratedKey, I get a new column headed Generated Key but with no values inside.

I'd appreciate any help anyone can give.

答:
Unfortunately you've run into one of the downsides of using an unsupported desktop database like MS Access. It's going to lack some of the more advanced features. In part, due to limitations of MS Access itself, but also due to Adobe dropping support it. A better path going forward is upgrading to a database that is more robust and designed for web app concurrency, like SQL Server. If that's not an option for now you're stuck with less ideal solutions...

Don't use SELECT MAX(ID)

As you already guessed, one thing that's not an option is using select max(ID). It's not thread safe so you're NOT guaranteed to get back the ID of the record you just inserted. Bottom line, don't use it.

Possible Option

Before the CF 8 introduced the result attribute, a typical approach was to append use a dbms specific function to return the newly generated ID after the insert. For example, with SQL Server:

```<code> <cfquery name="qInsert" ....>
    INSERT INTO SomeTable (....)
    VALUES (...)
    SELECT SCOPE_IDENTITY() AS GeneratedIDValue
 </cfquery>
</code>```

IIRC Access has something similar: @@IDENTITY. AFAIK, it's specific to the current database connection so it should be thread safe. Unfortunately Access doesn't support executing multiple statements in the same cfquery. At least not the last time I checked. So you'll probably need to use two cfquery's. You must wrap the two queries in a transaction to ensure they both use the same database connection/session:

```<code> <cftransaction>
    <cfquery ....>
       INSERT INTO SomeTable (....)
       VALUES (...)
       SELECT SCOPE_IDENTITY() AS GeneratedIDValue
    </cfquery>
    <cfquery name="qInsert" ....>
        SELECT @@IDENTITY AS GeneratedIDValue
    </cfquery>
 </cftransaction>

 <cfoutput>
 Generated ID: #qInsert.GeneratedIDValue#
 </cfoutput>
</code>```

Body:
I've seen similar questions asked here many times but none pertaining to ColdFusion. Based on some of the answers, this is the code I'm trying to run:

<cfquery name="getTest" datasource="POW" result="result">
    INSERT INTO myStuff (Stuff)
    VALUES ('My test 3')
</cfquery>
<cfdump var="#result#" >

and this is what I get:

struct

CACHED  false

EXECUTIONTIME   47

RECORDCOUNT 1

SQL INSERT INTO myStuff (Stuff) VALUES ('My test 3')

If I switch to result = result.GeneratedKey, I get a new column headed Generated Key but with no values inside.

I'd appreciate any help anyone can give.

Body:
Unfortunately you've run into one of the downsides of using an unsupported desktop database like MS Access. It's going to lack some of the more advanced features. In part, due to limitations of MS Access itself, but also due to Adobe dropping support it. A better path going forward is upgrading to a database that is more robust and designed for web app concurrency, like SQL Server. If that's not an option for now you're stuck with less ideal solutions...

Don't use SELECT MAX(ID)

As you already guessed, one thing that's not an option is using select max(ID). It's not thread safe so you're NOT guaranteed to get back the ID of the record you just inserted. Bottom line, don't use it.

Possible Option

Before the CF 8 introduced the result attribute, a typical approach was to append use a dbms specific function to return the newly generated ID after the insert. For example, with SQL Server:

 <cfquery name="qInsert" ....>
    INSERT INTO SomeTable (....)
    VALUES (...)
    SELECT SCOPE_IDENTITY() AS GeneratedIDValue
 </cfquery>

IIRC Access has something similar: @@IDENTITY. AFAIK, it's specific to the current database connection so it should be thread safe. Unfortunately Access doesn't support executing multiple statements in the same cfquery. At least not the last time I checked. So you'll probably need to use two cfquery's. You must wrap the two queries in a transaction to ensure they both use the same database connection/session:

 <cftransaction>
    <cfquery ....>
       INSERT INTO SomeTable (....)
       VALUES (...)
       SELECT SCOPE_IDENTITY() AS GeneratedIDValue
    </cfquery>
    <cfquery name="qInsert" ....>
        SELECT @@IDENTITY AS GeneratedIDValue
    </cfquery>
 </cftransaction>

 <cfoutput>
 Generated ID: #qInsert.GeneratedIDValue#
 </cfoutput>


问:
Telegram Bot Null Pointer Exception when executing Firestore methods
I am currently trying to validate user text submissions by querying them in Firestore first before sending them a reply. This is done using Firebase Admin SDK and https://github.com/rubenlagus/TelegramBots. Problem is that when accessing the methods that interact with Firestore (verifyValidUserAndOrganisation), the method doesn't execute yet the object is not null when I checked in debugger.

I am not sure what is the error and if there is, please suggest any other ways to validate with an asynchronous Firestore database read.

Function in question:

```<code>@NotNull
private Predicate<Update> validUserAndOrganisation() {
    return upd -> {
        String message = upd.getMessage().getText().trim();
        // Need to check both user telegram id and organisation code valid
        // Then proceed with allowing next reply, else need to throw message and stop ability
        if (message.length() == 6) { // Only proceed if length of text is valid for an org. code
            if (isValidOrganisationCode(message)) { // Additional check for text being valid organisation code regex to reduce unnecessary Firestore reads.
                // Check firebase
                try {
                    Verification verification = firebaseDB.verifyValidUserAndOrganisation(upd.getChatMember().getFrom().getId(), message); // <---- Here
                    if (verification.getSuccess()) {
                        return true;
                    } else {
                        silent.send(verification.getReason(), getChatId(upd)); // Will submit false afterwards to signify failing the check
                        return false;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else if (message.length() > 0 && !message.equals("/submit")) {
            silent.send("Please enter a valid organisation code", getChatId(upd));
        }
        return false;
    };
}
</code>```

Error logs:

```<code>[MyCelsiusBot Telegram Executor] INFO org.telegram.abilitybots.api.bot.BaseAbilityBot - [MyCelsiusBot] New update [41791280] received at 2022-02-07T00:31:52.469791300+08:00[Asia/Singapore]
[MyCelsiusBot Telegram Executor] INFO org.telegram.abilitybots.api.bot.BaseAbilityBot - Update(updateId=41791280, message=Message(messageId=163, from=User(id=5003829958, firstName=Kez, isBot=false, lastName=null, userName=Kzeezee, languageCode=en, canJoinGroups=null, canReadAllGroupMessages=null, supportInlineQueries=null), date=1644165113, chat=Chat(id=5003829958, type=private, title=null, firstName=Kez, lastName=null, userName=Kzeezee, allMembersAreAdministrators=null, photo=null, description=null, inviteLink=null, pinnedMessage=null, stickerSetName=null, canSetStickerSet=null, permissions=null, slowModeDelay=null, bio=null, linkedChatId=null, location=null, messageAutoDeleteTime=null, allowSavingContent=null, hasPrivateForwards=null), forwardFrom=null, forwardFromChat=null, forwardDate=null, text=Hhhhhh, entities=null, captionEntities=null, audio=null, document=null, photo=null, sticker=null, video=null, contact=null, location=null, venue=null, animation=null, pinnedMessage=null, newChatMembers=[], leftChatMember=null, newChatTitle=null, newChatPhoto=null, deleteChatPhoto=null, groupchatCreated=null, replyToMessage=null, voice=null, caption=null, superGroupCreated=null, channelChatCreated=null, migrateToChatId=null, migrateFromChatId=null, editDate=null, game=null, forwardFromMessageId=null, invoice=null, successfulPayment=null, videoNote=null, authorSignature=null, forwardSignature=null, mediaGroupId=null, connectedWebsite=null, passportData=null, forwardSenderName=null, poll=null, replyMarkup=null, dice=null, viaBot=null, senderChat=null, proximityAlertTriggered=null, messageAutoDeleteTimerChanged=null, voiceChatStarted=null, voiceChatEnded=null, voiceChatParticipantsInvited=null, voiceChatScheduled=null, isAutomaticForward=null, canBeForwarded=null), inlineQuery=null, chosenInlineQuery=null, callbackQuery=null, editedMessage=null, channelPost=null, editedChannelPost=null, shippingQuery=null, preCheckoutQuery=null, poll=null, pollAnswer=null, myChatMember=null, chatMember=null, chatJoinRequest=null)
java.lang.NullPointerException
    at bot.MyCelsiusTelegramBot.lambda$validUserAndOrganisation$12(MyCelsiusTelegramBot.java:145)
    at org.telegram.abilitybots.api.objects.Reply.lambda$isOkFor$1(Reply.java:97)
    at java.base/java.util.stream.ReduceOps$1ReducingSink.accept(ReduceOps.java:80)
    at java.base/java.util.AbstractList$RandomAccessSpliterator.forEachRemaining(AbstractList.java:720)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.reduce(ReferencePipeline.java:563)
    at org.telegram.abilitybots.api.objects.Reply.isOkFor(Reply.java:98)
    at org.telegram.abilitybots.api.bot.BaseAbilityBot.lambda$filterReply$22(BaseAbilityBot.java:663)
    at org.telegram.abilitybots.api.bot.BaseAbilityBot.runSilently(BaseAbilityBot.java:674)
    at org.telegram.abilitybots.api.bot.BaseAbilityBot.lambda$filterReply$23(BaseAbilityBot.java:663)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:176)
    at java.base/java.util.AbstractList$RandomAccessSpliterator.forEachRemaining(AbstractList.java:720)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.reduce(ReferencePipeline.java:553)
    at org.telegram.abilitybots.api.bot.BaseAbilityBot.filterReply(BaseAbilityBot.java:669)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:176)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
    at java.base/java.util.stream.Streams$StreamBuilderImpl.forEachRemaining(Streams.java:411)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at org.telegram.abilitybots.api.bot.BaseAbilityBot.onUpdateReceived(BaseAbilityBot.java:234)
    at org.telegram.abilitybots.api.bot.AbilityBot.onUpdateReceived(AbilityBot.java:55)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.telegram.telegrambots.meta.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
    at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:317)
[MyCelsiusBot Telegram Executor] INFO org.telegram.abilitybots.api.bot.BaseAbilityBot - [MyCelsiusBot] Processing of update [41791280] ended at 2022-02-07T00:31:52.547348100+08:00[Asia/Singapore]
---> Processing time: [77 ms] <---
</code>```

I also have the entire project at https://github.com/Kzeezee/MyCelsius if information is insufficient.

答:
With the help of @LukeWoodward, I did find my mistake and that upd.getChatMember() was the one responsible for giving me the null pointer exception.

upd.getChatMember() will be null if the messages are coming from direct DMs in Telegram and not from group chats. For that, you need to use upd.getMessage().getFrom().getId() for getting the user's id who direct messaged your bot.

Body:
I am currently trying to validate user text submissions by querying them in Firestore first before sending them a reply. This is done using Firebase Admin SDK and https://github.com/rubenlagus/TelegramBots. Problem is that when accessing the methods that interact with Firestore (verifyValidUserAndOrganisation), the method doesn't execute yet the object is not null when I checked in debugger.

I am not sure what is the error and if there is, please suggest any other ways to validate with an asynchronous Firestore database read.

Function in question:

@NotNull
private Predicate<Update> validUserAndOrganisation() {
    return upd -> {
        String message = upd.getMessage().getText().trim();
        // Need to check both user telegram id and organisation code valid
        // Then proceed with allowing next reply, else need to throw message and stop ability
        if (message.length() == 6) { // Only proceed if length of text is valid for an org. code
            if (isValidOrganisationCode(message)) { // Additional check for text being valid organisation code regex to reduce unnecessary Firestore reads.
                // Check firebase
                try {
                    Verification verification = firebaseDB.verifyValidUserAndOrganisation(upd.getChatMember().getFrom().getId(), message); // <---- Here
                    if (verification.getSuccess()) {
                        return true;
                    } else {
                        silent.send(verification.getReason(), getChatId(upd)); // Will submit false afterwards to signify failing the check
                        return false;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else if (message.length() > 0 && !message.equals("/submit")) {
            silent.send("Please enter a valid organisation code", getChatId(upd));
        }
        return false;
    };
}

Error logs:

[MyCelsiusBot Telegram Executor] INFO org.telegram.abilitybots.api.bot.BaseAbilityBot - [MyCelsiusBot] New update [41791280] received at 2022-02-07T00:31:52.469791300+08:00[Asia/Singapore]
[MyCelsiusBot Telegram Executor] INFO org.telegram.abilitybots.api.bot.BaseAbilityBot - Update(updateId=41791280, message=Message(messageId=163, from=User(id=5003829958, firstName=Kez, isBot=false, lastName=null, userName=Kzeezee, languageCode=en, canJoinGroups=null, canReadAllGroupMessages=null, supportInlineQueries=null), date=1644165113, chat=Chat(id=5003829958, type=private, title=null, firstName=Kez, lastName=null, userName=Kzeezee, allMembersAreAdministrators=null, photo=null, description=null, inviteLink=null, pinnedMessage=null, stickerSetName=null, canSetStickerSet=null, permissions=null, slowModeDelay=null, bio=null, linkedChatId=null, location=null, messageAutoDeleteTime=null, allowSavingContent=null, hasPrivateForwards=null), forwardFrom=null, forwardFromChat=null, forwardDate=null, text=Hhhhhh, entities=null, captionEntities=null, audio=null, document=null, photo=null, sticker=null, video=null, contact=null, location=null, venue=null, animation=null, pinnedMessage=null, newChatMembers=[], leftChatMember=null, newChatTitle=null, newChatPhoto=null, deleteChatPhoto=null, groupchatCreated=null, replyToMessage=null, voice=null, caption=null, superGroupCreated=null, channelChatCreated=null, migrateToChatId=null, migrateFromChatId=null, editDate=null, game=null, forwardFromMessageId=null, invoice=null, successfulPayment=null, videoNote=null, authorSignature=null, forwardSignature=null, mediaGroupId=null, connectedWebsite=null, passportData=null, forwardSenderName=null, poll=null, replyMarkup=null, dice=null, viaBot=null, senderChat=null, proximityAlertTriggered=null, messageAutoDeleteTimerChanged=null, voiceChatStarted=null, voiceChatEnded=null, voiceChatParticipantsInvited=null, voiceChatScheduled=null, isAutomaticForward=null, canBeForwarded=null), inlineQuery=null, chosenInlineQuery=null, callbackQuery=null, editedMessage=null, channelPost=null, editedChannelPost=null, shippingQuery=null, preCheckoutQuery=null, poll=null, pollAnswer=null, myChatMember=null, chatMember=null, chatJoinRequest=null)
java.lang.NullPointerException
    at bot.MyCelsiusTelegramBot.lambda$validUserAndOrganisation$12(MyCelsiusTelegramBot.java:145)
    at org.telegram.abilitybots.api.objects.Reply.lambda$isOkFor$1(Reply.java:97)
    at java.base/java.util.stream.ReduceOps$1ReducingSink.accept(ReduceOps.java:80)
    at java.base/java.util.AbstractList$RandomAccessSpliterator.forEachRemaining(AbstractList.java:720)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.reduce(ReferencePipeline.java:563)
    at org.telegram.abilitybots.api.objects.Reply.isOkFor(Reply.java:98)
    at org.telegram.abilitybots.api.bot.BaseAbilityBot.lambda$filterReply$22(BaseAbilityBot.java:663)
    at org.telegram.abilitybots.api.bot.BaseAbilityBot.runSilently(BaseAbilityBot.java:674)
    at org.telegram.abilitybots.api.bot.BaseAbilityBot.lambda$filterReply$23(BaseAbilityBot.java:663)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:176)
    at java.base/java.util.AbstractList$RandomAccessSpliterator.forEachRemaining(AbstractList.java:720)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.reduce(ReferencePipeline.java:553)
    at org.telegram.abilitybots.api.bot.BaseAbilityBot.filterReply(BaseAbilityBot.java:669)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:176)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
    at java.base/java.util.stream.Streams$StreamBuilderImpl.forEachRemaining(Streams.java:411)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at org.telegram.abilitybots.api.bot.BaseAbilityBot.onUpdateReceived(BaseAbilityBot.java:234)
    at org.telegram.abilitybots.api.bot.AbilityBot.onUpdateReceived(AbilityBot.java:55)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.telegram.telegrambots.meta.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
    at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:317)
[MyCelsiusBot Telegram Executor] INFO org.telegram.abilitybots.api.bot.BaseAbilityBot - [MyCelsiusBot] Processing of update [41791280] ended at 2022-02-07T00:31:52.547348100+08:00[Asia/Singapore]
---> Processing time: [77 ms] <---

I also have the entire project at https://github.com/Kzeezee/MyCelsius if information is insufficient.


问:
Trying to fit image inside a flex box in CSS
This is how I want the page to split, so that I can have a fluid layout.

```<code><div class="container">
  <div class="top">Top</div>
  <div class="image">image</div>
  <div class="footer">footer</div>
</div>

.container{
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
}

.top {
  flex: 25%;
  width: 100%;
  background-color: red;
}

.image {
  flex: 50%;
  width: 100%;
  background-color: green;
}

.footer{
  flex: 25%;
  width: 100%;
  background-color:blue;
}
</code>```

https://jsfiddle.net/9n7zmr60/

In the image section, I wanna insert an image and I want it to fit in the same ratio (25% 50% 25%) as above. However, when I try, its getting stretched like below:

```<code>.container{
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
}

.top {
  flex: 25%;
  width: 100%;
  background-color: red;
}

.image {
  flex: 50%;
  width: 100%;
  background-color: green;
  max-width: 100%;
  object-fit: contain;

}

.footer{
  flex: 25%;
  width: 100%;
  background-color:blue;
}
</code>```

https://jsfiddle.net/qcnwu7fe/

Please help

答:
Do this changes:

```<code>.image {
  flex: 50%; /*delete this*/
  height: 50%;
  width: 100%;
  background-color: green;
}
img{
  height: 100%;
  width: 100%;
}
</code>```

.container {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
}

.top {
  flex: 25%;
  width: 100%;
  background-color: red;
}

img {
  height: 100%;
  width: 100%;
}

.image {
  width: 100%;
  background-color: green;
  height: 50%;
}

.footer {
  flex: 25%;
  width: 100%;
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="top">Top</div>
  <div class="image"><img src="https://static1.momsimage.com/wordpress/wp-content/uploads/2019/08/Kids-cartoons.jpg" alt=""></div>
  <div class="footer">footer</div>
</div></code>```

Body:
This is how I want the page to split, so that I can have a fluid layout.

Top

image

footer

.container{
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
}

.top {
  flex: 25%;
  width: 100%;
  background-color: red;
}

.image {
  flex: 50%;
  width: 100%;
  background-color: green;
}

.footer{
  flex: 25%;
  width: 100%;
  background-color:blue;
}

https://jsfiddle.net/9n7zmr60/

In the image section, I wanna insert an image and I want it to fit in the same ratio (25% 50% 25%) as above. However, when I try, its getting stretched like below:

.container{
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
}

.top {
  flex: 25%;
  width: 100%;
  background-color: red;
}

.image {
  flex: 50%;
  width: 100%;
  background-color: green;
  max-width: 100%;
  object-fit: contain;

}

.footer{
  flex: 25%;
  width: 100%;
  background-color:blue;
}

https://jsfiddle.net/qcnwu7fe/

Please help

Body:
Do this changes:

.image {
  flex: 50%; /*delete this*/
  height: 50%;
  width: 100%;
  background-color: green;
}
img{
  height: 100%;
  width: 100%;
}

.container {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
}

.top {
  flex: 25%;
  width: 100%;
  background-color: red;
}

img {
  height: 100%;
  width: 100%;
}

.image {
  width: 100%;
  background-color: green;
  height: 50%;
}

.footer {
  flex: 25%;
  width: 100%;
  background-color: blue;
}

<div class="container">
  <div class="top">Top</div>
  <div class="image"><img src="https://static1.momsimage.com/wordpress/wp-content/uploads/2019/08/Kids-cartoons.jpg" alt=""></div>
  <div class="footer">footer</div>
</div>


问:
How to load tab items dynamically in Vuejs?
AppsTab.vue

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>
  <div
    :class="{
      'flex space-x-4': variant === 'horizontal',
    }"
  >
    <ul
      class="list-none bg-blue-900 bg-opacity-30 p-1.5 rounded-lg text-center overflow-auto whitespace-nowrap"
      :class="{
        'flex items-center mb-6': variant === 'vertical',
      }"
    >
      <li
        v-for="(tab, index) in tabList"
        :key="index"
        class="w-full px-4 py-1.5 rounded-lg"
        :class="{
          'text-blue-600 bg-white shadow-xl': index + 1 === activeTab,
          'text-white': index + 1 !== activeTab,
        }"
      >
        <label
          :for="`${_uid}${index}`"
          v-text="tab"
          class="cursor-pointer block"
        />
        <input
          :id="`${_uid}${index}`"
          type="radio"
          :name="`${_uid}-tab`"
          :value="index + 1"
          v-model="activeTab"
          class="hidden"
        />
      </li>
    </ul>
    <template v-for="(tab, index) in tabList">
      <div
        :key="index"
        v-if="index + 1 === activeTab"
        class="flex-grow bg-white rounded-lg shadow-xl p-4"
      >
        <!-- <slot :name="`tabPanel-${index + 1}`" /> --> want to get data using loop inside tab
      </div>
    </template>
  </div>
</template></code>```

App.vue

< script >
  import AppTabs from "./components/AppTabs";

export default {
  components: {
    AppTabs,
  },
  data() {
    return {
      tabList: ["Tab 1", "Tab 2", "Tab 3", "Tab 4"],
    };
  },
}; <
/script>```
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>
  <div class="bg-gradient-to-r from-blue-300 to-blue-500 min-h-screen">
    <app-tabs
      class="w-11/12 lg:w-10/12 mx-auto"
      :tabList="tabList"
      variant="horizontal"
    >
{{value}} // want to bind data inside tab
    </app-tabs>
  </div>
</template></code>```

Expected Output

I am working on vertical tabs. Where the functionality is working fine. Here is the complete working code with static mock data https://codesandbox.io/s/vue-js-tabs-forked-we2cx?file=/src/App.vue

Now i want to create some mockdata inside of my data like 'tabList' and then, i want to display data dynamically when user clicked on tabs(including content -->tabs)

How to remove static data, which is inside slots and then only use data dynamically

To start with that, i am not sure, Where to start the looping to display data inside tabs dynamically with mock data?

答:
You can set dynamic slot name using :slot="slotName" where slotName is a dynamic value

This can be achieved using a v-for aswell like below.

```<code><template v-for="content in contentList" :slot="content.slot">
  {{ content.content }}
</template>
</code>```

Where contentList is your array something like below.

```<code>contentList: [
  { id: 1, slot: "tabPanel-1", content: "Content 1" },
  { id: 2, slot: "tabPanel-2", content: "Content 2" },
  { id: 3, slot: "tabPanel-3", content: "Content 3" },
  { id: 4, slot: "tabPanel-4", content: "Content 4" },
]
</code>```

Working Fiddle

Body:
AppsTab.vue

<template>

        <label
          :for="`${_uid}${index}`"
          v-text="tab"
          class="cursor-pointer block"
        />
        <input
          :id="`${_uid}${index}`"
          type="radio"
          :name="`${_uid}-tab`"
          :value="index + 1"
          v-model="activeTab"
          class="hidden"
        />

    <template v-for="(tab, index) in tabList">

         want to get data using loop inside tab

    </template>

</template>

App.vue

< script >
  import AppTabs from "./components/AppTabs";

export default {
  components: {
    AppTabs,
  },
  data() {
    return {
      tabList: ["Tab 1", "Tab 2", "Tab 3", "Tab 4"],
    };
  },
}; <
/script>

<template>

    <app-tabs
      class="w-11/12 lg:w-10/12 mx-auto"
      :tabList="tabList"
      variant="horizontal"
    >
{{value}} // want to bind data inside tab
    </app-tabs>

</template>

Expected Output

I am working on vertical tabs. Where the functionality is working fine. Here is the complete working code with static mock data https://codesandbox.io/s/vue-js-tabs-forked-we2cx?file=/src/App.vue

Now i want to create some mockdata inside of my data like 'tabList' and then, i want to display data dynamically when user clicked on tabs(including content -->tabs)

How to remove static data, which is inside slots and then only use data dynamically

To start with that, i am not sure, Where to start the looping to display data inside tabs dynamically with mock data?

Body:
You can set dynamic slot name using :slot="slotName" where slotName is a dynamic value

This can be achieved using a v-for aswell like below.

<template v-for="content in contentList" :slot="content.slot">
  {{ content.content }}
</template>

Where contentList is your array something like below.

contentList: [
  { id: 1, slot: "tabPanel-1", content: "Content 1" },
  { id: 2, slot: "tabPanel-2", content: "Content 2" },
  { id: 3, slot: "tabPanel-3", content: "Content 3" },
  { id: 4, slot: "tabPanel-4", content: "Content 4" },
]

Working Fiddle


问:
using exact_extract from exactextractr in R
I am trying to run the example code from the exactextractr package in R

```<code>library(raster)
library(sf)
library(exactextractr)

    brazil <- st_as_sf(getData('GADM', country='BRA', level=2))

    prec <- getData('worldclim', var='prec', res=10)

    brazil$mean_dec_prec <- exact_extract(prec[[12]], brazil, 'mean')

    brazil <- cbind(brazil, exact_extract(prec, brazil, c('min', 'max')))
</code>```

When I get to the third line I keep getting the following error

```<code>    in CPP_stats(x, weights, wkb, default_value, default_weight, coverage_area,  :
  Cannot convert object to a function: [type=NULL; target=CLOSXP, SPECIALSXP, or BUILTINSXP].
</code>```

I've searched around but I can't find anyone else having this error, I've had other people run the code, we are using the same package versions and it works fine for them.

Does anyone have any ideas on the problem or how to fix it?

Thanks,
Dave

答:
It seems this was a package version issue, resolved by updating.

I was able to reproduce the bug with version 0.5.2, but it worked fine with version 0.7.2

Body:
I am trying to run the example code from the exactextractr package in R

library(raster)
library(sf)
library(exactextractr)

    brazil <- st_as_sf(getData('GADM', country='BRA', level=2))

    prec <- getData('worldclim', var='prec', res=10)

    brazil$mean_dec_prec <- exact_extract(prec[[12]], brazil, 'mean')

    brazil <- cbind(brazil, exact_extract(prec, brazil, c('min', 'max')))

When I get to the third line I keep getting the following error

    in CPP_stats(x, weights, wkb, default_value, default_weight, coverage_area,  :
  Cannot convert object to a function: [type=NULL; target=CLOSXP, SPECIALSXP, or BUILTINSXP].

I've searched around but I can't find anyone else having this error, I've had other people run the code, we are using the same package versions and it works fine for them.

Does anyone have any ideas on the problem or how to fix it?

Thanks,
Dave