问:
Charles Proxy vs Developer Console vs Browserstack
It seems that more developers are using Charles Proxy nowadays, but I can't beg to differ what are the advantages or what you can do with Charles that you can't do with others like Chrome Developer Console or browser stack.</p>

答:
Debugging proxies like Charles Proxy, HTTP Toolkit and Fiddler all have a few features that browser developer tools don't:

They can capture traffic from non-browser sources, like mobile devices and desktop applications.

They can capture traffic from multiple tabs or other sources all in one place, so you can see the traffic from your web app and the backend traffic between your microservices all in one place.

They can capture traffic that the browser doesn't show - e.g. the browser's own requests for internal browser services, or safebrowsing checks, or CORS requests that don't appear in dev tools.

They include lots options to rewrite or reredirect traffic (usually with both custom rules to automatically mock responses and with breakpoints to manually edit traffic)

They usually offer more advanced traffic filtering and inspection, e.g. more powerful tools for finding certain requests, for inspecting more formats of request & response body, for understanding compression and caching behaviour, for validation of headers or even for validation of recognized request parameters with specific known APIs.

That said, there's a few unique benefits of browser tools:

There is zero setup and no separate applications required.

You immediately get the exact traffic from a single page with no extra noise from anywhere else.

They can use metadata from the browser's internal state, e.g. to show which line of JS sent a specific request, or to show requests that failed before any connections were made (due to CORS, mixed content, or many other browser restrictions).


来源: stackexchange

问:
When to 'implement' interface in angular
My question might be stupid, but i would like to get some clarity on this. As per my understanding, in angular we use interface to give idea about the data structure. So suppose we have an array of data of persons, we create an interface like

```<code>export interface Person {
  name: string;
  age: string
 }
</code>```

And we can directly import this to our ts file and assign the type like

```<code>export class ComponentName implements OnInit {
data: Person[];
constructor() {}
ngOnInIt(){}
}
</code>```

I totally understand this. But my confusion is, when do we 'implement' interface. I saw examples like

```<code>export class ComponentName implements OnInit, Person {
data: Person[];
constructor() {}
ngOnInIt(){}
}
</code>```

Any help would be appreciatable. Thank you

答:
In letter options, now your ComponentName MUST HAVE name and age fields ;)

so construct like this class X implements Y says literally that X is an Y

Also keep in mind that in typescript declarations does not matter, but actual structure, so even without implements Person delcaration, if ComponentName would have name and age fields, person:Person=this would still be valid.

ContentLicense: CC BY-SA 4.0

Body:
My question might be stupid, but i would like to get some clarity on this. As per my understanding, in angular we use interface to give idea about the data structure. So suppose we have an array of data of persons, we create an interface like

export interface Person {
  name: string;
  age: string
 }

And we can directly import this to our ts file and assign the type like

export class ComponentName implements OnInit {
data: Person[];
constructor() {}
ngOnInIt(){}
}

I totally understand this. But my confusion is, when do we 'implement' interface. I saw examples like

export class ComponentName implements OnInit, Person {
data: Person[];
constructor() {}
ngOnInIt(){}
}

Any help would be appreciatable. Thank you


问:
Are C# events synchronous?
There are two parts to this question:

Does raising an event block the thread, or does it start execution of EventHandlers asynchronously and the thread goes continues on at the same time?

Are the individual EventHandlers (subscribed to the event) run synchronously one after another, or are they run asynchronously with no guarantee that others aren't running at the same time?

答: Events in C# run synchronously (in both cases), as long as you don't start a second thread manually.</p>

Title: Are C# events synchronous?

ContentLicense: CC BY-SA 3.0


问:
How to download Slack history messages if you are not the app admin?
I am trying to download the history messages for a specific Slack app, let's say MLflow.

I found a few open-source tools on Github but none of them actually work for me. It seems that slack has disabled ways for non-admin to create the access token since May 2020. Is there any way for the scraping script to work without tokens? WHat else can I do now?

答:
You can try the app called Backupery for Slack

Disclaimer: I'm the developer of the app and the app is not free, but a free trial is available.

The app can help you to export any conversation from your Slack workspace, including direct messages between you and an app. For example, if I need to export the conversation between me and Jira Cloud app, I just need to select the conversation and export it:

Please also note, the app will automatically create an access token for you. By default, Primary Owner, Owners, Admins and Full Members are allowed to install any applications for Slack (and create access tokens). However, a workspace Admin or Owner may limit installations to pre-approved apps - in this case you will not be able to use the app as it will not be possible to install it.


问:
v2 Azure Function with Service Bus trigger not firing
I am using Azure Functions V2 with a Service Bus trigger using 1.0.23 of the C# Functions SDK. I'm using the following approach to get secrets from KeyVault and use them within the settings of the triggers: How to map Azure Functions secrets from Key Vault automatically

The function, especially when it has done nothing for a while, doesn't fire when there are messages on the subscription. If I then go to the portal and execute manually (yes, that particular execution is fired with a null message) it kicks it into life and picks up the other messages on the queue and processes them correctly.

This obviously isn't ideally for our automated tests. Has anybody seen this, or know of anything that will help?

Also, the Function App is running on a consumption plan.

答: I've had a similar issue. ServiceBus connection was injected using ServiceBus value in ConnectionStrings section of Function configuration. This is enough when Function is in hot state but after transitioning to cold state AzureWebJobsServiceBus value is used to connect to service bus. So in my case setting AzureWebJobsServiceBus to ServiceBus connection string in Function configuration fixed this.</p>


问:
PHP/SQL Update - update only if value has been change
I have following PHP loop + SQL Update query.

```<code>for ($i=0;$i<count($_POST['id']);$i++) {

    if(!isset($_POST['live'][$i])){
        $_POST['live'][$i] = "0";
    } else { $_POST['live'][$i] = "1"; }

    $id = ($_POST['id'][$i]);
    $live = ($_POST['live'][$i]);
    $usr2 = $_SESSION['usr'];
    $updated = date("F j, Y, g:i a",time()+60*60);

    $sql = "UPDATE news SET live = '$live', usr2 = '$usr2', updated = '$updated' WHERE id = $id";
    $result = mysql_query($sql);
    //echo $sql."<br />";

}
if($result) {
    header("location: notes.php");
    exit();

}else {
    die("Query failed");
}
</code>```

How does it work:

I'm submitting big form will ALL OF THE table rows.

receiving this in different file as an array

if $_POST['live'] is 'not set' - set it to '0', if 'set' set it to 1

update array data within for loop

How to UPDATE only the rows which have been actually been changed?

Those which value from $_POST['live'] is actually different from this saved in DB, as the condition would be change of our $live row.

答:
I guess you're concerned about the updated field and that this value only changes when something has been altered. (If that's not the case forget about this answer.)

You can define an ON UPDATE CURRENT_TIMESTAMP clause for a timestamp field. Each time a record is updated without explicitly setting a value for this field mysql uses the current time as its new value...

...but only if the record is altered; if you "update" the fields with the same value as are already in that record nothing happens.

demo script:

```<code><?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

setup($pdo);
$stmt = $pdo->prepare('UPDATE soNews SET somevalue=:v WHERE id=:id');
show('original', $pdo);

$stmt->execute( array(':id'=>1, ':v'=>'z') );
show('update with new=old & id=1', $pdo);

$stmt->execute( array(':id'=>2, ':v'=>'y') ); // new value=old value
show('update with new!=old & id=2', $pdo);

function setup($pdo) {
    $pdo->exec('
        CREATE TEMPORARY TABLE soNews (
            id int auto_increment,
            somevalue varchar(32),
            updated TIMESTAMP DEFAULT 0 ON UPDATE CURRENT_TIMESTAMP,
            primary key(id)
        )
    ');

    $pdo->exec("INSERT INTO soNews (id,somevalue,updated) VALUES (1,'x', Now()-interval 47 hour),(2,'y', Now()-interval 47 hour)");
}

function show($label, $pdo) {
    echo "------ $label --------\n";
    foreach( $pdo->query('SELECT * FROM soNews', PDO::FETCH_ASSOC) as $row ) {
        echo join(', ', $row), "\n";
    }
}
</code>```

prints

```<code>------ original --------
1, x, 2011-08-16 14:09:53
2, y, 2011-08-16 14:09:53
------ update with new=old & id=1 --------
1, z, 2011-08-18 13:09:53
2, y, 2011-08-16 14:09:53
------ update with new!=old & id=2 --------
1, z, 2011-08-18 13:09:53
2, y, 2011-08-16 14:09:53
</code>```

As you can see as a result of the first update query the timestamp field has been updated while the second query setting new=old didn't affect the updated field.

Body:
I have following PHP loop + SQL Update query.

for ($i=0;$i<count($_POST['id']);$i++) {

    if(!isset($_POST['live'][$i])){
        $_POST['live'][$i] = "0";
    } else { $_POST['live'][$i] = "1"; }

    $id = ($_POST['id'][$i]);
    $live = ($_POST['live'][$i]);
    $usr2 = $_SESSION['usr'];
    $updated = date("F j, Y, g:i a",time()+60*60);

    $sql = "UPDATE news SET live = '$live', usr2 = '$usr2', updated = '$updated' WHERE id = $id";
    $result = mysql_query($sql);
    //echo $sql."
";

}
if($result) {
    header("location: notes.php");
    exit();

}else {
    die("Query failed");
}

How does it work:

I'm submitting big form will ALL OF THE table rows.

receiving this in different file as an array

if $_POST['live'] is 'not set' - set it to '0', if 'set' set it to 1

update array data within for loop

How to UPDATE only the rows which have been actually been changed?

Those which value from $_POST['live'] is actually different from this saved in DB, as the condition would be change of our $live row.

Body:
I guess you're concerned about the updated field and that this value only changes when something has been altered. (If that's not the case forget about this answer.)

You can define an ON UPDATE CURRENT_TIMESTAMP clause for a timestamp field. Each time a record is updated without explicitly setting a value for this field mysql uses the current time as its new value...

...but only if the record is altered; if you "update" the fields with the same value as are already in that record nothing happens.

demo script:

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

setup($pdo);
$stmt = $pdo->prepare('UPDATE soNews SET somevalue=:v WHERE id=:id');
show('original', $pdo);

$stmt->execute( array(':id'=>1, ':v'=>'z') );
show('update with new=old & id=1', $pdo);

$stmt->execute( array(':id'=>2, ':v'=>'y') ); // new value=old value
show('update with new!=old & id=2', $pdo);

