问:
Can multiple Android Applications(same device) share same key-pair for Passwordless Authentication using FIDO 2 Protocol?
Problem Statement:

I want to solve the user authentication on Android applications using the FIDO2 protocol(by providing an SDK), without doing multiple registration ceremonies for different applications on the same device.
For example, If a user has been Registered(generated Public-Private key pair) in an Android application A, he/she shall not be required to Registered in an Android application B(Given App A and App B are on the same device).

What could be the possible Solutions(as per my knowledge):-

A common SDK integrated with application A and B to provide authentication.

Separate Authentication App.

I want to go forward with Solution 1 as Solution 2 might not be desirable because it needs an extra step of downloading an extra app(Authentication App).

What am I able to achieve right now:-
We are able to do passwordless authentication of a user for app A and app B by maintaining separate private keys for app A and app B .

In the above diagram:-

User XYZ logs-in to App A and registers himself with app A on this device.

During the registration step a Public-private key pair is generated by the authenticator.

PrivateKey_1(PrivateKey) gets created and is stored in the Keystore and PublicKey_1(PublicKey) gets created and is shared with the server.

Let's say now that User XYZ wants to login to the app B.
Same process gets repeated for user XYZ to register him with app B.

In this process, A PrivateKey_2 gets created and is stored in the Keystore and PublicKey_2 gets created and is shared with the server.

So in above scenario User XYZ is able to authenticate on App A and App B using private key PrivateKey_1 and PrivateKey_2 respectively.

I want to know the feasibility of the following Scenario?
I want to do passwordless authentication of user XYZ for app A and app B, where applications(app A and app B) can use the same credentials (public and private key pair ) and do not need to perform a repeated registration ceremony(creating public and private key) for the same user on the same device for multiple applications sharing the common SDK(app A and app B).

In the above diagram:-

User XYZ logs-in to App A and registers himself with app A on this device.

In this process, a PrivateKey_1 gets created and is stored in the Keystore and
PublicKey_1 gets created and is shared with the server.

User XYZ wants to login to the app B.

App B should be able to verify user XYZ using the previously generated
credentials(by app A).

Is this even possible? Is there any gap in my understanding?

Any Suggestion and help is really appreciable :) :)

答: Are these accounts registered on the same service? Reading the Android FIDO2 API Interoperability with your website section, it seems possible to host https://example.com/.well-known/assetlinks.json with multiple Android apps listed.


来源: stackexchange

问:
How to count the length between two characters in a string
Hey I'm trying to create a function that takes in a string and a letter as arguments, identifies if there are two of this letter within the string, and then returns the number of characters between the two plus the letters.
So 'Saturday' and 'a' would return 6.

```<code>def sublength(string, char):
    new_string = ''
    for i in string:
        if i == char:
            new_string.append(i)
            if i != char:
                new_string.append(i)
                if i == char:
                    new_string.append(i)
                    break
    return len(new_string)

</code>```

What I want to do is iterate through string until char is found, add this character to new_string, continue to iterate and add the subsequent characters until char is found again, add it and then stop. This would be done in one iteration. However, as it's currently constructed, my function iterates through all of the string looking for matches and then stops.
How do I either do this in one iteration or break up the string to achieve the same functionality?
Thanks!

If you can provide a solution in JS as well I would really appreciate it!!