function setup($pdo) {
    $pdo->exec('
        CREATE TEMPORARY TABLE soNews (
            id int auto_increment,
            somevalue varchar(32),
            updated TIMESTAMP DEFAULT 0 ON UPDATE CURRENT_TIMESTAMP,
            primary key(id)
        )
    ');

    $pdo->exec("INSERT INTO soNews (id,somevalue,updated) VALUES (1,'x', Now()-interval 47 hour),(2,'y', Now()-interval 47 hour)");
}

function show($label, $pdo) {
    echo "------ $label --------\n";
    foreach( $pdo->query('SELECT * FROM soNews', PDO::FETCH_ASSOC) as $row ) {
        echo join(', ', $row), "\n";
    }
}

prints

------ original --------
1, x, 2011-08-16 14:09:53
2, y, 2011-08-16 14:09:53
------ update with new=old & id=1 --------
1, z, 2011-08-18 13:09:53
2, y, 2011-08-16 14:09:53
------ update with new!=old & id=2 --------
1, z, 2011-08-18 13:09:53
2, y, 2011-08-16 14:09:53

As you can see as a result of the first update query the timestamp field has been updated while the second query setting new=old didn't affect the updated field.


问:
Rest API Reponse : Uppercase to camelcase
What is the Best way to convert Uppercase values to camel case.
Lets say I have API with response {"name":"VIRAT KOHLI","teams":"RCB INDIA DELHI"}
Should it be handle  at DB query level or Java level (Business logic) or at Client-side like using Angular pipes. What is the best practices and what is best in terms of performance ?

At database I am using simple JDBC query.

答:
So I don't think there's a huge difference in performance or speed.
However, if you are working with a very large amount of data, doing the conversion at the database level could add a little bit more time.

It all depends on your context but you can :

Do it by Angular using the "TitleCasePipe"(https://angular.io/api/common/TitleCasePipe#titlecasepipe)
or
avoid repetition by doing a ".map()" on the received data by putting in camelCase the concerned fields (there are a lot of examples out there).

Do it on the Business layer of your Backend just making sure to do the transformation before sending the response.

Finally do it from the database (not recommended) but you have to take into account that the code is always faster than a database query.


问:
Distance finder not printing text
I'm trying to make this sign that, when you step close enough, shows a GUI.

To test it, I made it print("It works!") but It won't print anything.

LocalScript:

```<code>local Players = game:GetService('Players')
local LocalPlayer = Players.LocalPlayer

for _,Player in next, Players:GetChildren() do
    local character = Player.Character
    if character and character.Parent and Player ~= LocalPlayer then
        local Magnitude = (LocalPlayer.Character.HumanoidRootPart.Position - character.HumanoidRootPart.Position).magnitude

    end
end
while true do
    if Magnitude < 10 then
        print("It's working!")
    end
end
</code>```

答:
Your code has 3 main issues
1: Its a regular script, not a localscript
2: Your while true do loop will timeout when the server starts
3: Magnitude is only defined when doing for i,v

Try this code in a localscript instead

local Players = game:GetService('Players')
local LocalPlayer = Players.LocalPlayer
local Magnitude
while true do
    wait()
    for _,Player in next, Players:GetChildren() do
    local character = Player.Character
    if character and character.Parent and Player ~= LocalPlayer then
        Magnitude = (LocalPlayer.Character.HumanoidRootPart.Position - character.HumanoidRootPart.Position).magnitude

    end
end

if Magnitude ~= nil then
    if Magnitude < 10 then
        print("It's working!")
    end
end
end
```

Title: Distance finder not printing text

Body:
I'm trying to make this sign that, when you step close enough, shows a GUI.

To test it, I made it print("It works!") but It won't print anything.

LocalScript:

local Players = game:GetService('Players')
local LocalPlayer = Players.LocalPlayer

for _,Player in next, Players:GetChildren() do
    local character = Player.Character
    if character and character.Parent and Player ~= LocalPlayer then
        local Magnitude = (LocalPlayer.Character.HumanoidRootPart.Position - character.HumanoidRootPart.Position).magnitude

    end
end
while true do
    if Magnitude < 10 then
        print("It's working!")
    end
end


问:
How do I get a separator with a variable inside the URL in Laravel 5.8
I'm using Laravel 5.8 to develop a project. I have a page which contains a button, clicking on it will redirect you to a registration page. This button is located in multiple pages, so, when the button is clicked, I want the name of the page from which it was clicked to be shown in the URL.

For Example, take this Youtube link, https://www.youtube.com/watch?v=dQw4w9WgXcQ

The /watch?v=dQ part, I want to have that in my URL, where "watch" would be the current page's name, and v would contain the name/id of the previous page. I have posted the button and the routes below.

Let me know if something else is required.

```<code><a href="{{ url ('demo' )}}" class="set-btn btn3">Request a Demo</a>

Route::get('demo','Controller@dropdown_data');

Route::POST('demo','Controller@submit');
</code>```

The get route calls a function to retrieve data for dropdown fields from a database.
The post route calls the function for submission of the details.

答:
With the url() helper it is not possible to add URL query parameters. However, when you add a name to the route, you can use the route() helper like this on your pages:

```<code><a href="{{ url ('demo', ['prev' => 'nameOfCurrentPage')}}" class="set-btn btn3">
    Request a Demo
</a>
</code>```

And like this as your route definition:

```<code>Route::get('demo','Controller@dropdown_data')->name('demo');
</code>```

Body:
I'm using Laravel 5.8 to develop a project. I have a page which contains a button, clicking on it will redirect you to a registration page. This button is located in multiple pages, so, when the button is clicked, I want the name of the page from which it was clicked to be shown in the URL.

For Example, take this Youtube link, https://www.youtube.com/watch?v=dQw4w9WgXcQ

The /watch?v=dQ part, I want to have that in my URL, where "watch" would be the current page's name, and v would contain the name/id of the previous page. I have posted the button and the routes below.

Let me know if something else is required.

Request a Demo

Route::get('demo','Controller@dropdown_data');

Route::POST('demo','Controller@submit');

The get route calls a function to retrieve data for dropdown fields from a database.
The post route calls the function for submission of the details.

Body:
With the url() helper it is not possible to add URL query parameters. However, when you add a name to the route, you can use the route() helper like this on your pages:

<a href="{{ url ('demo', ['prev' => 'nameOfCurrentPage')}}" class="set-btn btn3">
    Request a Demo
</a>

And like this as your route definition:

Route::get('demo','Controller@dropdown_data')->name('demo');


问:
Pipeline job fails because of risky phpUnit tests and depracations
I have a pipeline that executes phpUnit tests, there's no failures running the tests but there's few tests that are risky or incomplete and there's few deprecation notices which make my pipeline fail. Is there a way to make the job not fail because of these warnings and only fail on phpUnit test failure?

答:
<env name="SYMFONY_DEPRECATIONS_HELPER" value="disabled" />

Puting this line inside my phpunit.xml file disabled deprecation warnings and the job was successful.


问:
I can't disable the user with the Keyrock API
I want to disable or enable the user found in keyrock with API, but I can't. https://keyrock.docs.apiary.io/ doesn't say how to do it here. Isn't that possible?enter image description here</p>

答:
Log in as an admin user via the REST API.

curl -iX POST \
  'http://localhost:3005/v1/auth/tokens' \
  -H 'Content-Type: application/json' \
  -d '{
  "name": "admin@test.com",
  "password": "1234"
}'
```
<p>The response header returns an <code>X-Subject-token</code> <strong>Header</strong> which identifies who has logged on the application. This token is required in all subsequent requests to gain access.</p>
<p>The image you give in the question is just a GUI version of the GET /users endpoint</p>
<pre class="lang-sh prettyprint-override"><code>curl -L -X GET 'http://localhost:3005/v1/users' \
-H 'Content-Type: application/json' \
-H 'X-Auth-token: aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
</code>```

Or you can request a specific user:

curl -L -X GET 'http://localhost:3005/v1/users/bbbbbbbb-good-0000-0000-000000000000' \
-H 'Content-Type: application/json' \
-H 'X-Auth-token: aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
```
<p>Returns:</p>
<pre class="lang-json prettyprint-override"><code>{
    "user": {
        "scope": [],
        "id": "bbbbbbbb-good-0000-0000-000000000000",
        "username": "bob",
        "email": "bob-the-manager@test.com",
        "enabled": true,
        "admin": false,
        "image": "default",
        "gravatar": false,
        "date_password": "2018-07-30T11:41:14.000Z",
        "description": "Bob is the regional manager",
        "website": null
    }
}
</code>```

You want to set enabled: false using the PATCH /user endpoint.

curl -L -X PATCH 'http://localhost:3005/v1/users/bbbbbbbb-good-0000-0000-000000000000' \
-H 'Content-Type: application/json' \
-H 'X-Auth-token: aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' \
--data-raw '{
    "user": {
        "username": "bob",
        "email": "bob-the-manager@test.com",
        "enabled": false,
        "gravatar": false,
        "date_password": "2018-07-26T15:25:14.000Z"
    }
}'
```

More information can be found within the Security Chapter Tutorials
within the FIWARE documentation where Keyrock is a component found within the FIWARE Catalogue

In the FIWARE documentation an example is given using Keyrock to provide user identities around a "powered by FIWARE" solution. Note that whilst Keyrock is commonly used  in  "powered by FIWARE" solutions (along with other elements from the FIWARE Catalogue), it could also be used to provide identities for other independent applications or micro-services - it is not tightly bound to only be used in FIWARE scenarios. Similarly alternative open-source or proprietary components for security or identity management systems could be used to secure  "powered by FIWARE" solution as well.

Body:
Log in as an admin user via the REST API.

curl -iX POST \
  'http://localhost:3005/v1/auth/tokens' \
  -H 'Content-Type: application/json' \
  -d '{
  "name": "admin@test.com",
  "password": "1234"
}'

The response header returns an X-Subject-token Header which identifies who has logged on the application. This token is required in all subsequent requests to gain access.

The image you give in the question is just a GUI version of the GET /users endpoint

curl -L -X GET 'http://localhost:3005/v1/users' \
-H 'Content-Type: application/json' \
-H 'X-Auth-token: aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'

Or you can request a specific user:

curl -L -X GET 'http://localhost:3005/v1/users/bbbbbbbb-good-0000-0000-000000000000' \
-H 'Content-Type: application/json' \
-H 'X-Auth-token: aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'

Returns:

{
    "user": {
        "scope": [],
        "id": "bbbbbbbb-good-0000-0000-000000000000",
        "username": "bob",
        "email": "bob-the-manager@test.com",
        "enabled": true,
        "admin": false,
        "image": "default",
        "gravatar": false,
        "date_password": "2018-07-30T11:41:14.000Z",
        "description": "Bob is the regional manager",
        "website": null
    }
}

You want to set enabled: false using the PATCH /user endpoint.

curl -L -X PATCH 'http://localhost:3005/v1/users/bbbbbbbb-good-0000-0000-000000000000' \
-H 'Content-Type: application/json' \
-H 'X-Auth-token: aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' \
--data-raw '{
    "user": {
        "username": "bob",
        "email": "bob-the-manager@test.com",
        "enabled": false,
        "gravatar": false,
        "date_password": "2018-07-26T15:25:14.000Z"
    }
}'

More information can be found within the Security Chapter Tutorials
within the FIWARE documentation where Keyrock is a component found within the FIWARE Catalogue

In the FIWARE documentation an example is given using Keyrock to provide user identities around a "powered by FIWARE" solution. Note that whilst Keyrock is commonly used  in  "powered by FIWARE" solutions (along with other elements from the FIWARE Catalogue), it could also be used to provide identities for other independent applications or micro-services - it is not tightly bound to only be used in FIWARE scenarios. Similarly alternative open-source or proprietary components for security or identity management systems could be used to secure  "powered by FIWARE" solution as well.


问:
Global Object in singleton
In the Singleton pattern why is that we have to use a static object and not a global object?

I tried the following

```<code>class Singleton;
Singleton*  instance1 = NULL;

class Singleton
{
private :
       Singleton()
       {
       }
       //static Singleton* instance1;

public:
        static Singleton* getinstance()

 if(instance1== NULL)
       {
       instance1 = new Singleton();
       }

 return instance1;

 void Dispaly()
       {
       }
 ~Singleton()
       {
       }
};
</code>```

When I compile this code I get the error "multiple definition of instance1"

Can anyone please give a plausible reason for this?

答:
That defeats the purpose of the singleton - accessing the object from a single place. You can access it everywhere without having to call getInstance().

As for the error, my guess is you included your header in multiple files.

Put

```<code>#pragma once
</code>```

at the beginning of your header file, that should solve the error.

But again, this is a bad implementation of the singleton pattern.

EDIT:

Or use header guards:

```<code>#ifndef _SINGLETON_CLASS_INCLUDED
#define _SINGLETON_CLASS_INCLUDED

//// contents of your header

#endif
</code>```

Title: Global Object in singleton

Body:
In the Singleton pattern why is that we have to use a static object and not a global object?

I tried the following

class Singleton;
Singleton*  instance1 = NULL;

class Singleton
{
private :
       Singleton()
       {
       }
       //static Singleton* instance1;

public:
        static Singleton* getinstance()

 if(instance1== NULL)
       {
       instance1 = new Singleton();
       }

 return instance1;

 void Dispaly()
       {
       }
 ~Singleton()
       {
       }
};

When I compile this code I get the error "multiple definition of instance1"

Can anyone please give a plausible reason for this?

Body:
That defeats the purpose of the singleton - accessing the object from a single place. You can access it everywhere without having to call getInstance().

As for the error, my guess is you included your header in multiple files.

Put

#pragma once

at the beginning of your header file, that should solve the error.

But again, this is a bad implementation of the singleton pattern.

EDIT:

Or use header guards:

#ifndef _SINGLETON_CLASS_INCLUDED
#define _SINGLETON_CLASS_INCLUDED

//// contents of your header

#endif


问:
How can update a object state in inputs ? (React js Hooks)
I'm new in React and I saw a lot of topics about updateo bject state but in my case I continue with erros.

I have a object useSate and I want update every time my input changes.
I have tried the spread operator.

My state :

```<code>const [inputs, setInputs] = useState({
    topic: {
      coins: 0,
      money: 0,
      cash: 0,
    }
 })
</code>```

my handle funtion :

```<code>const handleMoney = (e) => {
      setInputs(prevState =>({
        inputs:{
          ...prevState.inputs,
          coins: e.target.value
        }
      }))
}
</code>```

And my form ( is from react boostrap):

```<code>           <Form.Control
             min={0}
             type="number"
             value={inputs.coins}
             onChange={handleMoney }
           />
</code>```

答:
```<code> const handleMoney = (e) => {
    setInputs({
     ...inputs,
      inputs['topic']['coin'] = e.target.value
  })
</code>```

Otherwise You can use

```<code>    const handleMoney = (e) => {
      const newInput = {...inputs}
      newInput['topic']['coin'] =e.target.value
      setInputs(newInput)
    })
</code>```

And form is

```<code>       <Form.Control
       min={0}
       type="number"
       value={inputs.topic?.coins}
       onChange={()=>handleMoney() }
       />
</code>```

Body:
I'm new in React and I saw a lot of topics about updateo bject state but in my case I continue with erros.

I have a object useSate and I want update every time my input changes.
I have tried the spread operator.

My state :

const [inputs, setInputs] = useState({
    topic: {
      coins: 0,
      money: 0,
      cash: 0,
    }
 })

my handle funtion :

const handleMoney = (e) => {
      setInputs(prevState =>({
        inputs:{
          ...prevState.inputs,
          coins: e.target.value
        }
      }))
}

And my form ( is from react boostrap):

           <Form.Control
             min={0}
             type="number"
             value={inputs.coins}
             onChange={handleMoney }
           />

Body:
 const handleMoney = (e) => {
    setInputs({
     ...inputs,
      inputs['topic']['coin'] = e.target.value
  })

Otherwise You can use

    const handleMoney = (e) => {
      const newInput = {...inputs}
      newInput['topic']['coin'] =e.target.value
      setInputs(newInput)
    })

And form is

       <Form.Control
       min={0}
       type="number"
       value={inputs.topic?.coins}
       onChange={()=>handleMoney() }
       />


问:
Nuxt JS use injected function from plugin in another plugin file
I'm using Nuxt JS's inject function to inject a function into my page for code reusability. I'd like to use the function in another plugin file and can't seem to get the function in there.

Here's my set up:

plugins/utils/tracking.js

function setCookiePrefix () {
  return 'fudge__'
}

function getCookie (app, name) {
  try {
    const prefix = setCookiePrefix()
    const cookie = app.$cookies.get(`${prefix}${name}`)

    if (!cookie || cookie == '') {
      throw 'cookie not set'
    }

    return cookie
  } catch (err) { }

  return null
}

export default function ({ app, store, context }, inject) {

  /*
  * Get just the affiliate (cpm_id OR affiliate)
  * examples: "my_brand", "blah"
  */
  inject('getAffiliate', () => {
    const affiliate = getCookie(app, 'affiliate')
    const brand = getBrand(store)

    if (!affiliate) return brand

    return affiliate
  })

}
```
<p>And the file I'm trying to utilise the <code>getAffiliate</code> function in from my tracking.js file:</p>
<ul>
<li><strong>plugins/init-brand.js</strong></li>
</ul>
<pre class="lang-js prettyprint-override"><code>export default async function ({ app, route, store }) {
  const affiliate = app.$getAffiliate()
  console.log(affiliate) <-- undefined
}
</code>```

I've tried:

app.$getAffiliate()

this.$getAffiliate() <-- this works in a Vue file

$getAffiliate()

this.getAffiliate()

What am I missing to access my getAffiliate function in another plugin file?

答:
I have an api plugin with some axios set up. I can load it inside another plugin file like this:

```<code>export default ( {$api} , inject) => {
  const service = new SomeService($api)
  inject('someService', SomeService)
}
</code>```

So in your case that would be:

```<code>export default async function ({ app, route, store, $getAffiliate }) {
  const affiliate = $getAffiliate()
  console.log(affiliate)
}
</code>```

Not sure if this is the right way, but it works for me.

Body:
I'm using Nuxt JS's inject function to inject a function into my page for code reusability. I'd like to use the function in another plugin file and can't seem to get the function in there.

Here's my set up:

plugins/utils/tracking.js

function setCookiePrefix () {
  return 'fudge__'
}

function getCookie (app, name) {
  try {
    const prefix = setCookiePrefix()
    const cookie = app.$cookies.get(`${prefix}${name}`)

    if (!cookie || cookie == '') {
      throw 'cookie not set'
    }

    return cookie
  } catch (err) { }

  return null
}

export default function ({ app, store, context }, inject) {

  /*
  * Get just the affiliate (cpm_id OR affiliate)
  * examples: "my_brand", "blah"
  */
  inject('getAffiliate', () => {
    const affiliate = getCookie(app, 'affiliate')
    const brand = getBrand(store)

    if (!affiliate) return brand

    return affiliate
  })

}

And the file I'm trying to utilise the getAffiliate function in from my tracking.js file:

plugins/init-brand.js

export default async function ({ app, route, store }) {
  const affiliate = app.$getAffiliate()
  console.log(affiliate) <-- undefined
}

I've tried:

app.$getAffiliate()

this.$getAffiliate() <-- this works in a Vue file

$getAffiliate()

this.getAffiliate()

What am I missing to access my getAffiliate function in another plugin file?

Body:
I have an api plugin with some axios set up. I can load it inside another plugin file like this:

export default ( {$api} , inject) => {
  const service = new SomeService($api)
  inject('someService', SomeService)
}

So in your case that would be:

export default async function ({ app, route, store, $getAffiliate }) {
  const affiliate = $getAffiliate()
  console.log(affiliate)
}

Not sure if this is the right way, but it works for me.


问:
Problem executing regex with a shell command inside Python program
I am trying to write a Python script to automate some tasks while the event of high inbound connections to the server.

So a portion of it is to collect all the IPv4 addresses on the server.

The command helps to list out that.

```<code># ip a s eth0 | egrep -o 'inet [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | cut -d' ' -f2
198.168.1.2
198.168.1.3
198.168.1.4
</code>```

The problem I am facing when executing the shell regex part inside the python script.

```<code>#!/usr/bin/env python3
import os
ipv4_regex='[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
os_cmd = 'ip a s eth0 | egrep -o 'inet ipv4_regex' | cut -d' ' -f2'
os.system(os_cmd)
</code>```

But the output is error:

```<code># ./dos_fix.py
  File "./dos_fix.py", line 4
    os_cmd = 'ip a s eth0 | egrep -o 'inet ipv4_regex' | cut -d' ' -f2'
                                     ^
</code>```

To see if it was due to any whitespace interrupting between the egrep and pipe, I tried to escape those quotes with backslashes, but no luck.

```<code>#!/usr/bin/env python3
import os
ipv4_regex='[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
os_cmd = 'ip a s eth0 | egrep -o \'inet ipv4_regex\' | cut -d\' \' -f2'
os.system(os_cmd)
</code>```

What am I missing here?.

答:
Use double quotes and don't escape.

In the regular expression, use a raw string: r'contents'.

os.system has some limitations. subprocess is much better.

#!/usr/bin/env python3
import os