答:
Little long solution:-</p>
```<code>public static int getCharBetween(String s, char c){
        if(s.equals(null) ||s.length()==0){
            return -1;
        }
        char[] ch=s.toCharArray();
        List<Integer> list= new ArrayList<>();
        for(char cha:ch){
            if(cha==c){
                list.add(s.indexOf(cha));
                s=s.substring(s.indexOf(cha)+1, s.length()-1);
                if(list.size()==2){
                    break;
                }
            }
        }
        if(list.size()==0){
            return -1;
        }
        return (list.get(1)-list.get(0))-1;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hey I'm trying to create a function that takes in a string and a letter as arguments, identifies if there are two of this letter within the string, and then returns the number of characters between the two plus the letters.
So 'Saturday' and 'a' would return 6.

def sublength(string, char):
    new_string = ''
    for i in string:
        if i == char:
            new_string.append(i)
            if i != char:
                new_string.append(i)
                if i == char:
                    new_string.append(i)
                    break
    return len(new_string)

What I want to do is iterate through string until char is found, add this character to new_string, continue to iterate and add the subsequent characters until char is found again, add it and then stop. This would be done in one iteration. However, as it's currently constructed, my function iterates through all of the string looking for matches and then stops.
How do I either do this in one iteration or break up the string to achieve the same functionality?
Thanks!

If you can provide a solution in JS as well I would really appreciate it!!

Body:
Little long solution:-

public static int getCharBetween(String s, char c){
        if(s.equals(null) ||s.length()==0){
            return -1;
        }
        char[] ch=s.toCharArray();
        List<Integer> list= new ArrayList<>();
        for(char cha:ch){
            if(cha==c){
                list.add(s.indexOf(cha));
                s=s.substring(s.indexOf(cha)+1, s.length()-1);
                if(list.size()==2){
                    break;
                }
            }
        }
        if(list.size()==0){
            return -1;
        }
        return (list.get(1)-list.get(0))-1;
}


答:
FIDO2 credentials can be reused wherever the API is available so long as you reference the same RP ID whenever you attempt authentication. FIDO credentials are bound to a unique RP ID, and as long as you can prove ownership of an RP ID then you'll be able to request authentication with any credentials associated to that same RP ID.

In the case of Android, you'll be able to auth across apps so long as both apps are connected to a single website and its unique RP ID. To connect your app to a website, check out the FIDO2 API for Android docs, particularly its section on Interoperability with your website. It links to Google's page for setting up Digital Asset Links on your site so that you can prove ownership of an RP ID and use credentials associated with it for authentication across apps.

Once your apps and website are linked and the user has registered in one app you should then be able to use Fido2ApiClient.getSignPendingIntent() to authenticate in your second app so long as you specify your site's RP ID (the same one specified during registration) as the rpId in the PublicKeyCredentialRequestOptions you pass to the method.

P.S. What's nice about all of this is that credentials you register using Fido2ApiClient (or any equivalent API on other platforms for that matter) in a native app can later be used to log into your website using the WebAuthn API in the browser; you just need to reference the same RP ID in the PublicKeyCredentialRequestOptions you pass to WebAuthn's navigator.credentials.get()!

Title: Can multiple Android Applications(same device) share same key-pair for Passwordless Authentication using FIDO 2 Protocol?

Body:
Problem Statement:

I want to solve the user authentication on Android applications using the FIDO2 protocol(by providing an SDK), without doing multiple registration ceremonies for different applications on the same device.
For example, If a user has been Registered(generated Public-Private key pair) in an Android application A, he/she shall not be required to Registered in an Android application B(Given App A and App B are on the same device).

What could be the possible Solutions(as per my knowledge):-

A common SDK integrated with application A and B to provide authentication.

Separate Authentication App.

I want to go forward with Solution 1 as Solution 2 might not be desirable because it needs an extra step of downloading an extra app(Authentication App).

What am I able to achieve right now:-
We are able to do passwordless authentication of a user for app A and app B by maintaining separate private keys for app A and app B .

In the above diagram:-

User XYZ logs-in to App A and registers himself with app A on this device.

During the registration step a Public-private key pair is generated by the authenticator.

PrivateKey_1(PrivateKey) gets created and is stored in the Keystore and PublicKey_1(PublicKey) gets created and is shared with the server.

Let's say now that User XYZ wants to login to the app B.
Same process gets repeated for user XYZ to register him with app B.

In this process, A PrivateKey_2 gets created and is stored in the Keystore and PublicKey_2 gets created and is shared with the server.

So in above scenario User XYZ is able to authenticate on App A and App B using private key PrivateKey_1 and PrivateKey_2 respectively.

I want to know the feasibility of the following Scenario?
I want to do passwordless authentication of user XYZ for app A and app B, where applications(app A and app B) can use the same credentials (public and private key pair ) and do not need to perform a repeated registration ceremony(creating public and private key) for the same user on the same device for multiple applications sharing the common SDK(app A and app B).

In the above diagram:-

User XYZ logs-in to App A and registers himself with app A on this device.

In this process, a PrivateKey_1 gets created and is stored in the Keystore and
PublicKey_1 gets created and is shared with the server.

User XYZ wants to login to the app B.

App B should be able to verify user XYZ using the previously generated
credentials(by app A).

Is this even possible? Is there any gap in my understanding?

Any Suggestion and help is really appreciable :) :)


问:
Clear Entity Framework context on exception
I am working on an ASP.NET MVC website, and am using Entity Framework to save/update data into my database.

I am using ninject to inject dbContext into my repository class like below:

```<code>public class MyRepository : IMyRepository
{
    MyContext _context;

    public MyRepository(MyContext context)
    {
        _context = context;
    }

    // more code ...
</code>```

This is how I am injecting the context using ninject:

```<code>kernel.Bind<MyContext>().ToSelf().InSingletonScope();
</code>```

And I am using the injected dbContext as below to save the data into my database:

```<code>public void InsertModel(MyModel r)
{
    _context.MyModel.Add(r);
    _context.SaveChanges();
}
</code>```

Now, the problem I am facing is that if an exception occurs (for example if I purposely pass an invalid Model), Entity Framework will throw an exception. The invalid entity remains in the dbContext and all further save attempts will fail because of that.

I have been googling this issue and found This Article which suggests putting save / update operation in a try / catch block. If any exception occurs, it suggests to clear dbContext in the catch block.

Is this the correct appraoch? It sounds like a lot of work to put a try / catch around every save operation and clear the dbContext? I Would appreciate any help on explaining the correct approach for clearing the context.

答:
Try to use this code after your exception!</p>
```<code>foreach (var dbEntityEntry in _context.ChangeTracker.Entries().ToArray()) {
    if (dbEntityEntry.Entity != null) {
        dbEntityEntry.State = Microsoft.EntityFrameworkCore.EntityState.Detached;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am working on an ASP.NET MVC website, and am using Entity Framework to save/update data into my database.

I am using ninject to inject dbContext into my repository class like below:

public class MyRepository : IMyRepository
{
    MyContext _context;

    public MyRepository(MyContext context)
    {
        _context = context;
    }

    // more code ...

This is how I am injecting the context using ninject:

kernel.Bind<MyContext>().ToSelf().InSingletonScope();

And I am using the injected dbContext as below to save the data into my database:

public void InsertModel(MyModel r)
{
    _context.MyModel.Add(r);
    _context.SaveChanges();
}

Now, the problem I am facing is that if an exception occurs (for example if I purposely pass an invalid Model), Entity Framework will throw an exception. The invalid entity remains in the dbContext and all further save attempts will fail because of that.

I have been googling this issue and found This Article which suggests putting save / update operation in a try / catch block. If any exception occurs, it suggests to clear dbContext in the catch block.

Is this the correct appraoch? It sounds like a lot of work to put a try / catch around every save operation and clear the dbContext? I Would appreciate any help on explaining the correct approach for clearing the context.

Body:
Try to use this code after your exception!

foreach (var dbEntityEntry in _context.ChangeTracker.Entries().ToArray()) {
    if (dbEntityEntry.Entity != null) {
        dbEntityEntry.State = Microsoft.EntityFrameworkCore.EntityState.Detached;
    }
}


问:
Changing the href on gplus & facebook buttons using javascript
My website is [link-removed] and when you change the page from the main menu it uses ajax to load the main content div, this means the social buttons on the right are still pointing to the original page you landed on, how can I update them along with the page content?

I have tried

```<code>$('.sidebar g\\:like').attr("href", x);
$('.sidebar fb\\:like').attr("href", x);
</code>```

But doesn't seem to work

Any ideas? I am surprised I couldn't find a somebody with a similar problem...

答:
Both of those buttons are iFrames, so you wont be able to do that unless you use the facebook JS API for facebook. I dont think g+ has a non-iframe solution..

You would need to swap the entire button out with something like:

```<code>$('#social').html('<iframes to facebook and g+ buttons />');
</code>```

Body:
My website is [link-removed] and when you change the page from the main menu it uses ajax to load the main content div, this means the social buttons on the right are still pointing to the original page you landed on, how can I update them along with the page content?

I have tried

$('.sidebar g\\:like').attr("href", x);
$('.sidebar fb\\:like').attr("href", x);

But doesn't seem to work

Any ideas? I am surprised I couldn't find a somebody with a similar problem...

Body:
Both of those buttons are iFrames, so you wont be able to do that unless you use the facebook JS API for facebook. I dont think g+ has a non-iframe solution..

You would need to swap the entire button out with something like:

$('#social').html('<iframes to facebook and g+ buttons />');


问:
Display used coupons description on WooCommerce admin orders list
i want to display used coupons on WooCommerce admin orders list with the coupon description. So i'm using Display used coupons on WooCommerce admin orders list answer code and the used coupon code is shown, but can't include the used coupon description.

How is that possible?

答:
You can coupon object by WC_Coupon class and use $coupon->get_description() to get coupon description. try the below code.

```<code>function woo_customer_order_coupon_column_for_orders( $columns ) {
    $new_columns = array();
    foreach ( $columns as $column_key => $column_label ) {
        if ( 'order_total' === $column_key ) {
            $new_columns['order_coupons'] = __('coupons', 'woocommerce');
        }
        $new_columns[$column_key] = $column_label;
    }
    return $new_columns;
}
add_filter( 'manage_edit-shop_order_columns', 'woo_customer_order_coupon_column_for_orders' );

function woo_display_customer_order_coupon_in_column_for_orders( $column ) {
    global $the_order;
    if( $column  == 'order_coupons' ) {
        if( $coupons = $the_order->get_used_coupons() ) {
            foreach( $coupons as $coupon_code ){
                $coupon = new WC_Coupon($coupon_code);
                if( $coupon ){
                    echo "<span class='coupon-name'><b>".$coupon->code."</b></span>";
                    echo "<p class='coupon-description'>".$coupon->get_description()."</p>";
                }
            }
        } else {
            echo '<small><em>'. __('No Coupon') . '</em></small>';
        }
    }
}
add_action( 'manage_shop_order_posts_custom_column' , 'woo_display_customer_order_coupon_in_column_for_orders' );
</code>```

Tested and works

Body:
You can coupon object by WC_Coupon class and use $coupon->get_description() to get coupon description. try the below code.

function woo_customer_order_coupon_column_for_orders( $columns ) {
    $new_columns = array();
    foreach ( $columns as $column_key => $column_label ) {
        if ( 'order_total' === $column_key ) {
            $new_columns['order_coupons'] = __('coupons', 'woocommerce');
        }
        $new_columns[$column_key] = $column_label;
    }
    return $new_columns;
}
add_filter( 'manage_edit-shop_order_columns', 'woo_customer_order_coupon_column_for_orders' );

function woo_display_customer_order_coupon_in_column_for_orders( $column ) {
    global $the_order;
    if( $column  == 'order_coupons' ) {
        if( $coupons = $the_order->get_used_coupons() ) {
            foreach( $coupons as $coupon_code ){
                $coupon = new WC_Coupon($coupon_code);
                if( $coupon ){
                    echo "<span class='coupon-name'><b>".$coupon->code."</b></span>";
                    echo "<p class='coupon-description'>".$coupon->get_description()."</p>";
                }
            }
        } else {
            echo '<small><em>'. __('No Coupon') . '</em></small>';
        }
    }
}
add_action( 'manage_shop_order_posts_custom_column' , 'woo_display_customer_order_coupon_in_column_for_orders' );

Tested and works


问:
Flutter: StereamBuilder and Firebase RealTime
Hello I'am new in programming and aspecialy with flutter, i'm bulding a simple app to wrinte and read data from firebase database i have did a lot of research but i alawys have problems with syntax,
this is my data : enter image description here

this is my code for reading data  :

```<code>final Database = FirebaseDatabase.instance.ref('Users').child(UserId);

late DatabaseReference databaseReference;

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

 StreamBuilder(
            stream: Database.orderByKey().onValue,
            builder: (context, snapshot) {
              final tilesList = <ListTile>[];
              if (snapshot.hasData) {
                final myRobots = Map<dynamic, dynamic>.from((snapshot.data! as Event ).snapshot.value);
                myRobots.forEach((key, value) {
                  final nextRobot = Map<dynamic, dynamic>.from(value);
                  final RobotlTile = ListTile(
                      title: Text(nextRobot['Robot1']),
                      subtitle: Text(nextRobot['id']),
                  );
                  tilesList.add(RobotlTile);
                });
              }
              return Expanded(
                child: ListView(
                  children: tilesList,
                ),
              );
            },
          ),
</code>```

But i have a problem (The getter 'snapshot' isn't defined for the type 'Event'.) with snapshot.value afte final myRobots

答: See this answer from another question</p>

Body:
Hello I'am new in programming and aspecialy with flutter, i'm bulding a simple app to wrinte and read data from firebase database i have did a lot of research but i alawys have problems with syntax,
this is my data : enter image description here

this is my code for reading data  :

final Database = FirebaseDatabase.instance.ref('Users').child(UserId);

late DatabaseReference databaseReference;

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

 StreamBuilder(
            stream: Database.orderByKey().onValue,
            builder: (context, snapshot) {
              final tilesList = <ListTile>[];
              if (snapshot.hasData) {
                final myRobots = Map<dynamic, dynamic>.from((snapshot.data! as Event ).snapshot.value);
                myRobots.forEach((key, value) {
                  final nextRobot = Map<dynamic, dynamic>.from(value);
                  final RobotlTile = ListTile(
                      title: Text(nextRobot['Robot1']),
                      subtitle: Text(nextRobot['id']),
                  );
                  tilesList.add(RobotlTile);
                });
              }
              return Expanded(
                child: ListView(
                  children: tilesList,
                ),
              );
            },
          ),

But i have a problem (The getter 'snapshot' isn't defined for the type 'Event'.) with snapshot.value afte final myRobots

Body: See this answer from another question


问:
airflow.exceptions.AirflowException: PythonVirtualenvOperator requires virtualenv, please install it
I set up my airflow using pypi. An error occurred after start the airflow server by below command:
airflow standalone

airflow_version == 2.2.0

python_version == 3.8.4

but i have installed virtualenv.

Exception as below:

```<code>  Broken DAG: [/usr/local/python3/lib/python3.8/site-
  packages/airflow/example_dags/example_python_operator.py] Traceback
  (most recent call last):
  File "/usr/local/python3/lib/python3.8/site-
  packages/airflow/models/baseoperator.py", line 188, in apply_defaults
  result = func(self,*args,**kwargs)
  File "/usr/local/python3/lib/python3.8/site-
  packages/airflow/operators/python.py", line 342, in __init__
  raise AirflowException('PythonVirtualenvOperator requires virtualenv,
  please install it.')
  airflow.exceptions.AirflowException: PythonVirtualenvOperator requires
  virtualenv, please install it
</code>```

I have no idea to fix the bug, don't know what's wrong happen.

thank everyone very much!

答:
We had the same issue running this in Google Cloud Build when trying to upgrade Airflow.

On closer inpection, it looks like Airflow uses the which command to check if virtualenv exists. Because we were using pip install virtualenv --user to persist package installations between build steps, we needed to add export PATH="/builder/home/.local/bin:$$PATH" to our build script.

To see if this will work for you:

after install run which virtualenv to see if it finds the virtualenv command

if it doesn't, add the folder that virtualenv was installed in to your PATH and try starting the Airflow server again

Body:
I set up my airflow using pypi. An error occurred after start the airflow server by below command:
airflow standalone

airflow_version == 2.2.0

python_version == 3.8.4

but i have installed virtualenv.

Exception as below:

  Broken DAG: [/usr/local/python3/lib/python3.8/site-
  packages/airflow/example_dags/example_python_operator.py] Traceback
  (most recent call last):
  File "/usr/local/python3/lib/python3.8/site-
  packages/airflow/models/baseoperator.py", line 188, in apply_defaults
  result = func(self,*args,**kwargs)
  File "/usr/local/python3/lib/python3.8/site-
  packages/airflow/operators/python.py", line 342, in __init__
  raise AirflowException('PythonVirtualenvOperator requires virtualenv,
  please install it.')
  airflow.exceptions.AirflowException: PythonVirtualenvOperator requires
  virtualenv, please install it

I have no idea to fix the bug, don't know what's wrong happen.

thank everyone very much!


问:
Is there a python linter that checks if the type hint comes from the typing module?
I am looking for a python linter that checks if type hints come from the typing module.

As in, this:

def  func(arg: list)-> None:
   """ does something """
```
<p>should be:</p>
<pre class="lang-py prettyprint-override"><code>from typing import List

def  func(arg: List)-> None:
   """ does something """
</code>```

答:
To answer, you can use mypy.
On a note typing.List is deprecated since 3.9

Body:
I am looking for a python linter that checks if type hints come from the typing module.

As in, this:

def  func(arg: list)-> None:
   """ does something """

should be:

from typing import List

def  func(arg: List)-> None:
   """ does something """


问:
How can I test the responsiveness of my website on my Android device
I'm building a website on my Android device and I want to test its responsiveness on other devices (desktop and tablet) on my Android device. How can I do that?</p>

答:
There are many ways to accomplish this, maybe for a start you can use:

Developer tools from Chrome where it gives you a variety of different devices and screen sizes.

You can use ngrok to create an instant URL of your localhost where you can use it to test from your personal android device.

There more different ways to do but I would say this is a good start to jump in and explore yourself


问:
No operator matches the given name and argument types. You might need to add explicit type casts -- PostgreSQL 14.1
I'm a beginner in SQL and I use PostgreSQL.
My database is a list of real estate transactions, 1 row = 1 sale.
Here is a description of my tables :

```<code>CREATE TABLE adresse (
id SERIAL,
num_voie SMALLINT,
bis_ter VARCHAR(10),
type_voie VARCHAR(30),
voie VARCHAR(50),
cp VARCHAR(10),
ville VARCHAR(100));

CREATE TABLE bien(
id SERIAL,
type_bien VARCHAR(30),
surf_bien SMALLINT,
nbr_piece SMALLINT);

CREATE TABLE vente (
id SERIAL,
date_vente DATE,
prix_vente INTEGER,
id_adresse INTEGER,
id_bien INTEGER);
</code>```

Also, 'id_adresse' is a FK referencing adresse (id) and 'id_bien' is a FK referencing bien (id).

Here is my problem : when I try to calculate the rate of evolution of sales between the first and the second quarter with this query :

```<code>WITH vente_T1 AS (
SELECT count(*) FROM vente WHERE date_vente BETWEEN '2020-01-01' AND '2020-03-31'),
vente_T2 AS (
SELECT count(*) FROM vente WHERE date_vente BETWEEN '2020-04-01' AND '2020-06-30')
SELECT vente_T2-vente_T1 FROM vente_T1, vente_T2;
</code>```

I have this error :

```<code>ERROR:  operator does not exist: record - record
LINE 5: SELECT vente_T2-vente_T1 FROM vente_T1, vente_T2;
HINT: No operator matches the given name and argument types.
You might need to add explicit type casts.
SQL state: 42883 Character: 216
</code>```

I have seen in another topic "This was due to the WHERE clause contains String value instead of integer value."

But I don't know how I can calculate the rate of evolution of sales without specify dates.

答:
Your immediate problem is the expression vente_T2-vente_T1 - you can't subtract a complete record from another record. You can only do that for columns. However in order to access the column within the CTE, you should give them a proper alias:

```<code>WITH vente_T1 AS (
  SELECT count(*) as num_vente
  FROM vente
  WHERE date_vente BETWEEN '2020-01-01' AND '2020-03-31'
), vente_T2 AS (
  SELECT count(*) as num_vente
  FROM vente
  WHERE date_vente BETWEEN '2020-04-01' AND '2020-06-30'
)
SELECT vente_T2.num_vente - vente_T1.num_vente
--              ^ column name        ^ column name
FROM vente_T1
  cross join vente_T2;
</code>```

Body:
I'm a beginner in SQL and I use PostgreSQL.
My database is a list of real estate transactions, 1 row = 1 sale.
Here is a description of my tables :

CREATE TABLE adresse (
id SERIAL,
num_voie SMALLINT,
bis_ter VARCHAR(10),
type_voie VARCHAR(30),
voie VARCHAR(50),
cp VARCHAR(10),
ville VARCHAR(100));

CREATE TABLE bien(
id SERIAL,
type_bien VARCHAR(30),
surf_bien SMALLINT,
nbr_piece SMALLINT);

CREATE TABLE vente (
id SERIAL,
date_vente DATE,
prix_vente INTEGER,
id_adresse INTEGER,
id_bien INTEGER);

Also, 'id_adresse' is a FK referencing adresse (id) and 'id_bien' is a FK referencing bien (id).

Here is my problem : when I try to calculate the rate of evolution of sales between the first and the second quarter with this query :

WITH vente_T1 AS (
SELECT count(*) FROM vente WHERE date_vente BETWEEN '2020-01-01' AND '2020-03-31'),
vente_T2 AS (
SELECT count(*) FROM vente WHERE date_vente BETWEEN '2020-04-01' AND '2020-06-30')
SELECT vente_T2-vente_T1 FROM vente_T1, vente_T2;

I have this error :

ERROR:  operator does not exist: record - record
LINE 5: SELECT vente_T2-vente_T1 FROM vente_T1, vente_T2;
HINT: No operator matches the given name and argument types.
You might need to add explicit type casts.
SQL state: 42883 Character: 216

I have seen in another topic "This was due to the WHERE clause contains String value instead of integer value."

But I don't know how I can calculate the rate of evolution of sales without specify dates.

Body:
Your immediate problem is the expression vente_T2-vente_T1 - you can't subtract a complete record from another record. You can only do that for columns. However in order to access the column within the CTE, you should give them a proper alias:

WITH vente_T1 AS (
  SELECT count(*) as num_vente
  FROM vente
  WHERE date_vente BETWEEN '2020-01-01' AND '2020-03-31'
), vente_T2 AS (
  SELECT count(*) as num_vente
  FROM vente
  WHERE date_vente BETWEEN '2020-04-01' AND '2020-06-30'
)
SELECT vente_T2.num_vente - vente_T1.num_vente
--              ^ column name        ^ column name
FROM vente_T1
  cross join vente_T2;


问:
Why do delegates in a none static class work like they are static C#
Hi I've modified some delegate tutorial code to experiment and I know there are prebuilt delegates available but without taking those into account.

I don't understand how the following works which I will break down:

```<code> class Program
{
     static void Main(string[] args)
    {
        Human human1 = new Human(20);

        BuffsProccessor buffsProccessor1 = new BuffsProccessor();
        BuffsProccessor buffsProccessor2 = new BuffsProccessor();
        BuffsCanAdd buffsCanAdd = new BuffsCanAdd();
        BuffsProccessor.BuffHandler buffHandler = buffsCanAdd.AddStrengthBoost;
        buffHandler += buffsCanAdd.AddIntelligenceBoost;
        buffsProccessor1.ProcessBuffs(human1, buffHandler);
        buffsProccessor2.ProcessBuffs(human1, buffHandler);
    }
}

public class BuffsProccessor
{
    public delegate void BuffHandler(Race race);

    public void ProcessBuffs(Race race, BuffHandler buffHandler)
    {
        buffHandler(race);
        race.ShowStats();
    }
}

public class BuffsCanAdd
{
    public void AddStrengthBoost(Race race)
    {
        System.Console.WriteLine("Adding strength boost");
    }

    public void AddIntelligenceBoost(Race race)
    {
        System.Console.WriteLine("Adding intelligence boost");
    }
}
</code>```

What I'm finding confusing is how come this line works like the class and delegate are static:

```<code>            BuffsProccessor.BuffHandler buffHandler = buffsCanAdd.AddStrengthBoost;
</code>```

the class and the delegate within the class are accessible without an instance of the BuffsProccessor class.

What is happening in memory when

```<code>BuffsProccessor.BuffHandler buffHandler = buffsCanAdd.AddStrengthBoost;
</code>```

the buffHandler is there I'm finding this so confusing I'm struggling to form my question. Since the new keyword isn't being used how and where is it being stored in memory if it isn't in an instance of the BuffProccessorClass?

I hope this makes sense I can't find any delegate tutorials that answers this specific question.

答:
What, do you mean, "without an instance of the BuffsProccessor class"? It's right there:

```<code>buffsCanAdd.AddStrengthBoost;
</code>```

See that buffsCanAdd? That's your instance. If it were a static method you could just say AddStrengthBoost without the object before it.

The reason it works is that delegates don't just keep a reference to a method, they can also store a reference to the object to invoke the method on. This is mandatory for delegates to non instance methods, because you can't just invoke those methods on thin air.

As for your second question, there is a new involved, it's just that since C# 2, you can skip it and the compiler will put it for you. Before that, you had to do it by hand:

```<code>BuffsProccessor.BuffHandler buffHandler = new BuffsProccessor.BuffHandler(buffsCanAdd.AddStrengthBoost);
</code>```

But now it's considered bad style.

Body:
Hi I've modified some delegate tutorial code to experiment and I know there are prebuilt delegates available but without taking those into account.

I don't understand how the following works which I will break down:

 class Program
{
     static void Main(string[] args)
    {
        Human human1 = new Human(20);

        BuffsProccessor buffsProccessor1 = new BuffsProccessor();
        BuffsProccessor buffsProccessor2 = new BuffsProccessor();
        BuffsCanAdd buffsCanAdd = new BuffsCanAdd();
        BuffsProccessor.BuffHandler buffHandler = buffsCanAdd.AddStrengthBoost;
        buffHandler += buffsCanAdd.AddIntelligenceBoost;
        buffsProccessor1.ProcessBuffs(human1, buffHandler);
        buffsProccessor2.ProcessBuffs(human1, buffHandler);
    }
}

public class BuffsProccessor
{
    public delegate void BuffHandler(Race race);

    public void ProcessBuffs(Race race, BuffHandler buffHandler)
    {
        buffHandler(race);
        race.ShowStats();
    }
}

public class BuffsCanAdd
{
    public void AddStrengthBoost(Race race)
    {
        System.Console.WriteLine("Adding strength boost");
    }

    public void AddIntelligenceBoost(Race race)
    {
        System.Console.WriteLine("Adding intelligence boost");
    }
}

What I'm finding confusing is how come this line works like the class and delegate are static:

            BuffsProccessor.BuffHandler buffHandler = buffsCanAdd.AddStrengthBoost;

the class and the delegate within the class are accessible without an instance of the BuffsProccessor class.

What is happening in memory when

BuffsProccessor.BuffHandler buffHandler = buffsCanAdd.AddStrengthBoost;

the buffHandler is there I'm finding this so confusing I'm struggling to form my question. Since the new keyword isn't being used how and where is it being stored in memory if it isn't in an instance of the BuffProccessorClass?

I hope this makes sense I can't find any delegate tutorials that answers this specific question.

Body:
What, do you mean, "without an instance of the BuffsProccessor class"? It's right there:

buffsCanAdd.AddStrengthBoost;

See that buffsCanAdd? That's your instance. If it were a static method you could just say AddStrengthBoost without the object before it.

The reason it works is that delegates don't just keep a reference to a method, they can also store a reference to the object to invoke the method on. This is mandatory for delegates to non instance methods, because you can't just invoke those methods on thin air.

As for your second question, there is a new involved, it's just that since C# 2, you can skip it and the compiler will put it for you. Before that, you had to do it by hand:

BuffsProccessor.BuffHandler buffHandler = new BuffsProccessor.BuffHandler(buffsCanAdd.AddStrengthBoost);

But now it's considered bad style.


问:
Why do I get `ActiveStorage::FileNotFoundError` when trying to seed the db with attachments?
I'm trying to seed my development database. One of the models Project has images associated with it.

I have put a placeholder image in ./db/seed_files/. My seed file looks like this:

```<code># Add projects
1000.times do
  project = Project.new(
    name: Faker::Marketing.buzzwords.capitalize,
    description: Faker::Lorem.sentence(rand(1..30))
  )
  image_file = File.open("./db/seed_files/placeholder_image.png")
  project.images.attach(io: image_file, filename: "placeholder_image.png", content_type: "image/png")
  project.save
end
</code>```

This runs fine. It attaches one image to each project.

However, I want to seed each project with multiple images. I thought I could attach the same image multiple times.

I have tried:

```<code># Add projects
1000.times do
  project = Project.new(
    name: Faker::Marketing.buzzwords.capitalize,
    description: Faker::Lorem.sentence(rand(1..30))
  )
  image_file = File.open("./db/seed_files/placeholder_image.png")
  rand(1..3).times do
    project.images.attach(io: image_file, filename: "placeholder_image.png", content_type: "image/png")
  end
  project.save
end
</code>```

But this results in an error: ActiveStorage::FileNotFoundError.

```<code>/Users/greidods/.rvm/gems/ruby-2.6.1/bundler/gems/rails-b366be3b5b28/activestorage/lib/active_storage/service/disk_service.rb:136:in `rescue in stream'
/Users/greidods/.rvm/gems/ruby-2.6.1/bundler/gems/rails-b366be3b5b28/activestorage/lib/active_storage/service/disk_service.rb:129:in `stream'
/Users/greidods/.rvm/gems/ruby-2.6.1/bundler/gems/rails-b366be3b5b28/activestorage/lib/active_storage/service/disk_service.rb:28:in `block in download'
/Users/greidods/.rvm/gems/ruby-2.6.1/bundler/gems/rails-b366be3b5b28/activesupport/lib/active_support/notifications.rb:180:in `block in instrument'
/Users/greidods/.rvm/gems/ruby-2.6.1/bundler/gems/rails-b366be3b5b28/activesupport/lib/active_support/notifications/instrumenter.rb:23:in `instrument'
...
</code>```

I have a feeling that there's a approach to seeding a row with multiple attachments.

What is causing this error? Why can I attach the image once but not multiple times?

答:
In my case, what I noticed is that attaching attachments with ActiveStorage is not working properly when doing it inside a transaction. This applies to migrations, seeds or callbacks.
What I finally did to avoid my logic being wrapped inside a transaction is to run the logic inside a thread:

Thread.new do
  # your logic here
end.join
```

Body:
I'm trying to seed my development database. One of the models Project has images associated with it.

I have put a placeholder image in ./db/seed_files/. My seed file looks like this:

# Add projects
1000.times do
  project = Project.new(
    name: Faker::Marketing.buzzwords.capitalize,
    description: Faker::Lorem.sentence(rand(1..30))
  )
  image_file = File.open("./db/seed_files/placeholder_image.png")
  project.images.attach(io: image_file, filename: "placeholder_image.png", content_type: "image/png")
  project.save
end

This runs fine. It attaches one image to each project.

However, I want to seed each project with multiple images. I thought I could attach the same image multiple times.

I have tried:

# Add projects
1000.times do
  project = Project.new(
    name: Faker::Marketing.buzzwords.capitalize,
    description: Faker::Lorem.sentence(rand(1..30))
  )
  image_file = File.open("./db/seed_files/placeholder_image.png")
  rand(1..3).times do
    project.images.attach(io: image_file, filename: "placeholder_image.png", content_type: "image/png")
  end
  project.save
end

But this results in an error: ActiveStorage::FileNotFoundError.

/Users/greidods/.rvm/gems/ruby-2.6.1/bundler/gems/rails-b366be3b5b28/activestorage/lib/active_storage/service/disk_service.rb:136:in `rescue in stream'
/Users/greidods/.rvm/gems/ruby-2.6.1/bundler/gems/rails-b366be3b5b28/activestorage/lib/active_storage/service/disk_service.rb:129:in `stream'
/Users/greidods/.rvm/gems/ruby-2.6.1/bundler/gems/rails-b366be3b5b28/activestorage/lib/active_storage/service/disk_service.rb:28:in `block in download'
/Users/greidods/.rvm/gems/ruby-2.6.1/bundler/gems/rails-b366be3b5b28/activesupport/lib/active_support/notifications.rb:180:in `block in instrument'
/Users/greidods/.rvm/gems/ruby-2.6.1/bundler/gems/rails-b366be3b5b28/activesupport/lib/active_support/notifications/instrumenter.rb:23:in `instrument'
...

I have a feeling that there's a approach to seeding a row with multiple attachments.

What is causing this error? Why can I attach the image once but not multiple times?


问:
How to resolve sql query In pandas
I am new to sql query and having a small problem , here i want to find "top 3 venues which hosted most number of eliminator matches" but I think my sql is wrong how to get this done?
(I'm using jupiter notebook and pyspark)

```<code>import pandas as pd
from pandasql import sqldf

pysqldf = lambda q: sqldf(q, globals())

from matplotlib import pyplot as plt

data2 = pd.read_csv('ipl_matches.csv')

data2

#Most number of eliminator matches
eliminator = data2[data2.eliminator == 'Y']
eliminator

##I'm having problem in this query##
q = """SELECT venue_id, eliminator
       FROM eliminator """

names = pysqldf(q)
names
</code>```

答:
See if this query works for you:</p>
```<code>q=""" SELECT venue_id
    FROM eliminator group by venue_id order by count(venue_id) desc LIMIT 3"""
</code>```

Title: How to resolve sql query In pandas

Body:
I am new to sql query and having a small problem , here i want to find "top 3 venues which hosted most number of eliminator matches" but I think my sql is wrong how to get this done?
(I'm using jupiter notebook and pyspark)

import pandas as pd
from pandasql import sqldf

pysqldf = lambda q: sqldf(q, globals())

from matplotlib import pyplot as plt

data2 = pd.read_csv('ipl_matches.csv')

data2

#Most number of eliminator matches
eliminator = data2[data2.eliminator == 'Y']
eliminator

##I'm having problem in this query##
q = """SELECT venue_id, eliminator
       FROM eliminator """

names = pysqldf(q)
names

Body:
See if this query works for you:

q=""" SELECT venue_id
    FROM eliminator group by venue_id order by count(venue_id) desc LIMIT 3"""


问:
How to create global variables once when app is launched in Go?
Good day for all readers!

I have api service which needs key for some decrypt issues. Key calculates all time when I make request. That is wrong from an architectural point of view.

The option with environments (.env, viper...) drops because, in the future, I want to bring out this module to a separate library.

Hint me, how it is possible without using environments to calculate the key when starting the application and use it until stopping the application?

答:
A global var starts with a capital, so it is reachable from within other packages.

But... it's actually bad behaviour, because those other packages can change it.

Having a non capital one, still means that functions in the same package can change it.

Perhaps you can use a constant?

or make a singleton variable, see :

https://goplay.tools/snippet/9k7FLYbbvoo


问:
Unexpected token, expected "," Eslint Typescript with Vue
I was getting this eslint error when trying to use vue's type assertion. here's an example:</p>
```<code>data: function () {
        return {
            sellerIdToListings: {} as any, // 'as' Unexpected token, expected ","
        }
    },
</code>```

答: I started putting packages that didn't come with vue-cli 1 by 1 until I realized the problem was with babel-eslint. After removing it from package-json and unparse it from eslintrc the problem was solved

Body:
I was getting this eslint error when trying to use vue's type assertion. here's an example:

data: function () {
        return {
            sellerIdToListings: {} as any, // 'as' Unexpected token, expected ","
        }
    },


问:
No overload matches this call. in React Stripe PaymentElement
I get this error

```<code>No overload matches this call.
  Overload 1 of 2, '(options: { elements: StripeElements; confirmParams?: Partial<ConfirmPaymentData> | undefined; redirect: "if_required"; }): Promise<PaymentIntentResult>', gave the following error.
    Property 'update' is missing in type 'import("/sandbox/node_modules/@stripe/stripe-js/types/index").StripeElements' but required in type 'import("/sandbox/node_modules/@stripe/stripe-js/types/stripe-js/elements-group").StripeElements'.ts(2769)
elements-group.d.ts(41, 3): 'update' is declared here.
stripe.d.ts(57, 5): The expected type comes from property 'elements' which is declared here on type '{ elements: StripeElements; confirmParams?: Partial<ConfirmPaymentData> | undefined; redirect: "if_required"; }'
</code>```

in the below code snippet

```<code>const handleSubmit = async (e: any) => {
    e.preventDefault();

    if (!stripe || !elements) {
      return;
    }

    setIsLoading(true);

    const { error } = await stripe.confirmPayment({
      elements,
      confirmParams: {
        // Make sure to change this to your payment completion page
        return_url: "http://localhost:3000"
      },
      redirect: "if_required"
    });

    if (error.type === "card_error" || error.type === "validation_error") {
      setMessage(error.message);
    } else {
      setMessage("An unexpected error occured.");
    }

    setIsLoading(false);
  };
</code>```

I get this code from the stripe docs into this codesandbox for testing purposes, before using it in the project I'm working on right now. As I found out this error occurs when parameter count is mismatched, but as I checked in the node-module for the stripe.confirmPayment() It has the same parameter list as passed here. I can't see the actual issue here, and the component is not loading also, I guess it's related to this error. when I use <CardElement> from stripe it works fine, I couldn't find any typescript-related docs for this either. If someone can point out the real issue here, that would be great. Please refer the full code in codesandbox

答:
You have a weird entry in your package.json

```<code>"@stripe/react-stripe-js ": "stripe/stripe-js",
"@stripe/react-stripe-js": "1.7.0",
"@stripe/stripe-js": "1.22.0",
</code>```

remove the first one and reinstall your deps, It should fix it.

Body:
I get this error

No overload matches this call.
  Overload 1 of 2, '(options: { elements: StripeElements; confirmParams?: Partial<ConfirmPaymentData> | undefined; redirect: "if_required"; }): Promise<PaymentIntentResult>', gave the following error.
    Property 'update' is missing in type 'import("/sandbox/node_modules/@stripe/stripe-js/types/index").StripeElements' but required in type 'import("/sandbox/node_modules/@stripe/stripe-js/types/stripe-js/elements-group").StripeElements'.ts(2769)
elements-group.d.ts(41, 3): 'update' is declared here.
stripe.d.ts(57, 5): The expected type comes from property 'elements' which is declared here on type '{ elements: StripeElements; confirmParams?: Partial<ConfirmPaymentData> | undefined; redirect: "if_required"; }'

in the below code snippet

const handleSubmit = async (e: any) => {
    e.preventDefault();

    if (!stripe || !elements) {
      return;
    }

    setIsLoading(true);

    const { error } = await stripe.confirmPayment({
      elements,
      confirmParams: {
        // Make sure to change this to your payment completion page
        return_url: "http://localhost:3000"
      },
      redirect: "if_required"
    });

    if (error.type === "card_error" || error.type === "validation_error") {
      setMessage(error.message);
    } else {
      setMessage("An unexpected error occured.");
    }

    setIsLoading(false);
  };

I get this code from the stripe docs into this codesandbox for testing purposes, before using it in the project I'm working on right now. As I found out this error occurs when parameter count is mismatched, but as I checked in the node-module for the stripe.confirmPayment() It has the same parameter list as passed here. I can't see the actual issue here, and the component is not loading also, I guess it's related to this error. when I use <CardElement> from stripe it works fine, I couldn't find any typescript-related docs for this either. If someone can point out the real issue here, that would be great. Please refer the full code in codesandbox

Body:
You have a weird entry in your package.json

"@stripe/react-stripe-js ": "stripe/stripe-js",
"@stripe/react-stripe-js": "1.7.0",
"@stripe/stripe-js": "1.22.0",

remove the first one and reinstall your deps, It should fix it.


问:
Print values from a spreadsheet with certain value in column
I'm developing an application to automate a task in the office where I work. It consists of accessing a spreadsheet with customer data and checking which tax needs to be sent to the customer.

After the code, name, national registration code, e-mail and customer taxation come the taxes, according to the spreadsheet model below;

https://prnt.sc/26tsjdx

If the x is marked in the tax column (in the case of the code below, the column F:DAS) then I take the data of that customer and put it in a named list integrantes.

The problem I'm facing is that at the time of a simple print to be able to return all the members of the list it returns multiple results and not just the ones with the x. Can you help me?

Follow code below:

```<code>import openpyxl

wb = openpyxl.load_workbook('C:/temp/fechamento.xlsx')
sheet = wb['fechamento']

lastCol = sheet.max_column

integrantes = {}
codigos = []
nomes = []
cnpjs = []
emails = []
tributacoes = []
das = []

for r in range(1, sheet.max_row + 1):
    for c in range(6, lastCol + 1):
        imposto1 = sheet.cell(row=r, column=c).value
        if imposto1 != 'x' or '':
            codigo = sheet.cell(row=r, column=1).value
            nome = sheet.cell(row=r, column=2).value
            cnpj = sheet.cell(row=r, column=3).value
            email = sheet.cell(row=r, column=4).value
            tributacao = sheet.cell(row=r, column=5).value
            das1 = sheet.cell(row=1, column=c).value
            codigos.append(codigo)
            nomes.append(nome)
            cnpjs.append(cnpj)
            emails.append(email)
            tributacoes.append(tributacao)
            das.append(das1)
            integrantes[nome] = email

            for codigo, nome, cnpj, email, tributacao, das1 in zip(codigos, nomes, cnpjs, emails, tributacoes, das):

                print(codigo, nome, cnpj, email, tributacao)
</code>```

答:
in your if statement, you have

```<code>if imposto1 != 'x' or '':
</code>```

if you are just trying to get the ones with x, it should just be x.

Also you say integrantes is a named list, but you have it defined as a dictionary because of the {}.

Body:
I'm developing an application to automate a task in the office where I work. It consists of accessing a spreadsheet with customer data and checking which tax needs to be sent to the customer.

After the code, name, national registration code, e-mail and customer taxation come the taxes, according to the spreadsheet model below;

https://prnt.sc/26tsjdx

If the x is marked in the tax column (in the case of the code below, the column F:DAS) then I take the data of that customer and put it in a named list integrantes.

The problem I'm facing is that at the time of a simple print to be able to return all the members of the list it returns multiple results and not just the ones with the x. Can you help me?

Follow code below:

import openpyxl

wb = openpyxl.load_workbook('C:/temp/fechamento.xlsx')
sheet = wb['fechamento']

lastCol = sheet.max_column

integrantes = {}
codigos = []
nomes = []
cnpjs = []
emails = []
tributacoes = []
das = []

for r in range(1, sheet.max_row + 1):
    for c in range(6, lastCol + 1):
        imposto1 = sheet.cell(row=r, column=c).value
        if imposto1 != 'x' or '':
            codigo = sheet.cell(row=r, column=1).value
            nome = sheet.cell(row=r, column=2).value
            cnpj = sheet.cell(row=r, column=3).value
            email = sheet.cell(row=r, column=4).value
            tributacao = sheet.cell(row=r, column=5).value
            das1 = sheet.cell(row=1, column=c).value
            codigos.append(codigo)
            nomes.append(nome)
            cnpjs.append(cnpj)
            emails.append(email)
            tributacoes.append(tributacao)
            das.append(das1)
            integrantes[nome] = email

            for codigo, nome, cnpj, email, tributacao, das1 in zip(codigos, nomes, cnpjs, emails, tributacoes, das):

                print(codigo, nome, cnpj, email, tributacao)

Body:
in your if statement, you have

if imposto1 != 'x' or '':

if you are just trying to get the ones with x, it should just be x.

Also you say integrantes is a named list, but you have it defined as a dictionary because of the {}.


问:
What is the best way to compare a value against 'undefined'?
Is there any differences between

```<code>var a;
(a == undefined)
(a === undefined)
((typeof a) == "undefined")
((typeof a) === "undefined")
</code>```

Which one should we use?

答:
If a is undefined, then

```<code>a == undefined
</code>```

will actually throw an error. Use

```<code>(typeof a) === "undefined"
</code>```

Instead.

Body:
Is there any differences between

var a;
(a == undefined)
(a === undefined)
((typeof a) == "undefined")
((typeof a) === "undefined")

Which one should we use?

Body:
If a is undefined, then

a == undefined

will actually throw an error. Use

(typeof a) === "undefined"

Instead.


答:
use this query :

```<code>q = """SELECT venue_id, eliminator FROM eliminator order by venue_id desc limit 3 """
</code>```

this will give you last 3 biggest venue_id in descending mode

Title: How to resolve sql query In pandas

Body:
use this query :

q = """SELECT venue_id, eliminator FROM eliminator order by venue_id desc limit 3 """

this will give you last 3 biggest venue_id in descending mode


问:
How to use `setState` callback on react hooks
React hooks introduces useState for setting component state. But how can I use hooks to replace the callback like below code:

```<code>setState(
  { name: "Michael" },
  () => console.log(this.state)
);
</code>```

I want to do something after the state is updated.

I know I can use useEffect to do the extra things but I have to check the state previous value which requires a bit code. I am looking for a simple solution which can be used with useState hook.

答:
I explored the use-state-with-callback npm library, and other similar custom hooks, but in the end I realized I can just do something like this:</p>
```<code>const [user, setUser] = React.useState(
  {firstName: 'joe', lastName: 'schmo'}
)

const handleFirstNameChange=(val)=> {
  const updatedUser = {
     ...user,
     firstName: val
  }
  setUser(updatedUser)
  updateDatabase(updatedUser)
}
</code>```

Body:
React hooks introduces useState for setting component state. But how can I use hooks to replace the callback like below code:

setState(
  { name: "Michael" },
  () => console.log(this.state)
);

I want to do something after the state is updated.

I know I can use useEffect to do the extra things but I have to check the state previous value which requires a bit code. I am looking for a simple solution which can be used with useState hook.

Body:
I explored the use-state-with-callback npm library, and other similar custom hooks, but in the end I realized I can just do something like this:

const [user, setUser] = React.useState(
  {firstName: 'joe', lastName: 'schmo'}
)

const handleFirstNameChange=(val)=> {
  const updatedUser = {
     ...user,
     firstName: val
  }
  setUser(updatedUser)
  updateDatabase(updatedUser)
}


问:
Error installing Tensorflow 2 on Windows 11: SSL Decryption Failed or Bad Record Mac
So I am having trouble installing Tensorflow on Windows 11. I'm using Anaconda with Python 3.7.0 and I'm trying to install Tensorflow 2.1.0. The problem I have is when I try to install tensorflow with conda install tensorflow or pip3 install tensorflow I get the following error every time after a few dependencies are installed:

The only thing I can think of is the internet connection is slow on my laptop, which has been the case ever since I upgraded to Windows 11. Is there anything I can do? When I tried to install an earlier version of Tensorflow (1.13.1) I finally got it to install after it got stuck on the MKL package. I just kept trying to install MKL individually until it installed. But when I try to upgrade to 2.1.0 I immediately get the above error before any dependencies are installed. Has anyone had this problem?

答:
I  have the same issue  while trying to update conda using :

conda update conda

I notice the difference after my organisation updated the firewa

enter image description here


问:
Get specific value from OData response in Postman
Can anyone of you can help me this:
i Have such response body from WebAPI:

```<code>{
    "value": "Created: \"salesorder\" : \"22a734c3-bf5f-ec11-80e6-0050568d2958\"
Found 0 vis1_anschlussadresses
Found 1 vis1_postleitzahls
Reusing: \"vis1_postleitzahl\" : \"0d9344c7-a45d-e711-80c5-955c5ca2a164\"
Found 1 vis1_orts
Reusing: \"vis1_ort\" : \"92734f57-375e-e711-80c5-955c5ca2a164\"
Created: \"vis1_anschlussadresse\" : \"67a734c3-bf5f-ec11-80e6-0050568d2958\"
Found 0 vis1_anschlussobjekts
Created: \"vis1_anschlussobjekt\" : \"6ba734c3-bf5f-ec11-80e6-0050568d2958\"
Found 0 vis1_infrastrukturinformations
Created: \"vis1_infrastrukturinformation\" : \"6fa734c3-bf5f-ec11-80e6-0050568d2958\"
Found 1 contacts
Reusing: \"contact\" : \"22530f60-285f-ec11-80e6-0050568d2958\"
Found 1 competitors
Reusing: \"competitor\" : \"7841f8e7-c211-ea11-80cd-0050568d3968\"
[0000]: Information: OK
"
}

</code>```

i'd like to get specific values from this response body e.g. 22a734c3-bf5f-ec11-80e6-0050568d2958 and store as a environment variable. Is it possible?

答:
The first observation is that the response is a standard serialized structure. Even if we deserialise the JSON payload, the value of value is this string, that seems to represent a form of execution log:

```<code>Created: "salesorder" : "22a734c3-bf5f-ec11-80e6-0050568d2958"
Found 0 vis1_anschlussadresses
Found 1 vis1_postleitzahls
Reusing: "vis1_postleitzahl" : "0d9344c7-a45d-e711-80c5-955c5ca2a164"
Found 1 vis1_orts
Reusing: "vis1_ort" : "92734f57-375e-e711-80c5-955c5ca2a164"
Created: "vis1_anschlussadresse" : "67a734c3-bf5f-ec11-80e6-0050568d2958"
Found 0 vis1_anschlussobjekts
Created: "vis1_anschlussobjekt" : "6ba734c3-bf5f-ec11-80e6-0050568d2958"
Found 0 vis1_infrastrukturinformations
Created: "vis1_infrastrukturinformation" : "6fa734c3-bf5f-ec11-80e6-0050568d2958"
Found 1 contacts
Reusing: "contact" : "22530f60-285f-ec11-80e6-0050568d2958"
Found 1 competitors
Reusing: "competitor" : "7841f8e7-c211-ea11-80cd-0050568d3968"
[0000]: Information: OK
</code>```

To specifically resolve the value 22a734c3-bf5f-ec11-80e6-0050568d2958 we need to make a few assumtions:

the value we are looking for is in the First line

the value is contained inside double quotes

the quoted value is the entire line content after the last full-colon character ;

the name of the environment variable is FirstGuid

Given those assumptions, we can write a Tests script to run after the request:

var logValue = pm.response.json().value;
var lines = logValue.split(/\r?\n/);
var lineOneTokens = lines[0].split(':');
var guid = lineOneTokens[lineOneTokens.length() - 1].trim().replace(/"/g,"");

pm.environment.set('FirstGuid', guid);
```

References:

Scripting in Postman

JavaScript - split string by new line character

How to Get the Last Element of an Array in JavaScript

I want to remove double quotes from a String

Body:
Can anyone of you can help me this:
i Have such response body from WebAPI:

{
    "value": "Created: \"salesorder\" : \"22a734c3-bf5f-ec11-80e6-0050568d2958\"
Found 0 vis1_anschlussadresses
Found 1 vis1_postleitzahls
Reusing: \"vis1_postleitzahl\" : \"0d9344c7-a45d-e711-80c5-955c5ca2a164\"
Found 1 vis1_orts
Reusing: \"vis1_ort\" : \"92734f57-375e-e711-80c5-955c5ca2a164\"
Created: \"vis1_anschlussadresse\" : \"67a734c3-bf5f-ec11-80e6-0050568d2958\"
Found 0 vis1_anschlussobjekts
Created: \"vis1_anschlussobjekt\" : \"6ba734c3-bf5f-ec11-80e6-0050568d2958\"
Found 0 vis1_infrastrukturinformations
Created: \"vis1_infrastrukturinformation\" : \"6fa734c3-bf5f-ec11-80e6-0050568d2958\"
Found 1 contacts
Reusing: \"contact\" : \"22530f60-285f-ec11-80e6-0050568d2958\"
Found 1 competitors
Reusing: \"competitor\" : \"7841f8e7-c211-ea11-80cd-0050568d3968\"
[0000]: Information: OK
"
}

i'd like to get specific values from this response body e.g. 22a734c3-bf5f-ec11-80e6-0050568d2958 and store as a environment variable. Is it possible?

Body:
The first observation is that the response is a standard serialized structure. Even if we deserialise the JSON payload, the value of value is this string, that seems to represent a form of execution log:

Created: "salesorder" : "22a734c3-bf5f-ec11-80e6-0050568d2958"
Found 0 vis1_anschlussadresses
Found 1 vis1_postleitzahls
Reusing: "vis1_postleitzahl" : "0d9344c7-a45d-e711-80c5-955c5ca2a164"
Found 1 vis1_orts
Reusing: "vis1_ort" : "92734f57-375e-e711-80c5-955c5ca2a164"
Created: "vis1_anschlussadresse" : "67a734c3-bf5f-ec11-80e6-0050568d2958"
Found 0 vis1_anschlussobjekts
Created: "vis1_anschlussobjekt" : "6ba734c3-bf5f-ec11-80e6-0050568d2958"
Found 0 vis1_infrastrukturinformations
Created: "vis1_infrastrukturinformation" : "6fa734c3-bf5f-ec11-80e6-0050568d2958"
Found 1 contacts
Reusing: "contact" : "22530f60-285f-ec11-80e6-0050568d2958"
Found 1 competitors
Reusing: "competitor" : "7841f8e7-c211-ea11-80cd-0050568d3968"
[0000]: Information: OK

To specifically resolve the value 22a734c3-bf5f-ec11-80e6-0050568d2958 we need to make a few assumtions:

the value we are looking for is in the First line

the value is contained inside double quotes

the quoted value is the entire line content after the last full-colon character ;

the name of the environment variable is FirstGuid

Given those assumptions, we can write a Tests script to run after the request:

var logValue = pm.response.json().value;
var lines = logValue.split(/\r?\n/);
var lineOneTokens = lines[0].split(':');
var guid = lineOneTokens[lineOneTokens.length() - 1].trim().replace(/"/g,"");

pm.environment.set('FirstGuid', guid);

References:

Scripting in Postman

JavaScript - split string by new line character

How to Get the Last Element of an Array in JavaScript

I want to remove double quotes from a String


问:
How to prevent highcharts smoothing my data?
Highcharts/Highstocks does unnecessary smoothing of the data. Any ideas what I am doing wrong?

Here is the chart with the data. Raw data is available here.

The full chart is weirdly smoothed, like that:

And if I plot the same data in Python (matplotlib) it looks different:

And if I zoom in the corresponding part in Highcharts, it looks as it should:

**UPDATE:
apparently this smoothing happens only in HighStocks. In pure Highcharts the chart looks exactly as in Python: https://codepen.io/chapkovski/pen/mdqwOrO

答:
The solution is disabling dataGrouping

    plotOptions: {
        series: {
            dataGrouping: {
                enabled: false
            }
        }
    },
```

For the future please do not duplicate the same topic on multiple support channels (https://www.highcharts.com/forum/viewtopic.php?f=12&t=48131)

Body:
The solution is disabling dataGrouping

    plotOptions: {
        series: {
            dataGrouping: {
                enabled: false
            }
        }
    },

For the future please do not duplicate the same topic on multiple support channels (https://www.highcharts.com/forum/viewtopic.php?f=12&t=48131)


问:
Android Override Multiple Classes in Activity
The immediate answer is no, this is not possible in Java. I understand that, and this is a bit of a noob question, but i've been coding this way for some time now and i've always sort of felt it was a dirty method so i'd like to clarify what I am doing. Say for instance I have an Activity that is extending the Activity class so I can use onCreate etc etc...within that Activity, I have a SimpleCursorAdapter that populates a ListView.

```<code>String sql = "SELECT * FROM myTable";
Cursor data = database.rawQuery(sql, null);
String fields[] = {"field1", "field2", "field3"};
adapter = new CustomCursorAdapter(this, R.layout.custom_row, data, fields, new int[] { R.id.Field1, R.id.Field2, R.id.Field2 });
list.setAdapter(adapter);
</code>```

I have named this CustomCursorAdapter because I am creating an entirely new class called CustomCursorAdapter that extends SimpleCursorAdapter so I can use methods such as bindView, newView etc to use buttons on my ListView objects.

```<code>public class CustomCursorAdapter extends SimpleCursorAdapter {

private Context myContext;
private myActivity parentActivity;
private Button delButton;

public CustomCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
    super(context, layout, c, from, to);
    myContext = context;
    parentActivity = (myActivity) myContext;

@Override
public void bindView(View view, Context context, Cursor cursor) {
    int idColumn = cursor.getColumnIndex("_id");
    final int getId = cursor.getInt(idColumn);
    final double increment = 0.25;

    UnitsConversions convert = new UnitsConversions();

    int nameColumn = cursor.getColumnIndex("name");
    String getName = cursor.getString(nameColumn);
    TextView name = (TextView)view.findViewById(R.id.GrainName);
    name.setText(getName);

    delButton = (Button)view.findViewById(R.id.DeleteButton);
    delButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View arg0) {
            parentActivity.deleteItem(getId);
        }
    });

@Override
public View newView(Context context, Cursor cursor, final ViewGroup parent) {
    View view = View.inflate(context, R.layout.list_item, null);
    return view;
}
</code>```

I have scaled my code down a lot here just to use as an example so if I removed anything that makes this non working code I appologize, but non-working code isn't the purpose of my question. My question is, is this the only way to override methods unless I extend the activity itself with a SimpleCursorAdapter? It doesn't seem like a big deal, but when I have 10 different activities, all doing basically the same thing but with different ListViews and items and I have to create 10 different CustomCursorAdapter's it seems dirty and redundant. Maybe there is a way to create only 1 other activity and then pass in the items I need? It seems like it would be a lot cleaner to just use SimpleCursorAdapter instead of having to create a custom one and override the methods I need right in the Activity. If I didn't name this question properly, please feel free to edit.

答: Yes, there is a nicer way. You can create a subclass of Activity (and declare it abstract if you like) which implements overrided versions of every method in which you share code across your 10 classes. Then for each real Activity you need, extend that subclass of Activity and just make the changes you need to each method. If a method is different in each class but shares most of its code with the other Activities, then you can call the general super.method() and then apply the specific changes.</p>

Body:
The immediate answer is no, this is not possible in Java. I understand that, and this is a bit of a noob question, but i've been coding this way for some time now and i've always sort of felt it was a dirty method so i'd like to clarify what I am doing. Say for instance I have an Activity that is extending the Activity class so I can use onCreate etc etc...within that Activity, I have a SimpleCursorAdapter that populates a ListView.

String sql = "SELECT * FROM myTable";
Cursor data = database.rawQuery(sql, null);
String fields[] = {"field1", "field2", "field3"};
adapter = new CustomCursorAdapter(this, R.layout.custom_row, data, fields, new int[] { R.id.Field1, R.id.Field2, R.id.Field2 });
list.setAdapter(adapter);

I have named this CustomCursorAdapter because I am creating an entirely new class called CustomCursorAdapter that extends SimpleCursorAdapter so I can use methods such as bindView, newView etc to use buttons on my ListView objects.

public class CustomCursorAdapter extends SimpleCursorAdapter {

private Context myContext;
private myActivity parentActivity;
private Button delButton;

public CustomCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
    super(context, layout, c, from, to);
    myContext = context;
    parentActivity = (myActivity) myContext;

@Override
public void bindView(View view, Context context, Cursor cursor) {
    int idColumn = cursor.getColumnIndex("_id");
    final int getId = cursor.getInt(idColumn);
    final double increment = 0.25;

    UnitsConversions convert = new UnitsConversions();

    int nameColumn = cursor.getColumnIndex("name");
    String getName = cursor.getString(nameColumn);
    TextView name = (TextView)view.findViewById(R.id.GrainName);
    name.setText(getName);

    delButton = (Button)view.findViewById(R.id.DeleteButton);
    delButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View arg0) {
            parentActivity.deleteItem(getId);
        }
    });

@Override
public View newView(Context context, Cursor cursor, final ViewGroup parent) {
    View view = View.inflate(context, R.layout.list_item, null);
    return view;
}

I have scaled my code down a lot here just to use as an example so if I removed anything that makes this non working code I appologize, but non-working code isn't the purpose of my question. My question is, is this the only way to override methods unless I extend the activity itself with a SimpleCursorAdapter? It doesn't seem like a big deal, but when I have 10 different activities, all doing basically the same thing but with different ListViews and items and I have to create 10 different CustomCursorAdapter's it seems dirty and redundant. Maybe there is a way to create only 1 other activity and then pass in the items I need? It seems like it would be a lot cleaner to just use SimpleCursorAdapter instead of having to create a custom one and override the methods I need right in the Activity. If I didn't name this question properly, please feel free to edit.


问:
How to encourage a balanced solution in ojAlgo ExpressionBasedModel
I have the following model:

```<code>        ExpressionsBasedModel model = new ExpressionsBasedModel();

        Variable va = model.addVariable("va")
                .lower(0);

        Variable vb = model.addVariable("vb")
                .lower(0);

        Variable vc = model.addVariable("vc")
                .lower(0);

        Variable vd = model.addVariable("vd")
                .lower(0);

        Variable ve = model.addVariable("ve")
                .lower(0);

        Expression ef = model.addExpression("ef")
                .lower(0);

        Expression eg = model.addExpression("eg")
                .lower(0);

        Expression eh = model.addExpression("eh")
                .lower(-240);

        Expression ei = model.addExpression("ei")
                .lower(0);

        Expression ej = model.addExpression("ej")
                .lower(0);

        Expression ek = model.addExpression("ek")
                .lower(0);

        Expression el = model.addExpression("el")
                .lower(-2000);

        ef.set(va, -50);
        el.set(va, -100);
        eg.set(va, 100);

        eh.set(vb, -30);
        ef.set(vb, 40);
        ej.set(vb, 20);

        ek.set(vc, -30);
        eg.set(vc, -30);
        ei.set(vc, 60);

        ei.set(vd, -30);
        eg.set(vd, -30);
        ek.set(vd, 60);

        ej.set(ve, -40);
        el.set(ve, -40);
        ek.set(ve, 20);

        ei.weight(1);
        ek.weight(1);

        /*
         * These next 2 lines required to get balanced solution.
         * Without them ei = 720 and ek = 0.
         */
//        ek.lower(360);
//        ei.lower(360);

        model.maximise();

        BasicLogger.debug(model);
</code>```

Although ei and ek are equally weighted, the solution I get is:

```<code>############################################
0 <= va: 6.4 <= 6.4
0 <= vb: 8 <= 8
0 <= vc: 15.111111 (300)
0 <= vd: 6.222222 (300)
0 <= ve: 4 (200) <= 4
0 <= ef: 0.0
0 <= eg: 0.0
-240 <= eh: -240.0
0 <= ei: 720.0
0 <= ej: 0.0
0 <= ek: -0.0
-2000 <= el: -800.0
############################################
</code>```

ei == 720, ek == 0.

I would prefer a solution in which ei and ek are as balanced as possible, (ei == 360, ek == 360). Is there some way of encoding that requirement for "as balanced as possible" as a weighted expression?

In this specific example I have commented out the lower value constraint that actually result in the behavior I want. In real life, the model is dynamic and I may have 5 equally weighted expressions. I won't know the correct values in order to set the lower constraints.

答:
For future readers, I was able to do this by first converting the values represented by ei and ek into new variables, with the existing expressions ei and ek constraining the value of the new variables to the value these expressions previously had. Then I added a new variable, weighted it heavily, and constrained it to be less than each of the new variables.

```<code>        Expression ei = model.addExpression("ei")
                .lower(0);

        Expression ek = model.addExpression("ek")
                .lower(0);
</code>```

became:

```<code>        Expression ei = model.addExpression("ei")
                .level(0);
        Variable vei = model.addVariable("vei")
                .lower(0);
        ei.set(vei, -1);

        Expression ek = model.addExpression("ek")
                .level(0);
        Variable vek = model.addVariable("vek")
                .lower(0);
        ek.set(vek, -1);
</code>```

Weighting became:

```<code>        vei.weight(1);
        vek.weight(1);
</code>```

And added balance variable and constraints:

```<code>        Variable balance = model.addVariable("balance")
                .weight(100);

        model.addExpression("balance constraint for vei")
                .set(vei, 1)
                .set(balance, -1)
                .lower(0);

        model.addExpression("balance constraint for vek")
                .set(vek, 1)
                .set(balance, -1)
                .lower(0);
</code>```

This results in a solution that is as balanced as possible:

```<code>############################################
0 <= va: 6.4 <= 6.4
0 <= vb: 8 <= 8
0 <= vc: 11.111111
0 <= vd: 10.222222
0 <= ve: 4 <= 4
0 <= vei: 360 (1)
0 <= vek: 360 (1)
balance: 360 (100)
0 <= ef: 0.0
0 <= eg: 0.0
-240 <= eh: -240.0
0 <= ei: 0.0 <= 0
0 <= ej: 0.0
0 <= ek: -0.0 <= 0
-2000 <= el: -800.0
0 <= balance constraint for vei: 0.0
0 <= balance constraint for vek: 0.0
############################################
</code>```

Body:
I have the following model:

        ExpressionsBasedModel model = new ExpressionsBasedModel();

        Variable va = model.addVariable("va")
                .lower(0);

        Variable vb = model.addVariable("vb")
                .lower(0);

        Variable vc = model.addVariable("vc")
                .lower(0);

        Variable vd = model.addVariable("vd")
                .lower(0);

        Variable ve = model.addVariable("ve")
                .lower(0);

        Expression ef = model.addExpression("ef")
                .lower(0);

        Expression eg = model.addExpression("eg")
                .lower(0);

        Expression eh = model.addExpression("eh")
                .lower(-240);

        Expression ei = model.addExpression("ei")
                .lower(0);

        Expression ej = model.addExpression("ej")
                .lower(0);

        Expression ek = model.addExpression("ek")
                .lower(0);

        Expression el = model.addExpression("el")
                .lower(-2000);

        ef.set(va, -50);
        el.set(va, -100);
        eg.set(va, 100);

        eh.set(vb, -30);
        ef.set(vb, 40);
        ej.set(vb, 20);

        ek.set(vc, -30);
        eg.set(vc, -30);
        ei.set(vc, 60);

        ei.set(vd, -30);
        eg.set(vd, -30);
        ek.set(vd, 60);

        ej.set(ve, -40);
        el.set(ve, -40);
        ek.set(ve, 20);

        ei.weight(1);
        ek.weight(1);

        /*
         * These next 2 lines required to get balanced solution.
         * Without them ei = 720 and ek = 0.
         */
//        ek.lower(360);
//        ei.lower(360);

        model.maximise();

        BasicLogger.debug(model);

Although ei and ek are equally weighted, the solution I get is:

############################################
0 <= va: 6.4 <= 6.4
0 <= vb: 8 <= 8
0 <= vc: 15.111111 (300)
0 <= vd: 6.222222 (300)
0 <= ve: 4 (200) <= 4
0 <= ef: 0.0
0 <= eg: 0.0
-240 <= eh: -240.0
0 <= ei: 720.0
0 <= ej: 0.0
0 <= ek: -0.0
-2000 <= el: -800.0
############################################

ei == 720, ek == 0.

I would prefer a solution in which ei and ek are as balanced as possible, (ei == 360, ek == 360). Is there some way of encoding that requirement for "as balanced as possible" as a weighted expression?

In this specific example I have commented out the lower value constraint that actually result in the behavior I want. In real life, the model is dynamic and I may have 5 equally weighted expressions. I won't know the correct values in order to set the lower constraints.

Body:
For future readers, I was able to do this by first converting the values represented by ei and ek into new variables, with the existing expressions ei and ek constraining the value of the new variables to the value these expressions previously had. Then I added a new variable, weighted it heavily, and constrained it to be less than each of the new variables.

        Expression ei = model.addExpression("ei")
                .lower(0);

        Expression ek = model.addExpression("ek")
                .lower(0);

became:

        Expression ei = model.addExpression("ei")
                .level(0);
        Variable vei = model.addVariable("vei")
                .lower(0);
        ei.set(vei, -1);

        Expression ek = model.addExpression("ek")
                .level(0);
        Variable vek = model.addVariable("vek")
                .lower(0);
        ek.set(vek, -1);

Weighting became:

        vei.weight(1);
        vek.weight(1);

And added balance variable and constraints:

        Variable balance = model.addVariable("balance")
                .weight(100);

        model.addExpression("balance constraint for vei")
                .set(vei, 1)
                .set(balance, -1)
                .lower(0);

        model.addExpression("balance constraint for vek")
                .set(vek, 1)
                .set(balance, -1)
                .lower(0);

This results in a solution that is as balanced as possible:

############################################
0 <= va: 6.4 <= 6.4
0 <= vb: 8 <= 8
0 <= vc: 11.111111
0 <= vd: 10.222222
0 <= ve: 4 <= 4
0 <= vei: 360 (1)
0 <= vek: 360 (1)
balance: 360 (100)
0 <= ef: 0.0
0 <= eg: 0.0
-240 <= eh: -240.0
0 <= ei: 0.0 <= 0
0 <= ej: 0.0
0 <= ek: -0.0 <= 0
-2000 <= el: -800.0
0 <= balance constraint for vei: 0.0
0 <= balance constraint for vek: 0.0
############################################


问:
How can I fork a github repository using command line only?
I want to create a fork of a public github repository using the command line only. How can I do that?</p>

答:
You can use GitHub CLI
and run the

gh repo fork [<repository>] [-- <gitflags>...] [flags]
```

command after getting it setup.

Body:
You can use GitHub CLI
and run the

gh repo fork [<repository>] [-- <gitflags>...] [flags]

command after getting it setup.


问:
Transforming Bitarray into to list of power of 2's
I am trying to conver Bitarray into an array of corresponding decimal values if the bit is 1.
The code I write is below but i don't want to use for loop. Is there a way around to avoid loop?</p>
```<code>int right = 15;
var b = new BitArray(new int[] { right });
var valueList = new List<int>();
for (int i = 0; i < rightList.Count; i++)
{
         if (b[i])
         {
             valueList.Add((int)Math.Pow(2, i));
          }
}
</code>```

答:
Try copying the bits into an integer array directly.

```<code>    static void Main(string[] args)
    {
        var ba = new BitArray(new int[] { 15 });
        var array = new int[ba.Length / (8*sizeof(int))];
        ba.CopyTo(array, 0);
        Console.WriteLine(array);
    }
</code>```

The resulting array contains the values you want.

You can create some extension methods to get the list of integers, or the list of bytes if you want.

```<code>    public static int[] GetIntegerValues(this BitArray bitArray)
    {
        var array = new int[bitArray.Length / (8 * sizeof(int))];
        bitArray.CopyTo(array, 0);
        return array;
    }
    public static byte[] GetByteValues(this BitArray bitArray)
    {
        var array = new byte[bitArray.Length / 8];
        bitArray.CopyTo(array, 0);
        return array;
    }
</code>```

with some sample usage

```<code>    static void Main(string[] args)
    {
        var bits = new BitArray(new int[] { 15, int.MinValue, int.MaxValue });

        var int_array = bits.GetIntegerValues();
        var byte_array = bits.GetByteValues();

        Console.WriteLine(int_array);
        // {15, -2147483648, 2147483647}
        Console.WriteLine(byte_array);
        // {15,0,0,0, 0,0,0,128, 255,255,255,127}
    }
</code>```

Body:
I am trying to conver Bitarray into an array of corresponding decimal values if the bit is 1.
The code I write is below but i don't want to use for loop. Is there a way around to avoid loop?

int right = 15;
var b = new BitArray(new int[] { right });
var valueList = new List<int>();
for (int i = 0; i < rightList.Count; i++)
{
         if (b[i])
         {
             valueList.Add((int)Math.Pow(2, i));
          }
}

Body:
Try copying the bits into an integer array directly.

    static void Main(string[] args)
    {
        var ba = new BitArray(new int[] { 15 });
        var array = new int[ba.Length / (8*sizeof(int))];
        ba.CopyTo(array, 0);
        Console.WriteLine(array);
    }

The resulting array contains the values you want.

You can create some extension methods to get the list of integers, or the list of bytes if you want.

    public static int[] GetIntegerValues(this BitArray bitArray)
    {
        var array = new int[bitArray.Length / (8 * sizeof(int))];
        bitArray.CopyTo(array, 0);
        return array;
    }
    public static byte[] GetByteValues(this BitArray bitArray)
    {
        var array = new byte[bitArray.Length / 8];
        bitArray.CopyTo(array, 0);
        return array;
    }

with some sample usage

    static void Main(string[] args)
    {
        var bits = new BitArray(new int[] { 15, int.MinValue, int.MaxValue });

        var int_array = bits.GetIntegerValues();
        var byte_array = bits.GetByteValues();

        Console.WriteLine(int_array);
        // {15, -2147483648, 2147483647}
        Console.WriteLine(byte_array);
        // {15,0,0,0, 0,0,0,128, 255,255,255,127}
    }


答:
Ironically, undefined can be redefined in JavaScript, not that anyone in their right mind would do that, for example:

```<code>undefined = "LOL!";
</code>```

at which point all future equality checks against undefined will yeild unexpected results!

As for the difference between == and === (the equality operators), == will attempt to coerce values from one type to another, in English that means that 0 == "0" will evaluate to true even though the types differ (Number vs String) - developers tend to avoid this type of loose equality as it can lead to difficult to debug errors in your code.

As a result it's safest to use:

```<code>"undefined" === typeof a
</code>```

When checking for undefinedness :)

Title: What is the best way to compare a value against 'undefined'?

Body:
Ironically, undefined can be redefined in JavaScript, not that anyone in their right mind would do that, for example:

undefined = "LOL!";

at which point all future equality checks against undefined will yeild unexpected results!

As for the difference between == and === (the equality operators), == will attempt to coerce values from one type to another, in English that means that 0 == "0" will evaluate to true even though the types differ (Number vs String) - developers tend to avoid this type of loose equality as it can lead to difficult to debug errors in your code.

As a result it's safest to use:

"undefined" === typeof a

When checking for undefinedness :)


问:
how to use async and await to connect to mongoDB database?
I am new to JavaScript and currently learning mongoDB with node.
The code Bellow is in callback functions but i want to connect to mongoDB database using async and await with try and catch .

```<code>const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost/selfdb");

mongoose.connection
  .once("open", () => {
    console.log("connection has been made!");
  })
  .on("error", (error) => {
    console.log("connection error:", error);
  });
</code>```

I tried doing this way:

```<code>const mongoose = require("mongoose");

async function main() {
  const uri = "mongodb://localhost/selfdb";

  const client = new mongoose(uri);

  try {
    await client.connect();
    console.log("connection has been made!");
  } catch (e) {
    client.error(e);
  } finally {
    await client.close();
  }
}

main().catch(console.error);
</code>```

but i got following error:

TypeError: mongoose is not a constructor

how could i do it the right way?
am i doing any silly mistake?

答:
I believe the better way to connect is like this

```<code>const mongoose = require('mongoose')

const connectDB = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGO_URI)
    console.log(`MongoDB Connected: ${conn.connection.host}`)
  }
  catch (error) {
    console.log(error)
    process.exit(1)
  }
}

module.exports = connectDB
</code>```

Mongo URI is in .env file, but you can replace it with your connection string (but more secure in  .env file)

Then in server.js or index.js (entry file)

```<code>const connectDB = require('path_to_file')

connectDB()
</code>```

Body:
I am new to JavaScript and currently learning mongoDB with node.
The code Bellow is in callback functions but i want to connect to mongoDB database using async and await with try and catch .

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost/selfdb");

mongoose.connection
  .once("open", () => {
    console.log("connection has been made!");
  })
  .on("error", (error) => {
    console.log("connection error:", error);
  });

I tried doing this way:

const mongoose = require("mongoose");

async function main() {
  const uri = "mongodb://localhost/selfdb";

  const client = new mongoose(uri);

  try {
    await client.connect();
    console.log("connection has been made!");
  } catch (e) {
    client.error(e);
  } finally {
    await client.close();
  }
}

main().catch(console.error);

but i got following error:

TypeError: mongoose is not a constructor

how could i do it the right way?
am i doing any silly mistake?

Body:
I believe the better way to connect is like this

const mongoose = require('mongoose')

const connectDB = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGO_URI)
    console.log(`MongoDB Connected: ${conn.connection.host}`)
  }
  catch (error) {
    console.log(error)
    process.exit(1)
  }
}

module.exports = connectDB

Mongo URI is in .env file, but you can replace it with your connection string (but more secure in  .env file)

Then in server.js or index.js (entry file)

const connectDB = require('path_to_file')

connectDB()


问:
How is a boolean a valid React.ReactNode value?
How is a boolean value (true or false) not an invalid value for a prop of type React.ReactNode, resulting in the following being a Typescript error?

```<code>interface IProps {
    node: React.ReactNode;
}

const foo: IProps = {
    node: false,
};
</code>```

答:
ReactNode represents all the possible values that can be put as a child of an element. Booleans are allowed because the following is a very common pattern for doing conditional rendering:

```<code>const condition: boolean = Math.random() > 0.5;

<div>
  {condition && (
    <p>You win!</p>
  )}
</div>
</code>```

If condition is false, then the div's children prop will be false, and so the type is set up to allow this.

If you only want to allow elements, consider using React.ReactElement instead:

```<code>interface IProps {
   node: React.ReactElement;
}

const foo: IProps = {
  node: <div /> // Good
}

const foo2: IProps = {
  node: null // Error. If you want to allow null, change to React.ReactElement | null
}

const foo3: IProps = {
  node: false // Error
}
</code>```

Body:
How is a boolean value (true or false) not an invalid value for a prop of type React.ReactNode, resulting in the following being a Typescript error?

interface IProps {
    node: React.ReactNode;
}

const foo: IProps = {
    node: false,
};

Body:
ReactNode represents all the possible values that can be put as a child of an element. Booleans are allowed because the following is a very common pattern for doing conditional rendering:

const condition: boolean = Math.random() > 0.5;

<div>
  {condition && (
    <p>You win!</p>
  )}
</div>

If condition is false, then the div's children prop will be false, and so the type is set up to allow this.

If you only want to allow elements, consider using React.ReactElement instead:

interface IProps {
   node: React.ReactElement;
}

const foo: IProps = {
  node: <div /> // Good
}

const foo2: IProps = {
  node: null // Error. If you want to allow null, change to React.ReactElement | null
}

const foo3: IProps = {
  node: false // Error
}


问:
Google Apps Script Save copy to read only
How do you save a copy of the current Sheets file to a read-only copy? We have scripts that set values that once confirmed save to a new Sheets file. This new file needs to be set as ReadOnly as a part of the script.</p>

答:
A Google Sheets file will always be editable by the file onwer

It will not accesiable by other users it all unless it is explicitly shared with them
-The sharing can take place either through the UI or by script

To do it by script, you can use the method Spreadsheet.addViewer() or File.addViewer()

If a user who has is already an editor needs to be "downgraded" to a viewer, you can do remove him from the editors with removeEditor() before adding him as a viewer

You can also remove all editors (apart from the spreadsheet owner), sample:

```<code>var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.getEditors().forEach(function(editor){
  ss.removeEditor(editor):
})
</code>```

Body:
A Google Sheets file will always be editable by the file onwer

It will not accesiable by other users it all unless it is explicitly shared with them
-The sharing can take place either through the UI or by script

To do it by script, you can use the method Spreadsheet.addViewer() or File.addViewer()

If a user who has is already an editor needs to be "downgraded" to a viewer, you can do remove him from the editors with removeEditor() before adding him as a viewer

You can also remove all editors (apart from the spreadsheet owner), sample:

var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.getEditors().forEach(function(editor){
  ss.removeEditor(editor):
})


问:
Can I use Jsch to fake ssh connection to the localhost?
I spent a lot of time developing an application that would use JSch and connect to a remote machine thru ssh to perform some command-line operations. However I learned that these operations can be performed at the localhost as well (my app is running on localhost). Now... I am too lazy to rewrite all the code and honestly I feel bad since I got really attached to JSch. Is there a way to trick JSch to connect to localhost instead or tell it in some way to just use localhost even though the code says otherwise? :)

P.S. in case it's not possible, how come the regular Proccess class doesnt support setOutputStream and setErrStream like JSch does, but only getInputStream and getErrorStream ??

答:
As long as your local machine has an SSH server running (and your application has the necessary login credentials), you can use JSch to connect to your local machine, too - simply indicate localhost (or 127.0.0.1) as the host name for the connection.

This will have some overhead, though, since you are encrypting and decrypting all the data, which is not really necessary to execute some command locally. (On the other hand, this would allow you to run the commands as another user, for which you otherwise would need something like sudo or su, or RunAs under Windows.)

JSch implements the setOutputStream and setErrStream on top of the corresponding get... methods - it uses something similar to a PipedInputStream internally and a separate thread which shovels the data between those streams.

As JSch is open source, you can simply look how this is done (in the Channel class, if I remember right), and copy the relevant methods to your class which does the same things for a Process.

Is there a way to tell JSch not to encrypt the data?

You can use the none cipher, e.g. no encryption. This is by default disabled in all general-purpose clients and servers (as it defeats half of the purpose of SSH), but with the right configuration you can enable it. In JSch you can use

```<code>session.setConfig("cipher.s2c", "none,...");  // server to client
session.setConfig("cipher.c2s", "none,...");  // client to server
</code>```

(This configuration option is the list of all options the client supports - see the documentation of setConfig for all supported values. The server will normally select the first one of this list that it also supports. To force no encryption (or canceling the connection), list only none.)

I don't know how to enable this in the SSH server - read your server's documentation. (And enable it only for localhost, if possible.)

The recommended way of using it is to switch to the none cipher only after authentication (so the authentication is still encrypted), but for localhost this might not be necessary. (You can use session.rekey() to switch the cipher (and key) after changing the configuration.)

Body:
As long as your local machine has an SSH server running (and your application has the necessary login credentials), you can use JSch to connect to your local machine, too - simply indicate localhost (or 127.0.0.1) as the host name for the connection.

This will have some overhead, though, since you are encrypting and decrypting all the data, which is not really necessary to execute some command locally. (On the other hand, this would allow you to run the commands as another user, for which you otherwise would need something like sudo or su, or RunAs under Windows.)

JSch implements the setOutputStream and setErrStream on top of the corresponding get... methods - it uses something similar to a PipedInputStream internally and a separate thread which shovels the data between those streams.

As JSch is open source, you can simply look how this is done (in the Channel class, if I remember right), and copy the relevant methods to your class which does the same things for a Process.

Is there a way to tell JSch not to encrypt the data?

You can use the none cipher, e.g. no encryption. This is by default disabled in all general-purpose clients and servers (as it defeats half of the purpose of SSH), but with the right configuration you can enable it. In JSch you can use

session.setConfig("cipher.s2c", "none,...");  // server to client
session.setConfig("cipher.c2s", "none,...");  // client to server

(This configuration option is the list of all options the client supports - see the documentation of setConfig for all supported values. The server will normally select the first one of this list that it also supports. To force no encryption (or canceling the connection), list only none.)

I don't know how to enable this in the SSH server - read your server's documentation. (And enable it only for localhost, if possible.)

The recommended way of using it is to switch to the none cipher only after authentication (so the authentication is still encrypted), but for localhost this might not be necessary. (You can use session.rekey() to switch the cipher (and key) after changing the configuration.)


问:
Path Provider Using and Asset Problems
I want to add an image that I added to my application from the phone's gallery to the list and call it with Image.asset as a String value.

I managed to get the image with ImagePicker. Unfortunately, there is no next. I don't know exactly how to do this.

In short: I will select an image from gallery with ImagePicker and replace it with "Image.file"
I will do it by converting it to String value with Image.asset.

答:
You have to use image.file or image.memory to load an image from ImagePicker.

image.asset is for images that already exist within your app.

Title: Path Provider Using and Asset Problems


问:
How does this splice code work in javascript?
I'm new to programming so sorry if this is a stupid question.

In the following code I know that "March" is at index 1. With spice we are saying start at index 1, remove 0 (none) and add Feb. When we add feb, does it push march across?

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
console.log(months);```

答:
The splice function deletes and/or inserts an element at a specific position. https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

I don't understand your question. March will remain in the array but will be pushed one index further