ipv4_regex = r'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
os_cmd = f"ip a s eth0 | egrep -o 'inet {ipv4_regex}' | cut -d' ' -f2"
os.system(os_cmd)
```

Body:
I am trying to write a Python script to automate some tasks while the event of high inbound connections to the server.

So a portion of it is to collect all the IPv4 addresses on the server.

The command helps to list out that.

# ip a s eth0 | egrep -o 'inet [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | cut -d' ' -f2
198.168.1.2
198.168.1.3
198.168.1.4

The problem I am facing when executing the shell regex part inside the python script.

#!/usr/bin/env python3
import os
ipv4_regex='[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
os_cmd = 'ip a s eth0 | egrep -o 'inet ipv4_regex' | cut -d' ' -f2'
os.system(os_cmd)

But the output is error:

# ./dos_fix.py
  File "./dos_fix.py", line 4
    os_cmd = 'ip a s eth0 | egrep -o 'inet ipv4_regex' | cut -d' ' -f2'
                                     ^

To see if it was due to any whitespace interrupting between the egrep and pipe, I tried to escape those quotes with backslashes, but no luck.

#!/usr/bin/env python3
import os
ipv4_regex='[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
os_cmd = 'ip a s eth0 | egrep -o \'inet ipv4_regex\' | cut -d\' \' -f2'
os.system(os_cmd)

What am I missing here?.


问:
Trigger.AvailableNow for Delta source streaming queries in PySpark (Databricks)
All the examples in the Databricks documentation are in Scala. Can't find how to use this trigger type from PySpark. Is there an equivalent API or workaround ?</p>

答:
Python implementation missed the Spark 3.2 release, so it will be included into Spark 3.3 only (for OSS version). On Databricks it was released as part of DBR 10.3 (or 10.2?), and could be used as following:</p>
```<code>.trigger(availableNow=True)
</code>```

Body:
Python implementation missed the Spark 3.2 release, so it will be included into Spark 3.3 only (for OSS version). On Databricks it was released as part of DBR 10.3 (or 10.2?), and could be used as following:

.trigger(availableNow=True)


问:
How to load transformers pipeline from folder?
According to here pipeline provides an interface to save a pretrained pipeline locally with a save_pretrained method. When I use it, I see a folder created with a bunch of json and bin files presumably for the tokenizer and the model.

But the documentation does not specify a load method. How does one initialize a pipeline using a locally saved pipeline?

答:
If you read the specification for save_pretrained, it simply states that it

Save[s] the pipeline’s model and tokenizer.

I've also given a slightly related answer here on how custom models and tokenizers can be loaded. Essentially, you can simply specify the specific models/paths in the pipeline:

from transformers import pipeline, AutoModel, AutoTokenizer

# Replace with your custom model of choice
model = AutoModel.from_pretrained('/path/to/your/model')
tokenizer = AutoTokenizer.from_pretrained('/path/to/your/tokenizer')

pipe = pipeline(task='summarization',  # replace with whatever task you have
                model=model,
                tokenizer=tokenizer)

```


问:
SwiftUI NavigationView size to fit content
I want to create a bottom sheet that contains a NavigationView to support back and forth transitions managed by a coordinator.

As far as I saw, the NavigationView automatically uses all the space it can - independent of whether its content actually needs this space. I can limit it by using paddings/spacers or a frame modifier, but I want the NavigationView to resize itself based on the content I put in there (dynamically, cause the content may change at runtime).

Does someone know how to achieve that?

With default Spacer :(

With Spacer that has minLength = 500 :)
That's what it should look like.

答:
This is a very unusual use of NavigationView, actually there might be coming other issues along the way.

I couldn't get if to work with flexible size by GeometryReader, but for fixed you can do this:

```<code>    VStack {
        Color.clear // takes all available space above
        NavBottomSheet() // your Nav View
            .frame(maxHeight: 200) // you have to give it a fixed size
    }
</code>```

Body:
This is a very unusual use of NavigationView, actually there might be coming other issues along the way.

I couldn't get if to work with flexible size by GeometryReader, but for fixed you can do this:

    VStack {
        Color.clear // takes all available space above
        NavBottomSheet() // your Nav View
            .frame(maxHeight: 200) // you have to give it a fixed size
    }


问:
Update element on updating react state array
I am confused in updating element with React.useState()
I am creating dynamic calculator, where you can add fields, so I cannot use one state per result of category, so I created an object contains results by Id of category, and categories can be added there.
let [results, setResults] = React.useState({});
Then every time when user adds a product

```<code>for (const category of product.categories) {
  results[category.id] = 0;
</code>```

When I am updating result for some category, it is gets updated:

```<code>setResults(newResults => {
  newResults[categoryId] = mult * sum * quantity;
  return newResults;
})
</code>```

But my element in the table keeps showing zero (inital value)<TableCell align="right">
{results[category.id]}
</TableCell>

Upd: here is the full code: https://pastebin.com/cbJzFC8t
Page looks like this

答:
You need to define a new variable</p>
```<code>setResults(oldResults=> {
  let newResults = oldResults[categoryId]
  newResults = mult * sum * quantity;
  return newResults;
})
</code>```

Body:
I am confused in updating element with React.useState()
I am creating dynamic calculator, where you can add fields, so I cannot use one state per result of category, so I created an object contains results by Id of category, and categories can be added there.
let [results, setResults] = React.useState({});
Then every time when user adds a product

for (const category of product.categories) {
  results[category.id] = 0;

When I am updating result for some category, it is gets updated:

setResults(newResults => {
  newResults[categoryId] = mult * sum * quantity;
  return newResults;
})

But my element in the table keeps showing zero (inital value)<TableCell align="right">
{results[category.id]}
</TableCell>

Upd: here is the full code: https://pastebin.com/cbJzFC8t
Page looks like this

Body:
You need to define a new variable

setResults(oldResults=> {
  let newResults = oldResults[categoryId]
  newResults = mult * sum * quantity;
  return newResults;
})


问:
plot histogram after averaging images
I have the following code to average a set of images (say 100 images) and to plot the histogram of the averaged image (one image). I am not getting the histogram with this code. Could you please help me in this code.

```<code># reading multiple images
 S01=[i for i in glob.glob("C:/Users/experiment 1/S01/*.tif")]
  #  Averaging images
   s=np.array([np.array(Image.open(fname)) for fname in
   S01])
   s_avg=np.array(np.mean(s,axis=(0)),dtype=np.uint16)
   s_out=Image.fromarray(s_avg)
   #plot histogram
   plt.hist(s_out,bins=auto)
   plt.show()
</code>```

答:
No need to convert s_avg to an Image, you can compute the histogram of the array using .ravel()

```<code>fnames = [i for i in glob.glob("C:/Users/experiment 1/S01/*.tif")]
s=np.array([np.array(Image.open(fname)) for fname in fnames])

s_avg=np.mean(s,axis=(0))

#plot histogram
plt.hist(s_avg.ravel(),bins=100)
plt.show()
</code>```

Title: plot histogram after averaging images

Body:
I have the following code to average a set of images (say 100 images) and to plot the histogram of the averaged image (one image). I am not getting the histogram with this code. Could you please help me in this code.

# reading multiple images
 S01=[i for i in glob.glob("C:/Users/experiment 1/S01/*.tif")]
  #  Averaging images
   s=np.array([np.array(Image.open(fname)) for fname in
   S01])
   s_avg=np.array(np.mean(s,axis=(0)),dtype=np.uint16)
   s_out=Image.fromarray(s_avg)
   #plot histogram
   plt.hist(s_out,bins=auto)
   plt.show()

Body:
No need to convert s_avg to an Image, you can compute the histogram of the array using .ravel()

fnames = [i for i in glob.glob("C:/Users/experiment 1/S01/*.tif")]
s=np.array([np.array(Image.open(fname)) for fname in fnames])

s_avg=np.mean(s,axis=(0))

#plot histogram
plt.hist(s_avg.ravel(),bins=100)
plt.show()


问:
How can I create a wrapper for the RecyclerView Adapter that will accept any Adapter that implements RecyclerView.Adapter<RecyclerView.ViewHolder>
I know the title is a bit weird, sorry. This is a weird one that I'm not even sure I can explain it correctly, here is my attempt:

Basically I want to implement a wrapper for any adapters that extend RecyclerView.Adapter<RecyclerView.ViewHolder> , the wrapper eventually will be able to insert rows if needed and it will modify things like getItemCount() as necessary, but I'm nowhere near that part yet.

This is my class definition:

```<code>class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
</code>```

I pass to it the original adapter which I want to wrap.

If I have the class definition like that, and then I try to create an instance of MyRecyclerAdapterWrapper like this:

```<code>val wrapper = MyRecyclerAdapterWrapper(activity, myOriginalAdapter)
</code>```

Where myOriginalAdapter is an instance of:

```<code>class MyOriginalAdapter() : RecyclerView.Adapter<MyOriginalAdapter.MyViewHolder>() {
</code>```

I then get an error saying that it is expecting RecyclerView.Adapter<RecyclerView.ViewHolder>  but instead got MyOriginalAdapter.

So then I tried the out keyword on the class definition like this:

```<code>class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<out RecyclerView.ViewHolder>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
</code>```

And that allows my constructor call MyRecyclerAdapterWrapper(activity, myOriginalAdapter) to stop complaining, however then my MyRecyclerAdapterWrapper class fails at implementing some of the RecyclerView.Adapter<RecyclerView.ViewHolder> overrides because originalAdapter expects Nothing instead of RecyclerView.ViewHolder.

For example inside MyRecyclerAdapterWrapper I have this piece of code:

```<code>override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        originalAdapter.onBindViewHolder(holder,position)
}
</code>```

The error here is Type mismatch Required: Nothing Found: RecyclerView.ViewHolder.

So what is the correct way to handle this?

Edit: just wanted to be clear that other adapters will also use this wrapper, so the wrapper must be generic.

Edit: I should have mentioned this, there is a similar wrapper that works fine that I was using but it is in Java, the class definition on that one was:

```<code>public final class MyRecyclerAdapterWrapper extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
     public MyRecyclerAdapterWrapper(@NonNull Activity activity,
        @NonNull RecyclerView.Adapter originalAdapter){
</code>```

Edit: Based on the answer from @muetzenflo I was able to get most of it to work but still have a problem with some methods.

I now have this:

```<code>class MyRecyclerAdapterWrapper<T : RecyclerView.ViewHolder>(activity: Activity, val originalAdapter: RecyclerView.Adapter<T>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
</code>```

And

```<code> class MyCustomAdapter(): RecyclerView.Adapter<MyCustomAdapter.MyViewHolder>(){
        class MyViewHolder(v: View): RecyclerView.ViewHolder(v) {

        }
</code>```

This works:

```<code>val myRecyclerAdapterWrapper = MyRecyclerAdapterWrapper(this, MyCustomAdapter())
</code>```

But this doesn't:

```<code>genericMethod(myRecyclerAdapterWrapper)

private fun genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<RecyclerView.ViewHolder>) {

    }
</code>```

The error is:

```<code>Type mismatch: inferred type is MainActivity.MyRecyclerAdapterWrapper<MainActivity.MyCustomAdapter.MyViewHolder> but MainActivity.MyRecyclerAdapterWrapper<RecyclerView.ViewHolder> was expected
</code>```

Edit: Think I figured out how to make the generic methods:

```<code>private fun <T> genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<T> ) where T : RecyclerView.ViewHolder {

    }
</code>```

So in the end this is how my class ended up and it all compiles and runs:

```<code>class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val myRecyclerAdapterWrapper = MyRecyclerAdapterWrapper(this, MyCustomAdapter())
        genericMethod(myRecyclerAdapterWrapper)
    }
    private fun <T> genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<T> ) where T : RecyclerView.ViewHolder {
    }
    class MyRecyclerAdapterWrapper<T : RecyclerView.ViewHolder>(activity: Activity, val originalAdapter: RecyclerView.Adapter<T>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return originalAdapter.onCreateViewHolder(parent,viewType)
        }
        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            originalAdapter.onBindViewHolder(holder as T,position)
        }
        override fun getItemCount(): Int {
            return originalAdapter.itemCount
        }
    }
    class MyCustomAdapter(): RecyclerView.Adapter<MyCustomAdapter.MyViewHolder>(){
        class MyViewHolder(v: View): RecyclerView.ViewHolder(v) {
        }
        override fun getItemCount(): Int {
            TODO("Not yet implemented")
        }
        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
            TODO("Not yet implemented")
        }
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
            TODO("Not yet implemented")
        }
    }
}
</code>```

答:
There are my 2 classes that I use in all of my projects for making generalized use of databinding in RecyclerView items:

Usage

```<code>import androidx.recyclerview.widget.DiffUtil
import de.bvb09.android.R
import de.bvb09.android.data.model.news.NewsComponent
import de.bvb09.android.recyclerview.DataBindingAdapter
import de.bvb09.android.recyclerview.DataBindingViewHolder

/**
 * This adapter is responsible for the optional horizontal image gallery
 */
class ZoomImageAdapter : DataBindingAdapter<String>(DiffCallback) {

    override fun getItemViewType(position: Int): Int {
        return R.layout.item_zoom_image
    }

    /**
     * The DiffCallback is used by the [DataBindingAdapter] to check which items are
     * completely new and which just changed its content. When defining the Boolean checks, be
     * as precise as possible to avoid strange behaviour of the RecyclerView items.
     */
    object DiffCallback : DiffUtil.ItemCallback<String>() {
        override fun areItemsTheSame(oldItem: String, newItem: String): Boolean {
            return oldItem == newItem
        }

        override fun areContentsTheSame(oldItem: String, newItem: String): Boolean {
            return oldItem == newItem
        }
    }
}
</code>```

The ListAdapter

```<code>import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter

/**
 * This generic Adapter can be used to use any data class T as data provider for recyclerView list items.
 * To send a list of items to this adapter, use the submitList(newList) method. The DiffCallback is then called to
 * detect which items are completely new or have changed content. Animations are created accordingly and automatically.
 */
abstract class DataBindingAdapter<T>(diffCallback: DiffUtil.ItemCallback<T>) : ListAdapter<T, DataBindingViewHolder<T>>(diffCallback) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DataBindingViewHolder<T> {
        val layoutInflater = LayoutInflater.from(parent.context)
        val binding = DataBindingUtil.inflate<ViewDataBinding>(layoutInflater, viewType, parent, false)
        return DataBindingViewHolder(binding)
    }

    override fun onBindViewHolder(holder: DataBindingViewHolder<T>, position: Int) {
        val item = getItem(position)
        holder.bind(item)
    }
}
</code>```

The ViewHolder

```<code>import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import your.package.name.BR

/**
 * This ViewHolder is an addition to the [DataBindingAdapter]. From this, it receives a ViewDataBinding which
 * allows us to connect the data class T with the data-bindings defined in the item layout.
 */
class DataBindingViewHolder<T>(private val binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) {

    var item: T? = null
        private set

    fun rebind() {
        binding.invalidateAll()
        binding.executePendingBindings()
    }

    fun bind(item: T) {
        this.item = item
        binding.setVariable(BR.item, item)
        binding.executePendingBindings()
    }
}
</code>```

Body:
I know the title is a bit weird, sorry. This is a weird one that I'm not even sure I can explain it correctly, here is my attempt:

Basically I want to implement a wrapper for any adapters that extend RecyclerView.Adapter<RecyclerView.ViewHolder> , the wrapper eventually will be able to insert rows if needed and it will modify things like getItemCount() as necessary, but I'm nowhere near that part yet.

This is my class definition:

class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

I pass to it the original adapter which I want to wrap.

If I have the class definition like that, and then I try to create an instance of MyRecyclerAdapterWrapper like this:

val wrapper = MyRecyclerAdapterWrapper(activity, myOriginalAdapter)

Where myOriginalAdapter is an instance of:

class MyOriginalAdapter() : RecyclerView.Adapter<MyOriginalAdapter.MyViewHolder>() {

I then get an error saying that it is expecting RecyclerView.Adapter<RecyclerView.ViewHolder>  but instead got MyOriginalAdapter.

So then I tried the out keyword on the class definition like this:

class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<out RecyclerView.ViewHolder>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

And that allows my constructor call MyRecyclerAdapterWrapper(activity, myOriginalAdapter) to stop complaining, however then my MyRecyclerAdapterWrapper class fails at implementing some of the RecyclerView.Adapter<RecyclerView.ViewHolder> overrides because originalAdapter expects Nothing instead of RecyclerView.ViewHolder.

For example inside MyRecyclerAdapterWrapper I have this piece of code:

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        originalAdapter.onBindViewHolder(holder,position)
}

The error here is Type mismatch Required: Nothing Found: RecyclerView.ViewHolder.

So what is the correct way to handle this?

Edit: just wanted to be clear that other adapters will also use this wrapper, so the wrapper must be generic.

Edit: I should have mentioned this, there is a similar wrapper that works fine that I was using but it is in Java, the class definition on that one was:

public final class MyRecyclerAdapterWrapper extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
     public MyRecyclerAdapterWrapper(@NonNull Activity activity,
        @NonNull RecyclerView.Adapter originalAdapter){

Edit: Based on the answer from @muetzenflo I was able to get most of it to work but still have a problem with some methods.

I now have this:

class MyRecyclerAdapterWrapper<T : RecyclerView.ViewHolder>(activity: Activity, val originalAdapter: RecyclerView.Adapter<T>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

And

 class MyCustomAdapter(): RecyclerView.Adapter<MyCustomAdapter.MyViewHolder>(){
        class MyViewHolder(v: View): RecyclerView.ViewHolder(v) {

        }

This works:

val myRecyclerAdapterWrapper = MyRecyclerAdapterWrapper(this, MyCustomAdapter())

But this doesn't:

genericMethod(myRecyclerAdapterWrapper)

private fun genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<RecyclerView.ViewHolder>) {

    }

The error is:

Type mismatch: inferred type is MainActivity.MyRecyclerAdapterWrapper<MainActivity.MyCustomAdapter.MyViewHolder> but MainActivity.MyRecyclerAdapterWrapper<RecyclerView.ViewHolder> was expected

Edit: Think I figured out how to make the generic methods:

private fun <T> genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<T> ) where T : RecyclerView.ViewHolder {

    }

So in the end this is how my class ended up and it all compiles and runs:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val myRecyclerAdapterWrapper = MyRecyclerAdapterWrapper(this, MyCustomAdapter())
        genericMethod(myRecyclerAdapterWrapper)
    }
    private fun <T> genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<T> ) where T : RecyclerView.ViewHolder {
    }
    class MyRecyclerAdapterWrapper<T : RecyclerView.ViewHolder>(activity: Activity, val originalAdapter: RecyclerView.Adapter<T>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return originalAdapter.onCreateViewHolder(parent,viewType)
        }
        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            originalAdapter.onBindViewHolder(holder as T,position)
        }
        override fun getItemCount(): Int {
            return originalAdapter.itemCount
        }
    }
    class MyCustomAdapter(): RecyclerView.Adapter<MyCustomAdapter.MyViewHolder>(){
        class MyViewHolder(v: View): RecyclerView.ViewHolder(v) {
        }
        override fun getItemCount(): Int {
            TODO("Not yet implemented")
        }
        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
            TODO("Not yet implemented")
        }
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
            TODO("Not yet implemented")
        }
    }
}

Body:
There are my 2 classes that I use in all of my projects for making generalized use of databinding in RecyclerView items:

Usage

import androidx.recyclerview.widget.DiffUtil
import de.bvb09.android.R
import de.bvb09.android.data.model.news.NewsComponent
import de.bvb09.android.recyclerview.DataBindingAdapter
import de.bvb09.android.recyclerview.DataBindingViewHolder

/**
 * This adapter is responsible for the optional horizontal image gallery
 */
class ZoomImageAdapter : DataBindingAdapter<String>(DiffCallback) {

    override fun getItemViewType(position: Int): Int {
        return R.layout.item_zoom_image
    }

    /**
     * The DiffCallback is used by the [DataBindingAdapter] to check which items are
     * completely new and which just changed its content. When defining the Boolean checks, be
     * as precise as possible to avoid strange behaviour of the RecyclerView items.
     */
    object DiffCallback : DiffUtil.ItemCallback<String>() {
        override fun areItemsTheSame(oldItem: String, newItem: String): Boolean {
            return oldItem == newItem
        }

        override fun areContentsTheSame(oldItem: String, newItem: String): Boolean {
            return oldItem == newItem
        }
    }
}

The ListAdapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter

/**
 * This generic Adapter can be used to use any data class T as data provider for recyclerView list items.
 * To send a list of items to this adapter, use the submitList(newList) method. The DiffCallback is then called to
 * detect which items are completely new or have changed content. Animations are created accordingly and automatically.
 */
abstract class DataBindingAdapter<T>(diffCallback: DiffUtil.ItemCallback<T>) : ListAdapter<T, DataBindingViewHolder<T>>(diffCallback) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DataBindingViewHolder<T> {
        val layoutInflater = LayoutInflater.from(parent.context)
        val binding = DataBindingUtil.inflate<ViewDataBinding>(layoutInflater, viewType, parent, false)
        return DataBindingViewHolder(binding)
    }

    override fun onBindViewHolder(holder: DataBindingViewHolder<T>, position: Int) {
        val item = getItem(position)
        holder.bind(item)
    }
}

The ViewHolder

import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import your.package.name.BR

/**
 * This ViewHolder is an addition to the [DataBindingAdapter]. From this, it receives a ViewDataBinding which
 * allows us to connect the data class T with the data-bindings defined in the item layout.
 */
class DataBindingViewHolder<T>(private val binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) {

    var item: T? = null
        private set

    fun rebind() {
        binding.invalidateAll()
        binding.executePendingBindings()
    }

    fun bind(item: T) {
        this.item = item
        binding.setVariable(BR.item, item)
        binding.executePendingBindings()
    }
}


问:
Spring boot disable @EnableAsync for integration tests
I would like to disable @EnableAsync when I run my integration tests.

I tried to override the configuration file which is annotated with @EnableAsync with a class with the same name in my test package but it does not work.

In this topic: Is it possible to disable Spring's @Async during integration test?

I have seen that:

You can... Create a test configuration or simply override the task executor with a SyncTaskExecutor

but I do not understand how to do.

Any advice ? Thanks

答:
If a unique profile name is used when the tests are run (e.g. "test"), then the easiest way to disable async when running tests is with

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.EnableAsync;

@Profile("!test")
@Configuration
@EnableAsync
public class AsyncConfiguration {

}
```
<p>In my case I had to add the following to <code>src/test/resources/application.yml</code> to ensure tests are run under a profile named "test"</p>
<pre class="lang-yaml prettyprint-override"><code>spring:
  profiles:
    active: test
</code>```

Body:
If a unique profile name is used when the tests are run (e.g. "test"), then the easiest way to disable async when running tests is with

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.EnableAsync;

@Profile("!test")
@Configuration
@EnableAsync
public class AsyncConfiguration {

}

In my case I had to add the following to src/test/resources/application.yml to ensure tests are run under a profile named "test"

spring:
  profiles:
    active: test


问:
Display data From Firebase RTDB using Vue.js
Noob on Vue.js here. I've been trying to display the data retrieved from a Firebase Realtime Database.

To set up the project, I have done the following:

Ran npm install -g vue-cli to install vue.js;

Scaffolded an application using vue init webpack test (I accepted the default settings by pressing enter);

Ran npm install to install all dependencies;

Then I proceeded to edit some files. First, I added

import { rtdbPlugin } from 'vuefire'
Vue.use(rtdbPlugin)
```
<p>to the file at <code>./src/main.js</code>.</p>
<p>In <code>./src/App.vue</code> file, I wrote the following:</p>
<pre class="lang-html prettyprint-override"><code><template>
  <div id='app'>
    <!-- This should display all the data retrieved from Firebase RTDB -->
    <div v-for='(message) in messages'>
      <h4>{{ message.title }}</h4>
      <p>{{ message.text }}</p>
      <p>{{ message.timestamp }}</p>
    </div>
  </div>
</template>

<script>
import { initializeApp } from 'firebase/app'

// Using the Realtime Database feature from firebase
import { getDatabase, ref } from 'firebase/database'

// The config options
let config = {
  apiKey: <apiKey>,
  authDomain: <authDomain>,
  databaseURL: <databaseURL>,
  projectId: <projectId>,
  storageBucket: <storageBucket>,
  messagingSenderId: messagingSenderId,
  appId: <appID>
}

// Initialize Firebase
const app = initializeApp(config)

// Obtain the reference to our messages database object
const db = getDatabase(app)

let messagesRef = ref(db, 'messages')

export default {
  name: 'app',
  // Export the messages object in the Vue data object
  data () {
    messages: messagesRef
  }
}
</script>
</code>```

Those are all the changes I've made to the project.

When I ran the project using npm run dev, nothing happens on the page, i.e., the list is not displayed. On the Console tab of DevTools I get nothing but the following:

[HMR] Waiting for update signal from WDS...
vue.esm.js?efeb:9121 Download the Vue Devtools extension for a better development experience: https://github.com/vuejs/vue-devtools
```

I have no clue on what could be wrong. How could I fix this?

Please, let me know if any more information is needed.

Thanks in advance!

答:
After some research I found that vuefire isn't yet compatible to Firebase v9, which was the version installed when I ran npm install vuefire firebase --save. Then I installed the Firebase v7 using npm i firebase@7.24.0 and changed the App.vue code to:

// Import the individual SDK components to be used.
import firebase from 'firebase/app'
import 'firebase/database'

// The config options
let config = {
  apiKey: <apiKey>,
  authDomain: <authDomain>,
  databaseURL: <databaseURL>,
  projectId: <projectId>,
  storageBucket: <storageBucket>,
  messagingSenderId: messagingSenderId,
  appId: <appID>
}

let app = firebase.initializeApp(config)

// Obtain the reference to our messages database object
let db = app.database()
let messagesRef = db.ref('messages')

export default {
  name: 'app',
  // Export the messages object in the Vue data object
  data () {
    return {
      messages: []
    }
  },
  firebase: {
    messages: messagesRef
  }
}
```

I followed the instructions from Vuefire Docs. The main.js was left untouched.

I don't know whether this is the unique or the best solution, but it solved my problem: the list is rendered as expected (at least on the local server created by running npm run dev command).

Body:
Noob on Vue.js here. I've been trying to display the data retrieved from a Firebase Realtime Database.

To set up the project, I have done the following:

Ran npm install -g vue-cli to install vue.js;

Scaffolded an application using vue init webpack test (I accepted the default settings by pressing enter);

Ran npm install to install all dependencies;

Then I proceeded to edit some files. First, I added

import { rtdbPlugin } from 'vuefire'
Vue.use(rtdbPlugin)

to the file at ./src/main.js.

In ./src/App.vue file, I wrote the following:

<template>

{{ message.title }}

{{ message.text }}

{{ message.timestamp }}

</template>

Those are all the changes I've made to the project.

When I ran the project using npm run dev, nothing happens on the page, i.e., the list is not displayed. On the Console tab of DevTools I get nothing but the following:

[HMR] Waiting for update signal from WDS...
vue.esm.js?efeb:9121 Download the Vue Devtools extension for a better development experience: https://github.com/vuejs/vue-devtools

I have no clue on what could be wrong. How could I fix this?

Please, let me know if any more information is needed.

Thanks in advance!

Body:
After some research I found that vuefire isn't yet compatible to Firebase v9, which was the version installed when I ran npm install vuefire firebase --save. Then I installed the Firebase v7 using npm i firebase@7.24.0 and changed the App.vue code to:

// Import the individual SDK components to be used.
import firebase from 'firebase/app'
import 'firebase/database'

// The config options
let config = {
  apiKey: <apiKey>,
  authDomain: <authDomain>,
  databaseURL: <databaseURL>,
  projectId: <projectId>,
  storageBucket: <storageBucket>,
  messagingSenderId: messagingSenderId,
  appId: <appID>
}

let app = firebase.initializeApp(config)

// Obtain the reference to our messages database object
let db = app.database()
let messagesRef = db.ref('messages')

export default {
  name: 'app',
  // Export the messages object in the Vue data object
  data () {
    return {
      messages: []
    }
  },
  firebase: {
    messages: messagesRef
  }
}

I followed the instructions from Vuefire Docs. The main.js was left untouched.

I don't know whether this is the unique or the best solution, but it solved my problem: the list is rendered as expected (at least on the local server created by running npm run dev command).


问:
Rest API design: Managing access to sub-entities
Note: I realize that this is close to being off-topic for being opinion-based, but I am hoping that there is some accepted best practice to handle this that I just don't know about.

My problem is the following: I need to design a Rest API for a program where users can create their own projects, and each project contains files that can only be seen by users that have access. I am stuck with how to design the "List all files of a project" query.

Standard Rest API practice would suggest two endpoints, like:

```<code>`GET /projects`     # List all projects
`POST /projects`    # Create new project
`GET /projects/id`  # Get specific project
etc.
</code>```

and the same for the files of a project.

However, there should never be a reason to list all files - only the files of a single project. To make it more complicated, access management needs to be a thing, users should never see files that are in projects they don't have access to.

I can see multiple ways to handle that:

So the obvious way is to implement the GET function, optionally with a filter. However, this isn't optimal, since if the user doesn't set a filter, it would have to crawl through all projects, check for each project whether the user has access, and then list all files the user has access to:

GET /files?project=test1

I could also make the files command a subcommand of the projects command - e.g.

GET /projects/#id/files

However, I have the feeling this isn't too restful, since it doesn't expose entities directly?

Is there any concencus on which should usually be implemented? Is it okay to "force" users to set a parameter in the first one? Or is there a third alternative that solves what I am looking for? Happy about any literature recommendations on how to design this as well.

答:
After looking further, I came across this document from Microsoft. Some quotes:

Also consider the relationships between different types of resources and how you might expose these associations. For example, the /customers/5/orders might represent all of the orders for customer 5. You could also go in the other direction, and represent the association from an order back to a customer with a URI such as /orders/99/customer. However, extending this model too far can become cumbersome to implement. A better solution is to provide navigable links to associated resources in the body of the HTTP response message. This mechanism is described in more detail in the section Use HATEOAS to enable navigation to related resources.

In more complex systems, it can be tempting to provide URIs that enable a client to navigate through several levels of relationships, such as /customers/1/orders/99/products. However, this level of complexity can be difficult to maintain and is inflexible if the relationships between resources change in the future. Instead, try to keep URIs relatively simple. Once an application has a reference to a resource, it should be possible to use this reference to find items related to that resource. The preceding query can be replaced with the URI /customers/1/orders to find all the orders for customer 1, and then /orders/99/products to find the products in this order.

This makes me think that using solution 2 is probably the best case for me, since each file will be associated with only a single project, and should be deleted when a project is deleted. Files cannot exist on their own, outside of projects.

Body:
Note: I realize that this is close to being off-topic for being opinion-based, but I am hoping that there is some accepted best practice to handle this that I just don't know about.

My problem is the following: I need to design a Rest API for a program where users can create their own projects, and each project contains files that can only be seen by users that have access. I am stuck with how to design the "List all files of a project" query.

Standard Rest API practice would suggest two endpoints, like:

`GET /projects`     # List all projects
`POST /projects`    # Create new project
`GET /projects/id`  # Get specific project
etc.

and the same for the files of a project.

However, there should never be a reason to list all files - only the files of a single project. To make it more complicated, access management needs to be a thing, users should never see files that are in projects they don't have access to.

I can see multiple ways to handle that:

So the obvious way is to implement the GET function, optionally with a filter. However, this isn't optimal, since if the user doesn't set a filter, it would have to crawl through all projects, check for each project whether the user has access, and then list all files the user has access to:

GET /files?project=test1

I could also make the files command a subcommand of the projects command - e.g.

GET /projects/#id/files

However, I have the feeling this isn't too restful, since it doesn't expose entities directly?

Is there any concencus on which should usually be implemented? Is it okay to "force" users to set a parameter in the first one? Or is there a third alternative that solves what I am looking for? Happy about any literature recommendations on how to design this as well.


问:
How to add item to an array in Mongodb?
I am having trouble in appending data into an array in mongodb.
This is my schema:

const userSchema=mongoose.Schema({
    name: String,
    email: String,
    password: String,
    blog: [{
        date: Date,
        post: String
    }],
    week: [{
        weekday: String,
        tasks:[String]
    }],
    todo: [String]
});

const User= mongoose.model("User", userSchema);```
</div>
</div>
</p>
<p>I want to add data to todo but it is not working. Here is the code for that:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>app.post("/list", (req,res) =>{
    console.log(req.body);
    const user = req.body.userid;
    const item = req.body.data;

    console.log(user);
    console.log(item);
    User.findOne({_id: user}, function(err, foundUser){
        if(err){
            console.log(err);
        } else{
            foundUser.todo.push(item);
            foundUser.save();
            res.send("ToDo Updated");
        }
    });
});</code>```

I am getting user and item from the frontend. When I am console logging foundUser then I am getting the user but I am not able to add item to it.

答:
It's cause the save() is an async method, try using await</p>
```<code>app.post("/list", (req,res) =>{
    console.log(req.body);
    const user = req.body.userid;
    const item = req.body.data;

    console.log(user);
    console.log(item);
    User.findOne({_id: user}, async function(err, foundUser){
        if(err){
            console.log(err);
        } else{
            foundUser.todo.push(item);
            await foundUser.save();
            res.send("ToDo Updated");
        }
    });
});
</code>```

Title: How to add item to an array in Mongodb?

Body:
I am having trouble in appending data into an array in mongodb.
This is my schema:

const userSchema=mongoose.Schema({
    name: String,
    email: String,
    password: String,
    blog: [{
        date: Date,
        post: String
    }],
    week: [{
        weekday: String,
        tasks:[String]
    }],
    todo: [String]
});

const User= mongoose.model("User", userSchema);

I want to add data to todo but it is not working. Here is the code for that:

app.post("/list", (req,res) =>{
    console.log(req.body);
    const user = req.body.userid;
    const item = req.body.data;

    console.log(user);
    console.log(item);
    User.findOne({_id: user}, function(err, foundUser){
        if(err){
            console.log(err);
        } else{
            foundUser.todo.push(item);
            foundUser.save();
            res.send("ToDo Updated");
        }
    });
});

I am getting user and item from the frontend. When I am console logging foundUser then I am getting the user but I am not able to add item to it.

Body:
It's cause the save() is an async method, try using await

app.post("/list", (req,res) =>{
    console.log(req.body);
    const user = req.body.userid;
    const item = req.body.data;

    console.log(user);
    console.log(item);
    User.findOne({_id: user}, async function(err, foundUser){
        if(err){
            console.log(err);
        } else{
            foundUser.todo.push(item);
            await foundUser.save();
            res.send("ToDo Updated");
        }
    });
});


问:
refactoring problem with one of my classes
i wrote a program and i named my class StatusListActivity which extend Activity  and is the launcher and main class. I tried refactoring it by  changing the name to something else and whenever i tried to run the application, it closes please do you have an idea of what the problem was.

答:
I guess you are developing for Android? In that case, you might have changed the default launcher activity, which you have to reset in the deployment options of your project.

Also, you have to be aware, that by simply renaming a function, you have not changed any references on the code itself. For that, you have to use a proper refactoring-function as e.g. provided by Eclipse in the "Refactor"-Menu.


问:
ASP.NET5 WebAPI Session with redirect
I'm trying to store a session in my WebAPI's first method, and get it from a second method.
I'm using HttpContext.Session.SetString and I've included the required "app.useSession" and             services.AddDistributedMemoryCache(), services.AddSession() methods in my statup file.

The problem is, my first method has a return type of "RedirectResult" and at the and of it is doing a "new Redirect("http:// ...")"

And then when I try to run the second method, the session is null. I assume because the session cookie headers sent to the browser in the first method are being overridden by the redirect.

So what would be the way to do it?
I'm trying to store a code_verifier string (for OAuth PKCE implementation) and then redirect to an OAuth code request endpoint

Update: It seems my initial suspicion was incorrect. This has nothing to do with the redirect.
When the OAuth server redirects back to my second WebAPI's method, it does this via POST. And for some reason the cookies (including the
AspNetCore.Session cookie) are not being sent unlike when I try to make the request via a normal GET in the browser...

I do see the SameSite for the AspNetCore.Session cookie is set to LAX.
So how can I do this..?

答:
A "LAX" cookie doesn't allow it to be carried over when the request comes via POST from a 3rd party.

The problem was resolved by setting the SameSite property for the .NET core session cookie to "None". This also requires that the Secure flag be set to "true" and the WebAPI runs over https.

The previous session cookie had to be removed manually from the browser for this to take affect.

```<code>        services.AddSession(options =>
        {
            options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None;
            options.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always;
        });

        services.AddSession();
</code>```

Title: ASP.NET5 WebAPI Session with redirect

Body:
A "LAX" cookie doesn't allow it to be carried over when the request comes via POST from a 3rd party.

The problem was resolved by setting the SameSite property for the .NET core session cookie to "None". This also requires that the Secure flag be set to "true" and the WebAPI runs over https.

The previous session cookie had to be removed manually from the browser for this to take affect.

        services.AddSession(options =>
        {
            options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None;
            options.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always;
        });

        services.AddSession();


问:
how i can converti string arabica to date format English Wit flutter frome الثلاثاء 01 يونيو 2021 to 01/05/2021
from

```<code>الثلاثاء 01 يونيو 2021
</code>```

to

```<code>01/05/2021
</code>```

how i can convert string arabic to date format English with flutter from الثلاثاء 01 يونيو 2021 to 01/05/2021 jj/mm/yyyy dart language form string to

答:
I FOUND THE SOLUTION</p>
```<code>static int checkarabicdate(Date) {
    String mm ="";

    String dt = Date.substring(Date.indexOf(RegExp(r'[0-9]')),Date.length-1);
    print(dt);
    var currentDate = DateTime.now();

    String formattedDate = DateFormat('dd/MM/yyyy').format(currentDate);

    DateTime date1 = new DateFormat('dd/MM/yyyy').parse(formattedDate);
    print(date1);

    List<String> validadeSplit = dt.split(' ');

    String day = validadeSplit[0].toString();
    print(day);
    String month = validadeSplit[1].toString();
    print(month);
    String year = validadeSplit[2].toString();
    print(year);

    //   var  parsedDate = DateTime.parse('$year-$month-$day 00:00:00.000');

      if(month=="يناير") {
        mm = "01";
      }
      else if(month=="فبراير") {
        mm = "02";
      }
      else if(month=="مارس") {
        mm = "03";
      }

      else if(month=="أبريل") {
        mm = "04";
      }

      else if(month=="مايو") {
        mm = "05";
      }
      else if(month=="يونيو") {
        mm = "06";
      }
      else if(month=="يوليو") {
        mm = "07";
      }
      else if(month=="أغسطس") {
        mm = "08";
      }
      else if(month=="سبتمبر") {
        mm = "09";
      }
      else if(month=="أكتوبر") {
        mm = "10";
      }
      else if(month=="نوفمبر") {
        mm = "11";
      }
      else if(month=="ديسمبر") {
        mm = "12";
      }
      else mm ="01";

    DateTime start = DateTime.parse('$year-$mm-$day'.replaceAll(' ', ''));

    print(start);
    // DateTime date2= new   DateFormat('dd/MM/yyyy').parse(date);
    //print(parsedDate);
    date1 = DateTime(date1.year, date1.month, date1.day);
    start = DateTime(start.year, start.month, start.day);
    final differenceInDays = (date1.difference(start).inHours / 24).round();
    print('$differenceInDays');

    return differenceInDays;
  }
</code>```

Body:
from

الثلاثاء 01 يونيو 2021

to

01/05/2021

how i can convert string arabic to date format English with flutter from الثلاثاء 01 يونيو 2021 to 01/05/2021 jj/mm/yyyy dart language form string to

Body:
I FOUND THE SOLUTION

static int checkarabicdate(Date) {
    String mm ="";

    String dt = Date.substring(Date.indexOf(RegExp(r'[0-9]')),Date.length-1);
    print(dt);
    var currentDate = DateTime.now();

    String formattedDate = DateFormat('dd/MM/yyyy').format(currentDate);

    DateTime date1 = new DateFormat('dd/MM/yyyy').parse(formattedDate);
    print(date1);

    List<String> validadeSplit = dt.split(' ');

    String day = validadeSplit[0].toString();
    print(day);
    String month = validadeSplit[1].toString();
    print(month);
    String year = validadeSplit[2].toString();
    print(year);

    //   var  parsedDate = DateTime.parse('$year-$month-$day 00:00:00.000');

      if(month=="يناير") {
        mm = "01";
      }
      else if(month=="فبراير") {
        mm = "02";
      }
      else if(month=="مارس") {
        mm = "03";
      }

      else if(month=="أبريل") {
        mm = "04";
      }

      else if(month=="مايو") {
        mm = "05";
      }
      else if(month=="يونيو") {
        mm = "06";
      }
      else if(month=="يوليو") {
        mm = "07";
      }
      else if(month=="أغسطس") {
        mm = "08";
      }
      else if(month=="سبتمبر") {
        mm = "09";
      }
      else if(month=="أكتوبر") {
        mm = "10";
      }
      else if(month=="نوفمبر") {
        mm = "11";
      }
      else if(month=="ديسمبر") {
        mm = "12";
      }
      else mm ="01";

    DateTime start = DateTime.parse('$year-$mm-$day'.replaceAll(' ', ''));

    print(start);
    // DateTime date2= new   DateFormat('dd/MM/yyyy').parse(date);
    //print(parsedDate);
    date1 = DateTime(date1.year, date1.month, date1.day);
    start = DateTime(start.year, start.month, start.day);
    final differenceInDays = (date1.difference(start).inHours / 24).round();
    print('$differenceInDays');

    return differenceInDays;
  }


问:
Not allowed to make request to local host - swift
I am unable to post to a server in swift 5, XCode Version 11.6 (11E708), and iOS 13.6. I am receiving this error:

```<code>2020-08-26 08:20:55.252545-0400 iris[1642:721953] Task <BBB3809B-7BEF-4F60-9685-774027ADA7E6>.<1> finished with error [-1022] Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo={NSUnderlyingError=0x2810ad710 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}, NSErrorFailingURLStringKey=http://localhost:8000/searchImage/, NSErrorFailingURLKey=http://localhost:8000/searchImage/, NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.}
error=Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo={NSUnderlyingError=0x2810ad710 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}, NSErrorFailingURLStringKey=http://localhost:8000/searchImage/, NSErrorFailingURLKey=http://localhost:8000/searchImage/, NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.}
</code>```

I have followed this question How can I delete derived data in Xcode 8? and updated my info.plist

```<code><key> App Transport Security Settings </key>
<dict>
    <key> Allow Arbitrary Loads </key>
    <true />
</code>```

Note I don't care about security at this point. Additionally, I've tried a clean build and then deleted my derived data folder, but still I cannot post to the server. In another project I set this key in Info.plist and everything was fine. Any suggestions?

答:
Opened your Project target's info.plist file and added a Key called NSAppTransportSecurity as a Dictionary.

Add NSAllowsArbitraryLoads as Boolean and set its value to YES under NSAppTransportSecurity as like following image -

Body:
I am unable to post to a server in swift 5, XCode Version 11.6 (11E708), and iOS 13.6. I am receiving this error:

2020-08-26 08:20:55.252545-0400 iris[1642:721953] Task <BBB3809B-7BEF-4F60-9685-774027ADA7E6>.<1> finished with error [-1022] Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo={NSUnderlyingError=0x2810ad710 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}, NSErrorFailingURLStringKey=http://localhost:8000/searchImage/, NSErrorFailingURLKey=http://localhost:8000/searchImage/, NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.}
error=Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo={NSUnderlyingError=0x2810ad710 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}, NSErrorFailingURLStringKey=http://localhost:8000/searchImage/, NSErrorFailingURLKey=http://localhost:8000/searchImage/, NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.}

I have followed this question How can I delete derived data in Xcode 8? and updated my info.plist

<key> App Transport Security Settings </key>
<dict>
    <key> Allow Arbitrary Loads </key>
    <true />

Note I don't care about security at this point. Additionally, I've tried a clean build and then deleted my derived data folder, but still I cannot post to the server. In another project I set this key in Info.plist and everything was fine. Any suggestions?


问:
ngIf ngElse for dynamic data form web api in angular
I have dynamic data from API, here's the html:

```<code><table mat-table [dataSource]="dataSource" matSort matTableResponsive>

      <!-- ID Column -->
      <ng-container matColumnDef="id">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> ID </th>
        <td mat-cell *matCellDef="let row  let i = index;"> {{i+1}}  </td>
      </ng-container>

      <!-- Name Column -->
      <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
        <td mat-cell *matCellDef="let row"> {{row.name}} </td>
      </ng-container>

       <!-- PaymentType Column -->
       <ng-container matColumnDef="type">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> PaymentType </th>
        <td mat-cell *matCellDef="let row"> {{row.type}} </td>
      </ng-container>

    </table>
</code>```

From this html page I have 2 rows which are from the web-API and this last column {{row.type}} value can be 0 or 1.

How do I declare the if else statement?

My condition is:

```<code>  if(row.type==1)
     {
      online
     }
    else
     {
      offline
     }
</code>```

How do I implement my requirement from the above in the angular material table?

答:
Well, you can just simply use *ngIf directive:

```<code><ng-container matColumnDef="type">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> PaymentType </th>
    <td mat-cell *matCellDef="let row">
        <!-- There is nothing to stop you from adding more HTML here :) -->
        <span *ngIf="row.type === 1; else oflineType">Online</span>
    </td>
</ng-container>

<!-- This template can be anythwhere in your .html file -->
<ng-template #oflineType>
    offline
</ng-template>
</code>```

You might also want to use ternary operator syntax like this:

```<code><ng-container matColumnDef="type">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> PaymentType </th>
    <td mat-cell *matCellDef="let row">
        {{ row.type === 1 ? 'Online' : 'Offline' }}
    </td>
</ng-container>
</code>```

There are also more sophisticated ways to achieve that with pipes, maps etc. However i think this should be enough for your needs.

// Edit

If you want to use multiple conditions i would suggest function approach

```<code>// Your template .html
<ng-container matColumnDef="type">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> PaymentType </th>
    <td mat-cell *matCellDef="let row">
        {{ typeToString(row.type) }}
    </td>
</ng-container>

// Your controller .component.ts
typeToString(_type: number) {
    let stringType: string = 'default';
    // You can use if/switch there
    switch(_type) {
        case 1:
            stringType = 'online';
            break;
        case 2:
            stringType = 'offline';
            break;
        case 3:
            stringType = 'hidden';
            break;
        case 4:
            stringType = 'do not disturb';
            break;
    }

    return stringType;
}
</code>```

Body:
I have dynamic data from API, here's the html:

      <ng-container matColumnDef="id">
         ID
         {{i+1}}
      </ng-container>

      <ng-container matColumnDef="name">
         Name
         {{row.name}}
      </ng-container>

       <ng-container matColumnDef="type">
         PaymentType
         {{row.type}}
      </ng-container>

From this html page I have 2 rows which are from the web-API and this last column {{row.type}} value can be 0 or 1.

How do I declare the if else statement?

My condition is:

  if(row.type==1)
     {
      online
     }
    else
     {
      offline
     }

How do I implement my requirement from the above in the angular material table?

Body:
Well, you can just simply use *ngIf directive:

<ng-container matColumnDef="type">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> PaymentType </th>
    <td mat-cell *matCellDef="let row">
        <!-- There is nothing to stop you from adding more HTML here :) -->
        <span *ngIf="row.type === 1; else oflineType">Online</span>
    </td>
</ng-container>

<!-- This template can be anythwhere in your .html file -->
<ng-template #oflineType>
    offline
</ng-template>

You might also want to use ternary operator syntax like this:

<ng-container matColumnDef="type">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> PaymentType </th>
    <td mat-cell *matCellDef="let row">
        {{ row.type === 1 ? 'Online' : 'Offline' }}
    </td>
</ng-container>

There are also more sophisticated ways to achieve that with pipes, maps etc. However i think this should be enough for your needs.

// Edit

If you want to use multiple conditions i would suggest function approach

// Your template .html
<ng-container matColumnDef="type">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> PaymentType </th>
    <td mat-cell *matCellDef="let row">
        {{ typeToString(row.type) }}
    </td>
</ng-container>

// Your controller .component.ts
typeToString(_type: number) {
    let stringType: string = 'default';
    // You can use if/switch there
    switch(_type) {
        case 1:
            stringType = 'online';
            break;
        case 2:
            stringType = 'offline';
            break;
        case 3:
            stringType = 'hidden';
            break;
        case 4:
            stringType = 'do not disturb';
            break;
    }

    return stringType;
}


问:
Prevent selection of same dates react-day-picker
I'm using react-day-picker and I when startDate is selected I want to prevent selection of same date. how is that possible? I tried incrementing startDate by 1 and set It as disabledDays before property but It messed up selection. so which is proper way to achieve this?</p>
```<code> disabledDays = {
      before: startDate,
    };
</code>```

答:
Maybe there is an easier way, but I achieved this using this:</p>
```<code>handleDayClick(day) {
    if (this.state.from && DateUtils.isSameDay(day, this.state.from)) return;
    const range = DateUtils.addDayToRange(day, this.state);
    this.setState(range);
  }
</code>```

Body:
I'm using react-day-picker and I when startDate is selected I want to prevent selection of same date. how is that possible? I tried incrementing startDate by 1 and set It as disabledDays before property but It messed up selection. so which is proper way to achieve this?

 disabledDays = {
      before: startDate,
    };

Body:
Maybe there is an easier way, but I achieved this using this:

handleDayClick(day) {
    if (this.state.from && DateUtils.isSameDay(day, this.state.from)) return;
    const range = DateUtils.addDayToRange(day, this.state);
    this.setState(range);
  }


问:
How to get "tag name", "attribute name", "attribute value" in regex?
I'm trying to write a regular expression that needs to return every tag name, attribute name, and attribute value

Here is the code example

```<code>Hello, My name is Jack, This is my selfie:
[img id='4' src="imageurl"]
Below is the quick-link to my profile
[profile username='jackisbest']
</code>```

I need to get any text enclosed in [ ]

Also I need javascript regex to parse them and match them this way

```<code>> Match 1: img

> Match 2: id='4'
  Group 1: id
  Group 2: 4

> Match 3: src="imageurl"
  Group 1: src
  Group 2: imageurl
</code>```

This is the regex I am using, but it can only match attributes and value

```<code>(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']
</code>```

Thanks!!

答:
If you want to take the opening [ and the closing ] into account and the quantifier in the lookbehind is supported, you can use:

```<code>(?<=\[(\w+\b)[^\][\n]*)([^\s=]+)=['"]([^'"]*)['"](?=[^\][\n]*])
</code>```

(?<= Positive lookbehind to assert what is on the left is

\[ Match [

(\w+\b) Capture group 1, match 1+ word characters

[^\][\n]* Optionally match any char except [ ] or a newline

) Close the lookbehind

([^\s=]+)=['"]([^'"]*)['"] Capture group 2 and group 3 for the key and value

(?=[^\][\n]*]) Assert a ] to the right

Regex demo

The pattern has in group 1 the value of the value right after the opening [ and group 2 and group 3 are the values of the key and value pairs:

const regex = /(?<=\[(\w+\b)[^\][\n]*)([^\s=]+)=['"]([^'"]*)['"](?=[^\][\n]*])/g;
const str = `Hello, My name is Jack, This is my selfie:
[img id='4' src="imageurl"]
Below is the quick-link to my profile
[profile username='jackisbest' a='b']`;
let m;

console.log(Array.from(str.matchAll(regex), m => [m[1], m[2], m[3]]));```

Body:
I'm trying to write a regular expression that needs to return every tag name, attribute name, and attribute value

Here is the code example

Hello, My name is Jack, This is my selfie:
[img id='4' src="imageurl"]
Below is the quick-link to my profile
[profile username='jackisbest']

I need to get any text enclosed in [ ]

Also I need javascript regex to parse them and match them this way

> Match 1: img

> Match 2: id='4'
  Group 1: id
  Group 2: 4

> Match 3: src="imageurl"
  Group 1: src
  Group 2: imageurl

This is the regex I am using, but it can only match attributes and value

(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']

Thanks!!

Body:
If you want to take the opening [ and the closing ] into account and the quantifier in the lookbehind is supported, you can use:

(?<=\[(\w+\b)[^\][\n]*)([^\s=]+)=['"]([^'"]*)['"](?=[^\][\n]*])

(?<= Positive lookbehind to assert what is on the left is

\[ Match [

(\w+\b) Capture group 1, match 1+ word characters

[^\][\n]* Optionally match any char except [ ] or a newline

) Close the lookbehind

([^\s=]+)=['"]([^'"]*)['"] Capture group 2 and group 3 for the key and value

(?=[^\][\n]*]) Assert a ] to the right

Regex demo

The pattern has in group 1 the value of the value right after the opening [ and group 2 and group 3 are the values of the key and value pairs:

const regex = /(?<=\[(\w+\b)[^\][\n]*)([^\s=]+)=['"]([^'"]*)['"](?=[^\][\n]*])/g;
const str = `Hello, My name is Jack, This is my selfie:
[img id='4' src="imageurl"]
Below is the quick-link to my profile
[profile username='jackisbest' a='b']`;
let m;

console.log(Array.from(str.matchAll(regex), m => [m[1], m[2], m[3]]));