问:
Sorting columns having lists with reference to each other in pandas
Suppose my data frame is like:

```<code>   A             B           Date
[1,3,2]    ['a','b','c']     date1
</code>```

I want to sort both the columns but with reference to each other. Like the output should be:

```<code>   A             B           Date
[1,2,3]    ['a','c','b']     date1
</code>```

Now if these had been two lists only I would have sorted through zip method.

But as these are columns of data frame. I am not sure how to use apply method to sort these with reference to each other.

My dataframe as a whole is sorted on the basis of third column (date). Now for each such dates the other two columns have list, each having same number of values. I want to sort those lists on the basis of each other

答:
If all cells have the same number of values, try this flattening and groupby approach:

```<code>df
           A          B
0  [1, 3, 2]  [a, b, c]
1  [4, 6, 5]  [d, f, e]  # added an extra row for demonstration
</code>```

```<code>(df.apply(pd.Series.explode)
   .groupby(level=0)
   .apply(lambda x: x.sort_values('A'))
   .groupby(level=0)
   .agg(list))

           A          B
0  [1, 2, 3]  [a, c, b]
1  [4, 5, 6]  [d, e, f]
</code>```

Obligatory disclaimer: Please don't use pandas to store lists in columns.

Body:
Suppose my data frame is like:

   A             B           Date
[1,3,2]    ['a','b','c']     date1

I want to sort both the columns but with reference to each other. Like the output should be:

   A             B           Date
[1,2,3]    ['a','c','b']     date1

Now if these had been two lists only I would have sorted through zip method.

But as these are columns of data frame. I am not sure how to use apply method to sort these with reference to each other.

My dataframe as a whole is sorted on the basis of third column (date). Now for each such dates the other two columns have list, each having same number of values. I want to sort those lists on the basis of each other

Body:
If all cells have the same number of values, try this flattening and groupby approach:

df
           A          B
0  [1, 3, 2]  [a, b, c]
1  [4, 6, 5]  [d, f, e]  # added an extra row for demonstration

(df.apply(pd.Series.explode)
   .groupby(level=0)
   .apply(lambda x: x.sort_values('A'))
   .groupby(level=0)
   .agg(list))

           A          B
0  [1, 2, 3]  [a, c, b]
1  [4, 5, 6]  [d, e, f]

Obligatory disclaimer: Please don't use pandas to store lists in columns.


来源: stackexchange

问:
Set zero tax class to specific item count from defined product categories in Woocommerce
In WooCommerce, if the cart contains 6 or more items from 2 specific categories, then I would like to set a specific tax class (tax-zero) only to these items (not the entire cart, so not change it for the other products).

I use this piece of code which calculates the number of items in cart that are from the 2 categories, but I can't find how to complete it in order to set them with my "tax-zero" tax class.

add_action( 'woocommerce_before_calculate_totals', 'apply_conditionally_taxes', 20, 1 );
function apply_conditionally_taxes( $cart ){

    $item_count   = $cart->get_cart_contents_count();
    $kingcat_count = 0;

    foreach ( $cart->get_cart() as $cart_item ) {
        if ( has_term( 'patisseries', 'product_cat', $cart_item['product_id'] ) or has_term( 'viennoiseries-et-gaufres', 'product_cat', $cart_item['product_id'] ) ) {
            $kingcat_count += $cart_item['quantity'];
            //echo $kingcat_count;
        }

    }
}
```

答:
Code contains: (explanation added as a comment to the code)

Only count the items that belong to a certain category

Set a specific tax class to those items only

function action_woocommerce_before_calculate_totals( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;

    /* SETTINGS */

    // Set categories
    $categories = array ( 'patisseries', 'viennoiseries-et-gaufres' );

    // Contains 6 or more items
    $contains_min = 6;

    /* END SETTINGS */

    // Counter
    $counter = 0;

    // Loop trough
    foreach ( $cart->get_cart() as $cart_item ) {
        // Break loop
        if ( $counter >= $contains_min ) {
            break;
        }

        // Has term
        if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
            // Add to counter
            $counter += $cart_item['quantity'];
        }
    }

    // Check
    if ( $counter >= $contains_min ) {
        // Loop trough
        foreach( $cart->get_cart() as $cart_item ) {
            // Has term
            if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
                // We set "Zero rate" tax class
                $cart_item['data']->set_tax_class( 'Zero rate' );
            }
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );
```

ContentLicense: CC BY-SA 4.0


问:
JSONDecodeError: Expecting value: line 1 column 1 error in AWS Lambda
I am trying to write a aws lambda function which will push the SQS queue output in a s3 bucket.
But the lambda function is failing to push the message , the cloudwatch log is showing

```<code>JSONDecodeError: Expecting value: line 1 column 1
</code>```

i am posting the lambda function which i am using

```<code>import json
import boto3

def lambda_handler(event, context):
s3 = boto3.client("s3")
data = json.loads(event["Records"][0]["body"]) --getting error in this line
print(data)
s3.put_object(Bucket="sqsmybucket",key="data.json", Body=json.dumps(data))
#print(event)
return {
    'statusCode': 200,
    'body': json.dumps('Hello from Lambda!')
}
</code>```

The cloud watch log is showing

```<code>2020-05-30T23:51:45.276+05:30

[ERROR] JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 6, in lambda_handler
data = json.loads(event["Records"][0]["body"])
 File "/var/lang/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/var/lang/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/var/lang/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
</code>```

I have formatted the message and saved it to the cloud below is the link

```<code>[formatted JSON code][1]
</code>```

formatted JSON

Please help , thanks in advance

答:
Your event["Records"][0]["body"] is a plain string, not json:

```<code>"body": "A difficult message."
</code>```

Therefore, json.loads(event["Records"][0]["body"]) is equivalent to json.loads("A difficult message.") which obviously fails.

To get body's value you can do the following instead:

```<code>data = event["Records"][0]["body"]
</code>```

However, since later you have the following statment:

```<code>Body=json.dumps(data)
</code>```

The Body will be:

```<code>Body='"A difficult message."'
</code>```

which may or may not be what you desire.

Body:
I am trying to write a aws lambda function which will push the SQS queue output in a s3 bucket.
But the lambda function is failing to push the message , the cloudwatch log is showing

JSONDecodeError: Expecting value: line 1 column 1

i am posting the lambda function which i am using

import json
import boto3

def lambda_handler(event, context):
s3 = boto3.client("s3")
data = json.loads(event["Records"][0]["body"]) --getting error in this line
print(data)
s3.put_object(Bucket="sqsmybucket",key="data.json", Body=json.dumps(data))
#print(event)
return {
    'statusCode': 200,
    'body': json.dumps('Hello from Lambda!')
}

The cloud watch log is showing

2020-05-30T23:51:45.276+05:30

[ERROR] JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 6, in lambda_handler
data = json.loads(event["Records"][0]["body"])
 File "/var/lang/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/var/lang/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/var/lang/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None

I have formatted the message and saved it to the cloud below is the link

[formatted JSON code][1]

formatted JSON

Please help , thanks in advance

Body:
Your event["Records"][0]["body"] is a plain string, not json:

"body": "A difficult message."

Therefore, json.loads(event["Records"][0]["body"]) is equivalent to json.loads("A difficult message.") which obviously fails.

To get body's value you can do the following instead:

data = event["Records"][0]["body"]

However, since later you have the following statment:

Body=json.dumps(data)

The Body will be:

Body='"A difficult message."'

which may or may not be what you desire.


问:
why is my flutter app's user-info page loosing the data stored when i restart the app? (fyi the data is getting stored in Firebase but not in the app)
i'm Trying to create a user-info page using flutter and i manage to store the info in the Firebase-cloud server which is good,but it looses the information in my app screen once i restart the app or navigate to another page,how do i make the info survive a restart? and can i add and retrieve the data at the same time with Firestore.instance.collection('userinfo').

this is a screenshot of my app page

```<code>   class _UserInfoPageState extends State<UserInfoPage> {
  void _submitUserInfo(String userName, String address, String userPhone,
      String pincode, String state)

  {
    Firestore.instance.collection('userinfo').add({
      'username': userName,
      'Address': address,
      'user Phone no': userPhone,
      'pincode': pincode,
      'state': state,
    });
</code>```

答:
It's hard to tell with that huge block of code. But I couldn't find anywhere in your code where you fetch the information from Firebase.

Any data that isn't saved on the device gets cleared when you close the app. So you will have to pull the data from Firebase to populate it, or you store it on the device(look into SharedPreferences).

If I missed something important in your code I apologize.

Body:
i'm Trying to create a user-info page using flutter and i manage to store the info in the Firebase-cloud server which is good,but it looses the information in my app screen once i restart the app or navigate to another page,how do i make the info survive a restart? and can i add and retrieve the data at the same time with Firestore.instance.collection('userinfo').

this is a screenshot of my app page

   class _UserInfoPageState extends State<UserInfoPage> {
  void _submitUserInfo(String userName, String address, String userPhone,
      String pincode, String state)

  {
    Firestore.instance.collection('userinfo').add({
      'username': userName,
      'Address': address,
      'user Phone no': userPhone,
      'pincode': pincode,
      'state': state,
    });


问:
PHP export excel unicode ( russian chars ) problem
I have used below code to export excel file using php. For english text, I didn't find any issues. But Russian characters I find some issues. I have attached my code.</p>

```<code>mysql_connect("localhost","USERNAME","PASSWORD");
mysql_select_db("DATABASE");
mysql_query("SET NAMES 'UTF8'");
// Get data records from table.
$result=mysql_query("select * from usertbl order by user_id asc");

// Functions for export to excel.
function xlsBOF() {
   echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
   return;
 }
function xlsEOF() {
     echo pack("ss", 0x0A, 0x00);
     return;
 }
function xlsWriteNumber($Row, $Col, $Value) {
    echo pack("sssss", 0x203, 14, $Row, $Col, 0x0);
    echo pack("d", $Value);
    return;
 }
 function xlsWriteLabel($Row, $Col, $Value ) {
   $L = strlen($Value);
   echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
   echo $Value;
   return;
  }
  header("Pragma: public");
  header("Expires: 0");
  header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  header("Content-type: application/vnd.ms-excel;charset:UTF-8");
  header("Content-Type: application/force-download");
  header("Content-Type: application/octet-stream");
  header("Content-Type: application/download");
  header("Content-Disposition: attachment;filename=orderlist.xls ");
  header("Content-Transfer-Encoding: binary ");

  xlsBOF();

 /*
 Make a top line on your excel sheet at line 1 (starting at 0).
 The first number is the row number and the second number is the column, both are
 start  at '0'*/

 xlsWriteLabel(0,0,"List of car company.");

 // Make column labels. (at line 3)
 xlsWriteLabel(2,0,"No.");
 xlsWriteLabel(2,1,"Nickname");

 $xlsRow = 3;

 // Put data records from mysql by while loop.
 while($row=mysql_fetch_array($result)){

   xlsWriteNumber($xlsRow,0,$row['user_id']);
   //$row['nickname']= iconv('UTF-8', 'SJIS', $row['NAME']);
   //$row['nickname'] = mb_convert_encoding($row['NAME'], 'UTF-16LE', 'UTF-8');
     xlsWriteLabel($xlsRow,1,$row['NAME']);

    $xlsRow++;
  }
 xlsEOF();
 exit();
</code>```

答:
XLS file format is a really complex one and I would strongly advise against writing your own writer implementation.

Instead use one of the existing implementations, like phpexcel or even choose to write to CSV or XLSX formats.

ContentLicense: CC BY-SA 3.0

Body:
I have used below code to export excel file using php. For english text, I didn't find any issues. But Russian characters I find some issues. I have attached my code.

mysql_connect("localhost","USERNAME","PASSWORD");
mysql_select_db("DATABASE");
mysql_query("SET NAMES 'UTF8'");
// Get data records from table.
$result=mysql_query("select * from usertbl order by user_id asc");

// Functions for export to excel.
function xlsBOF() {
   echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
   return;
 }
function xlsEOF() {
     echo pack("ss", 0x0A, 0x00);
     return;
 }
function xlsWriteNumber($Row, $Col, $Value) {
    echo pack("sssss", 0x203, 14, $Row, $Col, 0x0);
    echo pack("d", $Value);
    return;
 }
 function xlsWriteLabel($Row, $Col, $Value ) {
   $L = strlen($Value);
   echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
   echo $Value;
   return;
  }
  header("Pragma: public");
  header("Expires: 0");
  header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  header("Content-type: application/vnd.ms-excel;charset:UTF-8");
  header("Content-Type: application/force-download");
  header("Content-Type: application/octet-stream");
  header("Content-Type: application/download");
  header("Content-Disposition: attachment;filename=orderlist.xls ");
  header("Content-Transfer-Encoding: binary ");

  xlsBOF();

 /*
 Make a top line on your excel sheet at line 1 (starting at 0).
 The first number is the row number and the second number is the column, both are
 start  at '0'*/

 xlsWriteLabel(0,0,"List of car company.");

 // Make column labels. (at line 3)
 xlsWriteLabel(2,0,"No.");
 xlsWriteLabel(2,1,"Nickname");

 $xlsRow = 3;

 // Put data records from mysql by while loop.
 while($row=mysql_fetch_array($result)){

   xlsWriteNumber($xlsRow,0,$row['user_id']);
   //$row['nickname']= iconv('UTF-8', 'SJIS', $row['NAME']);
   //$row['nickname'] = mb_convert_encoding($row['NAME'], 'UTF-16LE', 'UTF-8');
     xlsWriteLabel($xlsRow,1,$row['NAME']);

    $xlsRow++;
  }
 xlsEOF();
 exit();


问:
Catching DoesNotExist exception in a custom manager in Django
I have a custom manager for a Django model. I don't seem to be able to catch DoesNotExist exception here. I know how to do it inside the model but it didn't work here:

```<code>class TaskManager(models.Manager):
    def task_depend_tree(self, *args, **kwargs):
        if "id" in kwargs:
            try:
                task = self.get(id=kwargs["id"])
            except DoesNotExist:
                raise Http404
</code>```

Get_object_or_404 doesn't work either.
What is wrong here?

答:
I handle the exception this way and it worked.</p>

```<code>from django.core.exceptions import ObjectDoesNotExist

try:
    task = self.get(id=kwargs["id"])
except ObjectDoesNotExist as DoesNotExist:
    raise Http404

</code>```

Body:
I have a custom manager for a Django model. I don't seem to be able to catch DoesNotExist exception here. I know how to do it inside the model but it didn't work here:

class TaskManager(models.Manager):
    def task_depend_tree(self, *args, **kwargs):
        if "id" in kwargs:
            try:
                task = self.get(id=kwargs["id"])
            except DoesNotExist:
                raise Http404

Get_object_or_404 doesn't work either.
What is wrong here?

Body:
I handle the exception this way and it worked.

from django.core.exceptions import ObjectDoesNotExist

try:
    task = self.get(id=kwargs["id"])
except ObjectDoesNotExist as DoesNotExist:
    raise Http404


问:
Entity Framework Code first making a column non-nullable
I am using EF code first for my project. I have following code in my DataModel

```<code>[HiddenInput(DisplayValue = false)]
public DateTime? PasswordDate { get; set; }
</code>```

To make this non-nullable I removed '?' and ran Add-Migration command from Package manager console. following migration file was generated.

```<code>  public partial class PasswordDate : DbMigration
{
    public override void Up()
    {
        AlterColumn("dbo.CertificateInfoes", "PasswordDate", c => c.DateTime(nullable: false));
    }

    public override void Down()
    {
        AlterColumn("dbo.CertificateInfoes", "PasswordDate", c => c.DateTime());
    }
}
</code>```

But when I run Update-Database command:

```<code>Update-Database -SourceMigration 201309020721215_PasswordDate
</code>```

I get following error: Cannot insert the value NULL into column 'PasswordDate', table ''; column does not allow nulls. UPDATE fails.
The statement has been terminated.

Kindly suggest the solutions.

答:
It's not possible to directly add a non-nullable column to a table that has historical data in the table if no default value is provided for that column.

What I do is

add the column as nullable.

provide an sql script to populate this newly added column.

alter the column to make is as non-nullable.

Code example(with postgres database):

```<code> public override void Up()
    {
        AddColumn("public.YourTableName", "YourColumnName", c => c.Int(nullable: true));
        Sql(@"UPDATE ""public"".""YourTableName""
              SET ""YourColumnName"" = Value you want to set
            ");

        AlterColumn("public.YourTableName", "YourColumnName", c => c.Int(nullable: false));
    }
</code>```

Body:
I am using EF code first for my project. I have following code in my DataModel

[HiddenInput(DisplayValue = false)]
public DateTime? PasswordDate { get; set; }

To make this non-nullable I removed '?' and ran Add-Migration command from Package manager console. following migration file was generated.

  public partial class PasswordDate : DbMigration
{
    public override void Up()
    {
        AlterColumn("dbo.CertificateInfoes", "PasswordDate", c => c.DateTime(nullable: false));
    }

    public override void Down()
    {
        AlterColumn("dbo.CertificateInfoes", "PasswordDate", c => c.DateTime());
    }
}

But when I run Update-Database command:

Update-Database -SourceMigration 201309020721215_PasswordDate

I get following error: Cannot insert the value NULL into column 'PasswordDate', table ''; column does not allow nulls. UPDATE fails.
The statement has been terminated.

Kindly suggest the solutions.

Body:
It's not possible to directly add a non-nullable column to a table that has historical data in the table if no default value is provided for that column.

What I do is

add the column as nullable.

provide an sql script to populate this newly added column.

alter the column to make is as non-nullable.

Code example(with postgres database):

 public override void Up()
    {
        AddColumn("public.YourTableName", "YourColumnName", c => c.Int(nullable: true));
        Sql(@"UPDATE ""public"".""YourTableName""
              SET ""YourColumnName"" = Value you want to set
            ");

        AlterColumn("public.YourTableName", "YourColumnName", c => c.Int(nullable: false));
    }


问:
Azure Data Factory V2 Dynamic Content
Long story short, I have a data dump that is too large for an azure function. So we are using Data Factory.
I have tasked another function to generate an access token for an API and output it as part of a json. I would like to set that token to a variable within the pipeline. So far I have this:

I'm attempting to use the Dynamic Content "language" to set the variable:

```<code>@activity('Get_Token').output
</code>```

I'd like something like pythons:

```<code>token = data.get('data', {}).get('access_token', '')
</code>```

As a secondary question, my next step is to use this token to call an API while iterating over another output, so perhaps this exact step can be added into the ForEach?

答:
Looks like the variable should be @activity('Get token').output.data.access_token as others have indicated but, as you've guessed, there's no need to assign a variable if you only need it within the foreach.  You can access any predecessor output from that successor activity.  Here's how to use the token while iterating over another output:

Let's say your function also outputs listOfThings as an array
within the data key. Then you can set the foreach activity to
iterate over @activity('Get token').output.data.listOfThings.

Inside the foreach you will have (let's say) a Copy activity with a
REST dataset as the source.  Configure the REST linked service
with anonymous auth ...

... then you'll find a field called Additional
Headers in the REST dataset where you can create a key Authorization
with value as above, Basic @activity('Get token').output.data.access_token

The thing that you said you want to iterate over (in the listOfThings JSON array) can be referenced inside the foreach activity with
@item() (or, if it's a member of an item in the listOfThings
iterable then it would be @item().myMember)

To make #4 explicit for anyone else arriving here:

If listOfThings looks like this, listOfThings: [ "thing1", "thing2", ...]

for example, filenames: ["file1.txt", "file2.txt", ...]

then @item() becomes file1.txt etc.

whereas

If listOfThings looks like this, listOfThings: [ {"key1":"value1", "key2":"value2" ... }, {"key1":"value1", "key2":"value2" ... }, ...]

for example. filenames: [ {"folder":"folder1", "filename":"file1.txt"}, {"folder":"folder2", "filename":"file2.txt"}, ... ]

then @item().filename becomes file1.txt etc.

Title: Azure Data Factory V2 Dynamic Content

Body:
Long story short, I have a data dump that is too large for an azure function. So we are using Data Factory.
I have tasked another function to generate an access token for an API and output it as part of a json. I would like to set that token to a variable within the pipeline. So far I have this:

I'm attempting to use the Dynamic Content "language" to set the variable:

@activity('Get_Token').output

I'd like something like pythons:

token = data.get('data', {}).get('access_token', '')

As a secondary question, my next step is to use this token to call an API while iterating over another output, so perhaps this exact step can be added into the ForEach?


问:
Can't find the stream provider when using named route navigation
I have a Stream Provider (connected to firebase) that is not working. I am guessing that the problem lies in the fact that I am using a named navigator [Navigator.pushNamed(context, '/route',)]. I guess this makes the 'route' widget to not be the son of the widget that calls it. Let me show it better below.

My app structure is as follows:
My main widget which handles routing and receives the Stream with user authentication (there is no problem here):

```<code>void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return StreamProvider<User>.value(
      value: AuthService().user,
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Wrapper(),
        routes: {
          '/home': (context) => Wrapper(),
          '/edit_profile': (context) => UserProfile() //This is where I am having trouble.
        }
      ),
    );
  }
}
</code>```

The Wrapper that validates if the user is authenticated and acts accordingly:

```<code>class Wrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    final user = Provider.of<User>(context);

    // return either the Home or Authenticate widget
    if (user == null){
      return Authenticate();
    } else {
      return HomeWrapper();
    }

  }
}
</code>```

The HomeWrapper which receives the second stream and redirects to the widget I am having trouble with:

```<code>class HomeWrapper extends StatefulWidget {
  @override
  _HomeWrapperState createState() => _HomeWrapperState();
}

class _HomeWrapperState extends State<HomeWrapper> {

  String currentBodyName = 'home';
  Widget currentBodyWidget = Home();

  @override
  Widget build(BuildContext context) {

    Widget _drawerOptions = Row(
      children: [
        FlatButton(child: someChild, onPressed: () {Navigator.pushNamed(context, '/edit_profile',);},), //This is the actual call to the navigator.
      ],
    );

    return StreamProvider<Map>.value( //This is the problematic Stream!
        value: DatabaseService().userDetail,
        child: Scaffold(
        //Body
        body: currentBodyWidget,

        //I am simplifying this to show the most important parts
        bottomNavigationBar: myBottomNavigationBar(
          buttons: <Widget>[
            FlatButton(
              icon: someIcon,
              onPressed: () =>  _onItemTapped('home'),
            ),
            FlatButton(
              icon: otherIcon,
              onPressed: () => _onItemTapped('second_screen'),
            ),
          ],)

          //Drawer
          drawer: Drawer(child: _drawerOptions,), //This one has the call to the problematic edit_profile route.
    );
  }

  void _onItemTapped(String newBodyName) {
    if (newBodyName != currentBodyName){
      setState(() {
        currentBodyName = newBodyName;
        switch(newBodyName) {
          case 'home': {
            currentBodyWidget = Home();
          }
          break;

          case 'second_screen': {
            currentBodyWidget = SecondScreen();
          }
          break;

          default: {
            currentBodyWidget = Home();
          }
          break;
        }
      });
    }
  }

}
</code>```

Finally the edit_profile route calls the UserProfile Widget which looks like this:

```<code>class UserProfile extends StatefulWidget {
  @override
  _UserProfileState createState() => _UserProfileState();
}

class _UserProfileState extends State<UserProfile> {

  @override
  Widget build(BuildContext context) {

    //This is where the error occurs!!
    final userDocument = Provider.of<Map>(context) ?? [];
    print(userDocument);

    return Scaffold(body: Container());
  }
}

</code>```

This is the error that it throws:

```<code>The following ProviderNotFoundError was thrown building UserProfile(dirty, state: _UserProfileState#09125):
Error: Could not find the correct Provider<Map<dynamic, dynamic>> above this UserProfile Widget
</code>```

Thank you very much!!

答:
Turns out my approach was wrong.

Instead of wrapping the HomeWrapper with the StreamProvider, hoping that it would pass the data to the next route (UserProfile ), what I did was to wrap the UserProfile widget with a StreamProvider, as follows:

(Note: I changed the Map StreamProvider for a UserData StreamProvider.)

```<code>class UserProfile extends StatefulWidget {
  @override
  _UserProfileState createState() => _UserProfileState();
}

class _UserProfileState extends State<UserProfile> {

  @override
  Widget build(BuildContext context) {
    final user = Provider.of<User>(context);

    return StreamBuilder<UserData>(
        stream: DatabaseService(uid: user.uid).userData,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            UserData userData = snapshot.data;

            return Scaffold(
              body: Container(
                   //My Widget here
            );
          } else
            return Loading();
        });
  }
}
</code>```

This series was very helpful: https://www.youtube.com/playlist?list=PL4cUxeGkcC9j--TKIdkb3ISfRbJeJYQwC

Body:
I have a Stream Provider (connected to firebase) that is not working. I am guessing that the problem lies in the fact that I am using a named navigator [Navigator.pushNamed(context, '/route',)]. I guess this makes the 'route' widget to not be the son of the widget that calls it. Let me show it better below.

My app structure is as follows:
My main widget which handles routing and receives the Stream with user authentication (there is no problem here):

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return StreamProvider<User>.value(
      value: AuthService().user,
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Wrapper(),
        routes: {
          '/home': (context) => Wrapper(),
          '/edit_profile': (context) => UserProfile() //This is where I am having trouble.
        }
      ),
    );
  }
}

The Wrapper that validates if the user is authenticated and acts accordingly:

class Wrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    final user = Provider.of<User>(context);

    // return either the Home or Authenticate widget
    if (user == null){
      return Authenticate();
    } else {
      return HomeWrapper();
    }

  }
}

The HomeWrapper which receives the second stream and redirects to the widget I am having trouble with:

class HomeWrapper extends StatefulWidget {
  @override
  _HomeWrapperState createState() => _HomeWrapperState();
}

class _HomeWrapperState extends State<HomeWrapper> {

  String currentBodyName = 'home';
  Widget currentBodyWidget = Home();

  @override
  Widget build(BuildContext context) {

    Widget _drawerOptions = Row(
      children: [
        FlatButton(child: someChild, onPressed: () {Navigator.pushNamed(context, '/edit_profile',);},), //This is the actual call to the navigator.
      ],
    );

    return StreamProvider<Map>.value( //This is the problematic Stream!
        value: DatabaseService().userDetail,
        child: Scaffold(
        //Body
        body: currentBodyWidget,

        //I am simplifying this to show the most important parts
        bottomNavigationBar: myBottomNavigationBar(
          buttons: <Widget>[
            FlatButton(
              icon: someIcon,
              onPressed: () =>  _onItemTapped('home'),
            ),
            FlatButton(
              icon: otherIcon,
              onPressed: () => _onItemTapped('second_screen'),
            ),
          ],)

          //Drawer
          drawer: Drawer(child: _drawerOptions,), //This one has the call to the problematic edit_profile route.
    );
  }

  void _onItemTapped(String newBodyName) {
    if (newBodyName != currentBodyName){
      setState(() {
        currentBodyName = newBodyName;
        switch(newBodyName) {
          case 'home': {
            currentBodyWidget = Home();
          }
          break;

          case 'second_screen': {
            currentBodyWidget = SecondScreen();
          }
          break;

          default: {
            currentBodyWidget = Home();
          }
          break;
        }
      });
    }
  }

}

Finally the edit_profile route calls the UserProfile Widget which looks like this:

class UserProfile extends StatefulWidget {
  @override
  _UserProfileState createState() => _UserProfileState();
}

class _UserProfileState extends State<UserProfile> {

  @override
  Widget build(BuildContext context) {

    //This is where the error occurs!!
    final userDocument = Provider.of<Map>(context) ?? [];
    print(userDocument);

    return Scaffold(body: Container());
  }
}

This is the error that it throws:

The following ProviderNotFoundError was thrown building UserProfile(dirty, state: _UserProfileState#09125):
Error: Could not find the correct Provider<Map<dynamic, dynamic>> above this UserProfile Widget

Thank you very much!!

Body:
Turns out my approach was wrong.

Instead of wrapping the HomeWrapper with the StreamProvider, hoping that it would pass the data to the next route (UserProfile ), what I did was to wrap the UserProfile widget with a StreamProvider, as follows:

(Note: I changed the Map StreamProvider for a UserData StreamProvider.)

class UserProfile extends StatefulWidget {
  @override
  _UserProfileState createState() => _UserProfileState();
}

class _UserProfileState extends State<UserProfile> {

  @override
  Widget build(BuildContext context) {
    final user = Provider.of<User>(context);

    return StreamBuilder<UserData>(
        stream: DatabaseService(uid: user.uid).userData,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            UserData userData = snapshot.data;

            return Scaffold(
              body: Container(
                   //My Widget here
            );
          } else
            return Loading();
        });
  }
}

This series was very helpful: https://www.youtube.com/playlist?list=PL4cUxeGkcC9j--TKIdkb3ISfRbJeJYQwC


问:
Filter Pyspark dataframe column with None value
I'm trying to filter a PySpark dataframe that has None as a row value:

```<code>df.select('dt_mvmt').distinct().collect()

[Row(dt_mvmt=u'2016-03-27'),
 Row(dt_mvmt=u'2016-03-28'),
 Row(dt_mvmt=u'2016-03-29'),
 Row(dt_mvmt=None),
 Row(dt_mvmt=u'2016-03-30'),
 Row(dt_mvmt=u'2016-03-31')]
</code>```

and I can filter correctly with an string value:

```<code>df[df.dt_mvmt == '2016-03-31']
# some results here
</code>```

but this fails:

```<code>df[df.dt_mvmt == None].count()
0
df[df.dt_mvmt != None].count()
0
</code>```

But there are definitely values on each category. What's going on?

答:
There are multiple ways you can remove/filter the null values from a column in DataFrame.

Lets create a simple DataFrame with below code:

```<code>date = ['2016-03-27','2016-03-28','2016-03-29', None, '2016-03-30','2016-03-31']
df = spark.createDataFrame(date, StringType())
</code>```

Now you can try one of the below approach to filter out the null values.

```<code># Approach - 1
df.filter("value is not null").show()

# Approach - 2
df.filter(col("value").isNotNull()).show()

# Approach - 3
df.filter(df["value"].isNotNull()).show()

# Approach - 4
df.filter(df.value.isNotNull()).show()

# Approach - 5
df.na.drop(subset=["value"]).show()

# Approach - 6
df.dropna(subset=["value"]).show()

# Note: You can also use where function instead of a filter.
</code>```

You can also check the section "Working with NULL Values" on my blog for more information.

I hope it helps.

Body:
I'm trying to filter a PySpark dataframe that has None as a row value:

df.select('dt_mvmt').distinct().collect()

[Row(dt_mvmt=u'2016-03-27'),
 Row(dt_mvmt=u'2016-03-28'),
 Row(dt_mvmt=u'2016-03-29'),
 Row(dt_mvmt=None),
 Row(dt_mvmt=u'2016-03-30'),
 Row(dt_mvmt=u'2016-03-31')]

and I can filter correctly with an string value:

df[df.dt_mvmt == '2016-03-31']
# some results here

but this fails:

df[df.dt_mvmt == None].count()
0
df[df.dt_mvmt != None].count()
0

But there are definitely values on each category. What's going on?

Body:
There are multiple ways you can remove/filter the null values from a column in DataFrame.

Lets create a simple DataFrame with below code:

date = ['2016-03-27','2016-03-28','2016-03-29', None, '2016-03-30','2016-03-31']
df = spark.createDataFrame(date, StringType())

Now you can try one of the below approach to filter out the null values.

# Approach - 1
df.filter("value is not null").show()

# Approach - 2
df.filter(col("value").isNotNull()).show()

# Approach - 3
df.filter(df["value"].isNotNull()).show()

# Approach - 4
df.filter(df.value.isNotNull()).show()

# Approach - 5
df.na.drop(subset=["value"]).show()

# Approach - 6
df.dropna(subset=["value"]).show()

# Note: You can also use where function instead of a filter.

You can also check the section "Working with NULL Values" on my blog for more information.

I hope it helps.


问:
search in datagridview C# winfom
I want to put a search option in DataGridView, i.e., User types the string or int in TextBox and similar records the DataGridView should be highlighted. I tried it using KeyPress event but didn't work.

```<code>  if (Char.IsLetter(e.KeyChar))
  {
     for (int i = 0; i < (dgemployee.Rows.Count); i++)
     {
         if (dgemployee.Rows[i].Cells["Employee"].Value.ToString().
                    StartsWith(e.KeyChar.ToString(), true,
                    CultureInfo.InvariantCulture))
         {
             dgemployee.Rows[i].Cells[0].Selected = true;
             return;
         }
      }
</code>```

Actually, I need to search the whole DataGridView, not only one column and row. So any best solution?

答:
If your DataGridView is bound to a DataTable or a DataView, you can do this:

Create a BindingSource and make BindingSource.DataSource the Datatable or DataView that your DGV is currently using.  Then set your DataGridView.DataSource to the BindingSource.  Then you can use the BindingSource.Filter property to query your datasource by setting the BindingSource.Filterto your query string which will automatically filter the DGV.  You can find the syntax here - it is very similar to basic SQL queries, except you can only use wild cards on the beginning and end of the string.

Title: search in datagridview C# winfom

Body:
I want to put a search option in DataGridView, i.e., User types the string or int in TextBox and similar records the DataGridView should be highlighted. I tried it using KeyPress event but didn't work.

  if (Char.IsLetter(e.KeyChar))
  {
     for (int i = 0; i < (dgemployee.Rows.Count); i++)
     {
         if (dgemployee.Rows[i].Cells["Employee"].Value.ToString().
                    StartsWith(e.KeyChar.ToString(), true,
                    CultureInfo.InvariantCulture))
         {
             dgemployee.Rows[i].Cells[0].Selected = true;
             return;
         }
      }

Actually, I need to search the whole DataGridView, not only one column and row. So any best solution?


问:
How to pull response from a URL and than put said response into a JSON
I need to send a request to https://authserver.mojang.com/authenticate

and get the response

```<code>{
    "accessToken": "valid accessToken",
    "clientToken": "client identifier",

    "selectedProfile": {
        "id": "profile identifier",
        "name": "player name"
    },
    "requestUser": true
}
</code>```

But I dont know how to ask the server for the out put.

What I need to input is

```<code>{
  "agent": { "name": "Minecraft", "version": 1 },
  "username": "-email here-",
  "password": "-pass here-"
}
</code>```

That is the data needed to get the token but I can't seem to get the code to ask the server for the token data and than receive it and put it into a JSON.

答:
```<code>const postData = async _ => {
  const response = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      "agent": { "name": "Minecraft", "version": 1 },
      "username": "-email here-",
      "password": "-pass here-"
    })
  })

  console.log(response)
}
</code>```

This should get the response you need judging by https://wiki.vg/Authentication#Payload this link.

Body:
I need to send a request to https://authserver.mojang.com/authenticate

and get the response

{
    "accessToken": "valid accessToken",
    "clientToken": "client identifier",

    "selectedProfile": {
        "id": "profile identifier",
        "name": "player name"
    },
    "requestUser": true
}

But I dont know how to ask the server for the out put.

What I need to input is

{
  "agent": { "name": "Minecraft", "version": 1 },
  "username": "-email here-",
  "password": "-pass here-"
}

That is the data needed to get the token but I can't seem to get the code to ask the server for the token data and than receive it and put it into a JSON.

Body:
const postData = async _ => {
  const response = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      "agent": { "name": "Minecraft", "version": 1 },
      "username": "-email here-",
      "password": "-pass here-"
    })
  })

  console.log(response)
}

This should get the response you need judging by https://wiki.vg/Authentication#Payload this link.


问:
Reading file in the same folder - Improvement?
i am writing an python script.  I was having some problems to open the file.   The error was always that system just can not find the file.

Because of that i tried get the active path... Replace backslash ... and so on....

Is there any improvements to work with the file in the same folder?

The Code

```<code>import os

# The name of the txt file that is in the same folder.
myFile = 'noticia.txt'

# Getting the active script
diretorio = os.path.dirname(os.path.abspath(__file__))

# Replace BackSlash and concatenate myFile
correctPath = diretorio.replace("\\", "/") + "/" + myFile

# Open file
fileToRead = open(correctPath, "r")

# Store text in a variable
myText = fileToRead.read()

# Print
print(myText)

</code>```

Note:

The script is in the same folder of the txt file.

答:
Is there any improvements to work with the file in the same folder?

First off, please see PEP 8 for standard conventions on variable names.

```<code>correctPath = diretorio.replace("\\", "/") + "/" + myFile
</code>```

While forward slashes are preferred when you specify a new path in your code, there is no need to replace the backslashes in a path that Windows gives you. Python and/or Windows will translate behind the scenes as necessary.

However, it would be better to use os.path.join to combine the path components (something like correct_path = os.path.join(diretorio, my_file)).

```<code>fileToRead = open(correctPath, "r")

# Store text in a variable
myText = fileToRead.read()
</code>```

It is better to use a with block to manage the file, which ensures that it is closed properly, like so:

```<code>with open(correct_path, 'r') as my_file:
    my_text = my_file.read()
</code>```

Body:
i am writing an python script.  I was having some problems to open the file.   The error was always that system just can not find the file.

Because of that i tried get the active path... Replace backslash ... and so on....

Is there any improvements to work with the file in the same folder?

The Code

import os

# The name of the txt file that is in the same folder.
myFile = 'noticia.txt'

# Getting the active script
diretorio = os.path.dirname(os.path.abspath(__file__))

# Replace BackSlash and concatenate myFile
correctPath = diretorio.replace("\\", "/") + "/" + myFile

# Open file
fileToRead = open(correctPath, "r")

# Store text in a variable
myText = fileToRead.read()

# Print
print(myText)

Note:

The script is in the same folder of the txt file.

Body:
Is there any improvements to work with the file in the same folder?

First off, please see PEP 8 for standard conventions on variable names.

correctPath = diretorio.replace("\\", "/") + "/" + myFile

While forward slashes are preferred when you specify a new path in your code, there is no need to replace the backslashes in a path that Windows gives you. Python and/or Windows will translate behind the scenes as necessary.

However, it would be better to use os.path.join to combine the path components (something like correct_path = os.path.join(diretorio, my_file)).

fileToRead = open(correctPath, "r")

# Store text in a variable
myText = fileToRead.read()

It is better to use a with block to manage the file, which ensures that it is closed properly, like so:

with open(correct_path, 'r') as my_file:
    my_text = my_file.read()


问:
Enabling SSL with XAMPP
I've been following this guide as much as I could
http://robsnotebook.com/xampp-ssl-encrypt-passwords .

However whenever I browse to a page starting with https the apache server replies 404 Object Not Found.

What setting I am missing? Thanks for any help.

答:
In case you are on Mac OS (catalina or mojave) and wants to enable HTTPS/SSL on XAMPP for Mac, you need to enable the virtual host and use the default certificates included in XAMPP.
On your httpd-vhosts.conf file add a new vhost:

```<code><VirtualHost *:443>
    ServerAdmin webmaster@localhost.com
    DocumentRoot "/Users/your-user/your-site"
    ServerName your-site.local
    SSLEngine on
    SSLCertificateFile "etc/ssl.crt/server.crt"
    SSLCertificateKeyFile "etc/ssl.key/server.key"
    <Directory "/Users/your-user/your-site">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Require all granted
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>
</code>```

Title: Enabling SSL with XAMPP

Body:
In case you are on Mac OS (catalina or mojave) and wants to enable HTTPS/SSL on XAMPP for Mac, you need to enable the virtual host and use the default certificates included in XAMPP.
On your httpd-vhosts.conf file add a new vhost:

<VirtualHost *:443>
    ServerAdmin webmaster@localhost.com
    DocumentRoot "/Users/your-user/your-site"
    ServerName your-site.local
    SSLEngine on
    SSLCertificateFile "etc/ssl.crt/server.crt"
    SSLCertificateKeyFile "etc/ssl.key/server.key"
    <Directory "/Users/your-user/your-site">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Require all granted
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>


问:
Retrieving user data from mongoDB
I'm building an app where a user logs in and can create a grocery list on their account (there are more things they can do like create recipes, but this is the example I want to use). Right now I have it so everybody who logs in sees the same list. But I want each user to be able to log in and view their own grocery list that they made. I'm assuming the logic is literally like logging into a social media site and viewing YOUR profile, not somebody else's.

I'm using mongoDB/mongoose and I just read about the populate method as well as referencing other schemas in your current schema. Here is my schema for the list:

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create item schema
const GroceryListItemSchema = new Schema({
  item: {
    type: String,
    required: [true, 'Item field is required']
  },
  userId: {
    type: mongoose.Schema.Types.ObjectId, ref: "user",
  }
});

// Create an Item model
const GroceryListItem = mongoose.model('groceryListItem', GroceryListItemSchema);
module.exports = GroceryListItem;
</code>```

And here is the post request to add a list item:

```<code>//POST request for shopping list
router.post("/list", checkToken, (req, res, next) => {
  // Add an item to the database
  const groceryListItem = new GroceryListItem({
    item: req.body.item,
    userId: ???
  })

  groceryListItem.save()
    .then((groceryListItem) => {
      res.send(groceryListItem);
    })
    .catch(next);
});
</code>```

Here is my userModel - not sure if this is necessary to show:

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

const UserSchema = new Schema({
  username: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  password2: {
    type: String,
    required: true,
  },

});

const User = mongoose.model("users", UserSchema);
module.exports = User;
</code>```

(in case anyone is wondering why the model is called "users"-- that's what I initially called it on accident and when I changed the name to "user" it errored out...so I changed it back.)

I am not sure how to add the userId when making an instance of the groceryListItem. In the mongoose docs (https://mongoosejs.com/docs/populate.html#saving-refs), they use the example of a Story and Person Schema. They reference each other, and then they create an instance of Person, calling it author. Then they grab the _id from author and reference it in their instance of Story, called story1. So that makes sense to me. But the only way they can do that is because author and story1 are located in the same file.

So it seems like what I should do is grab the user _id by saying userId: users._id. But my new User instance is in my user routes. And I'd rather not combine the two. Because then I'd have another list to combine as well so that would be my user routes, recipe routes, and shopping list routes all in one file and that would be extremely messy.

Anyone have any idea how I can make this work? It seems so simple but for some reason I cannot figure this out.

Thank you!!

EDIT - frontend API call:

```<code>handleSubmitItem = (e) => {
    e.preventDefault();
    const newItem = {
      item: this.state.userInput,
    };

    authAxios
      .post(`http://localhost:4000/list/${userId}`, newItem)
      .then((res) => {
        this.setState({ items: [...this.state.items, newItem] });
        newItem._id = res.data._id;
      })
      .catch((err) => console.log(err));

    this.setState({ userInput: "" });
  };
</code>```

答:
Here you can simply pass in the user ID in the POST request params. The POST URL in the frontend should look like this; {localhost:9000/like/${userID}}

You can get the user ID at the express backend like this;

```<code>router.post("/list/:id", checkToken, (req, res, next) => {
// Add an item to the database
const groceryListItem = new GroceryListItem({
    item: req.body.item,
    userId: req.params.id
})

groceryListItem.save()
    .then((groceryListItem) => {
        res.send(groceryListItem);
    }).catch(next);
</code>```

});

Title: Retrieving user data from mongoDB

Body:
I'm building an app where a user logs in and can create a grocery list on their account (there are more things they can do like create recipes, but this is the example I want to use). Right now I have it so everybody who logs in sees the same list. But I want each user to be able to log in and view their own grocery list that they made. I'm assuming the logic is literally like logging into a social media site and viewing YOUR profile, not somebody else's.

I'm using mongoDB/mongoose and I just read about the populate method as well as referencing other schemas in your current schema. Here is my schema for the list:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create item schema
const GroceryListItemSchema = new Schema({
  item: {
    type: String,
    required: [true, 'Item field is required']
  },
  userId: {
    type: mongoose.Schema.Types.ObjectId, ref: "user",
  }
});

// Create an Item model
const GroceryListItem = mongoose.model('groceryListItem', GroceryListItemSchema);
module.exports = GroceryListItem;

And here is the post request to add a list item:

//POST request for shopping list
router.post("/list", checkToken, (req, res, next) => {
  // Add an item to the database
  const groceryListItem = new GroceryListItem({
    item: req.body.item,
    userId: ???
  })

  groceryListItem.save()
    .then((groceryListItem) => {
      res.send(groceryListItem);
    })
    .catch(next);
});

Here is my userModel - not sure if this is necessary to show:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const UserSchema = new Schema({
  username: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  password2: {
    type: String,
    required: true,
  },

});

const User = mongoose.model("users", UserSchema);
module.exports = User;

(in case anyone is wondering why the model is called "users"-- that's what I initially called it on accident and when I changed the name to "user" it errored out...so I changed it back.)

I am not sure how to add the userId when making an instance of the groceryListItem. In the mongoose docs (https://mongoosejs.com/docs/populate.html#saving-refs), they use the example of a Story and Person Schema. They reference each other, and then they create an instance of Person, calling it author. Then they grab the _id from author and reference it in their instance of Story, called story1. So that makes sense to me. But the only way they can do that is because author and story1 are located in the same file.

So it seems like what I should do is grab the user _id by saying userId: users._id. But my new User instance is in my user routes. And I'd rather not combine the two. Because then I'd have another list to combine as well so that would be my user routes, recipe routes, and shopping list routes all in one file and that would be extremely messy.

Anyone have any idea how I can make this work? It seems so simple but for some reason I cannot figure this out.

Thank you!!

EDIT - frontend API call:

handleSubmitItem = (e) => {
    e.preventDefault();
    const newItem = {
      item: this.state.userInput,
    };

    authAxios
      .post(`http://localhost:4000/list/${userId}`, newItem)
      .then((res) => {
        this.setState({ items: [...this.state.items, newItem] });
        newItem._id = res.data._id;
      })
      .catch((err) => console.log(err));

    this.setState({ userInput: "" });
  };

Body:
Here you can simply pass in the user ID in the POST request params. The POST URL in the frontend should look like this; {localhost:9000/like/${userID}}

You can get the user ID at the express backend like this;

router.post("/list/:id", checkToken, (req, res, next) => {
// Add an item to the database
const groceryListItem = new GroceryListItem({
    item: req.body.item,
    userId: req.params.id
})

groceryListItem.save()
    .then((groceryListItem) => {
        res.send(groceryListItem);
    }).catch(next);

});


Title: Divide arbitrary binary integers by 3 in python

Body:
All the binary integers am given are always divisible by 3 so no floating-point values involved.
The return value must also be a binary string
Tried this but a and h are different yet they should be

>>> a="1111111111111111111111111111111111111111111111111111111111111111111111"
>>> f=int(a,base=2)
>>> print (f)
1180591620717411303423
>>> g = f/3
>>> c=int(g*3)
>>> print(c)
1180591620717411303424
>>> h = bin(c)
>>> print(h)
0b10000000000000000000000000000000000000000000000000000000000000000000000

Body:
Since your numbers are always divisible by 3 it is better to use // for integer division, because when you use floating point division for large numbers the result might not be exactly right.

So your code will be something like:

>>> a="1111111111111111111111111111111111111111111111111111111111111111111111"
>>> f=int(a, base=2)
>>> print(f)
1180591620717411303423
>>> g = f // 3
>>> c = g * 3
>>> print(c)
1180591620717411303423
>>> h = bin(c)
>>> print(h)
0b1111111111111111111111111111111111111111111111111111111111111111111111


问:
Docker Flask Conda - Not a conda environment
I am playing with flask app which uses conda environment. App works fine in local development so I wanted to dockerize it. Building via Dockerfile is successful but when I run app via:

```<code>docker run -p 5000:5000 3d-photo
</code>```

I got:

```<code>Not a conda environment: /opt/conda/envs/myenv
  File "app.py", line 18
    def render(filter_name: str):
                          ^
SyntaxError: invalid syntax
ERROR conda.cli.main_run:execute(39): Subprocess for 'conda run [u'python', u'app.py']' command failed.  Stderr was:
Not a conda environment: /opt/conda/envs/myenv
  File "app.py", line 18
    def render(filter_name: str):
                          ^
SyntaxError: invalid syntax
</code>```

Code which throws error looks like:

```<code>@app.route("/render/<filter_name>", methods=["POST"])
def render(filter_name: str):
    if request.method == "POST":
        f = request.files["file"]

        tempdir = tempfile.mkdtemp()
        in_dir = tempfile.mkdtemp(prefix="image_", dir=tempdir)
        out_dir = tempfile.mkdtemp(prefix="image_", dir=tempdir)

        image = Image.open(BytesIO(f.read()))
        image.save(in_dir.name + "/image.jpg", "JPEG")

        render_mp4(in_dir.name, out_dir.name, filter_name)

        filename = "image_" + filter_name + ".mp4"
        fout = open(os.path.join(out_dir.name, filename), "rb")

        response = make_response(fout.read())
        response.headers.set("Content-Type", "video/mp4")
        response.headers.set("Content-Disposition", "attachment", filename=filename)
        shutil.rmtree(tempdir)

        return response
</code>```

and the Dockerfile:

```<code>FROM ubuntu:latest
FROM continuumio/miniconda:latest
RUN apt-get update && apt-get install -y \
    python3-pip \
    python3-dev \
    build-essential
RUN pip3 install auxlib
COPY . /app
WORKDIR /app
RUN conda env create --file exported_conda_env.yml
SHELL ["conda", "run", "-n", "3DPhotoCreator", "/bin/bash", "-c"]
RUN pip install -r requirements.txt
RUN conda install pytorch==1.4.0 torchvision==0.5.0 cudatoolkit==10.1.243 -c pytorch
EXPOSE 5000
CMD ["conda", "run", "-n", "myenv", "python", "app.py"]
</code>```

Any hints here?

答:
You never created an environment named myenv.  It looks like you created an environment named 3DPhotoCreator, but not myenv.  It isn't clear what you're trying to do.

By the way, I think there is probably no need to use conda run, unless your dependencies rely on special environment variables being set.  (I don't think they do.)  You can probably just call the python interpreter without explicitly activating the environment:

```<code>CMD /opt/conda/envs/3DPhotoCreator/bin/python app.py
</code>```

Body:
I am playing with flask app which uses conda environment. App works fine in local development so I wanted to dockerize it. Building via Dockerfile is successful but when I run app via:

docker run -p 5000:5000 3d-photo

I got:

Not a conda environment: /opt/conda/envs/myenv
  File "app.py", line 18
    def render(filter_name: str):
                          ^
SyntaxError: invalid syntax
ERROR conda.cli.main_run:execute(39): Subprocess for 'conda run [u'python', u'app.py']' command failed.  Stderr was:
Not a conda environment: /opt/conda/envs/myenv
  File "app.py", line 18
    def render(filter_name: str):
                          ^
SyntaxError: invalid syntax

Code which throws error looks like:

@app.route("/render/<filter_name>", methods=["POST"])
def render(filter_name: str):
    if request.method == "POST":
        f = request.files["file"]

        tempdir = tempfile.mkdtemp()
        in_dir = tempfile.mkdtemp(prefix="image_", dir=tempdir)
        out_dir = tempfile.mkdtemp(prefix="image_", dir=tempdir)

        image = Image.open(BytesIO(f.read()))
        image.save(in_dir.name + "/image.jpg", "JPEG")

        render_mp4(in_dir.name, out_dir.name, filter_name)

        filename = "image_" + filter_name + ".mp4"
        fout = open(os.path.join(out_dir.name, filename), "rb")

        response = make_response(fout.read())
        response.headers.set("Content-Type", "video/mp4")
        response.headers.set("Content-Disposition", "attachment", filename=filename)
        shutil.rmtree(tempdir)

        return response

and the Dockerfile:

FROM ubuntu:latest
FROM continuumio/miniconda:latest
RUN apt-get update && apt-get install -y \
    python3-pip \
    python3-dev \
    build-essential
RUN pip3 install auxlib
COPY . /app
WORKDIR /app
RUN conda env create --file exported_conda_env.yml
SHELL ["conda", "run", "-n", "3DPhotoCreator", "/bin/bash", "-c"]
RUN pip install -r requirements.txt
RUN conda install pytorch==1.4.0 torchvision==0.5.0 cudatoolkit==10.1.243 -c pytorch
EXPOSE 5000
CMD ["conda", "run", "-n", "myenv", "python", "app.py"]

Any hints here?

Body:
You never created an environment named myenv.  It looks like you created an environment named 3DPhotoCreator, but not myenv.  It isn't clear what you're trying to do.

By the way, I think there is probably no need to use conda run, unless your dependencies rely on special environment variables being set.  (I don't think they do.)  You can probably just call the python interpreter without explicitly activating the environment:

CMD /opt/conda/envs/3DPhotoCreator/bin/python app.py


问:
Socket event handler access to socket instance
I'm trying to make my application more modular by moving socket event handlers to different files. specifically, i'm trying to do this

```<code>socket.on('foo',fooHandler)
socket.on('bar',barHandler)
</code>```

however , the handlers dont seem to have access to the socket instance. this doesnt work

```<code>fooHandler = (data) => {
  console.log(socket.id)
}
</code>```

socket is undefined. Is there a way i can access socket instance within the function. i've tried this.socket.id or specifying the socket argument in my handler. they dont seem to work

答:
Use bind function

```<code>socket.on('foo', fooHandler.bind(socket))
socket.on('bar', barHandler.bind(socket))

fooHandler = (data) {
// NOTE: You CAN'T use arrow function: fooHandler = (data) => ... here
// because it will ignore your `bind'
  console.log(this.id)  // `this' is socket
}
</code>```

You can optimize:

```<code>socket.on2 = function (arg, func) {
    socket.on(arg, func.bind(socket))
}
// Then:
socket.on2('foo', fooHandler)
</code>```

Body:
I'm trying to make my application more modular by moving socket event handlers to different files. specifically, i'm trying to do this

socket.on('foo',fooHandler)
socket.on('bar',barHandler)

however , the handlers dont seem to have access to the socket instance. this doesnt work

fooHandler = (data) => {
  console.log(socket.id)
}

socket is undefined. Is there a way i can access socket instance within the function. i've tried this.socket.id or specifying the socket argument in my handler. they dont seem to work

Body:
Use bind function

socket.on('foo', fooHandler.bind(socket))
socket.on('bar', barHandler.bind(socket))

fooHandler = (data) {
// NOTE: You CAN'T use arrow function: fooHandler = (data) => ... here
// because it will ignore your `bind'
  console.log(this.id)  // `this' is socket
}

You can optimize:

socket.on2 = function (arg, func) {
    socket.on(arg, func.bind(socket))
}
// Then:
socket.on2('foo', fooHandler)


问:
Send string literal as argument in C++ template - Parameter pack
My function declaration and implementation.
It accepts variable number of arguments

```<code>template <typename... ParamType,
            typename = typename std::void_t<std::enable_if_t<std::is_same_v<ParamType, std::string> ||
                                                            std::is_floating_point_v<ParamType> ||
                                                            std::is_integral_v<ParamType>>...>>
static inline void Log(const ParamType &... args)
{
   //Implementation
}
</code>```

I need to add support for cstrings(char *, const char *) and string literals.

```<code>Console::Log("Non std::string literal"); //ERROR (const char [24])
Console::Log("hola %s %s %d %s"s,"helloWorld"s,"Joma"s,1, 1990); //OK
Console::Log<String, String, String,int, int>("hola %s %s %d %s"s,"helloWorld"s,"Joma"s,1, 1990); //OK
</code>```

答:
The key expression is this disjunction:

```<code>std::is_same_v<ParamType, std::string> ||
std::is_floating_point_v<ParamType> ||
std::is_integral_v<ParamType>
</code>```

You just need to add these terms:

```<code>std::is_same_v<std::decay_t<ParamType>, char const *> ||
std::is_same_v<std::decay_t<ParamType>, char *>
</code>```

The usage of std::decay_t will cause the type of "abc" (which is char const (&)[4]) to decay to char const *.

Note that the function will receive string literal arguments as char const (&)[N] so the implementation needs to be able to handle that.

Body:
My function declaration and implementation.
It accepts variable number of arguments

template <typename... ParamType,
            typename = typename std::void_t<std::enable_if_t<std::is_same_v<ParamType, std::string> ||
                                                            std::is_floating_point_v<ParamType> ||
                                                            std::is_integral_v<ParamType>>...>>
static inline void Log(const ParamType &... args)
{
   //Implementation
}

I need to add support for cstrings(char *, const char *) and string literals.

Console::Log("Non std::string literal"); //ERROR (const char [24])
Console::Log("hola %s %s %d %s"s,"helloWorld"s,"Joma"s,1, 1990); //OK
Console::Log<String, String, String,int, int>("hola %s %s %d %s"s,"helloWorld"s,"Joma"s,1, 1990); //OK

Body:
The key expression is this disjunction:

std::is_same_v<ParamType, std::string> ||
std::is_floating_point_v<ParamType> ||
std::is_integral_v<ParamType>

You just need to add these terms:

std::is_same_v<std::decay_t<ParamType>, char const *> ||
std::is_same_v<std::decay_t<ParamType>, char *>

The usage of std::decay_t will cause the type of "abc" (which is char const (&)[4]) to decay to char const *.

Note that the function will receive string literal arguments as char const (&)[N] so the implementation needs to be able to handle that.


答:
```<code>$json = json_decode('...your json string...');
$rows_that_contains_catid_12 = array();
$allowed_catid_values = array("12","12-");
foreach($json as &$v) {
    foreach($v as &$rv){
        if(in_array($rv['catid'],$allowed_catid_values))
            $rows_that_contains_catid_12[] = $rv;
    }
}

</code>```

<p>$rows_that_contains_catid_12 holds your result...
Regards</p>

Title: PHP JSON Search with key name

Body:
I have following JSON Data

"12-305":[{"catid":"12","fname":"SALADS","ord":"0","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"6","Valid":"0","Phone":"1","Web":"1","ovalue":"All Salads","id":"305","icon":"","price":"0"}]
"12-270":[{"catid":"12","fname":"SALADS","ord":"1","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"6","Valid":"0","Phone":"1","Web":"1","ovalue":"No Salad","id":"270","icon":"","price":"0"}],
"12-273":[{"catid":"12","fname":"SAUCE","ord":"2","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"No Sauce","id":"273","icon":"","price":"0"}],
"15-19":[{"catid":"15","fname":"SAUCE","ord":"2","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"2","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"BBQ Sauce","id":"19","icon":"","price":"0"}],
"12-19":[{"catid":"12","fname":"SAUCE","ord":"2","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"BBQ Sauce","id":"19","icon":"","price":"0"}],
"15-20":[{"catid":"15","fname":"SAUCE","ord":"3","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"2","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"Garlic Sauce","id":"20","icon":"","price":"0"}],
"12-20":[{"catid":"12","fname":"SAUCE","ord":"3","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"Garlic Sauce","id":"20","icon":"","price":"0"}]`

I want to only grab rows that contains "catid":"12" or key is like "12-" is this posible with using php json?

Body:
$json = json_decode('...your json string...');
$rows_that_contains_catid_12 = array();
$allowed_catid_values = array("12","12-");
foreach($json as &$v) {
    foreach($v as &$rv){
        if(in_array($rv['catid'],$allowed_catid_values))
            $rows_that_contains_catid_12[] = $rv;
    }
}

$rows_that_contains_catid_12 holds your result...
Regards


问:
ERROR: Could not get unknown property 'com' for root project 'myApp' of type org.gradle.api.Project
I want to try out Android Studio.
I have a fresh installation on Ubuntu Linux.

When I create new project
File->New->New Project...

Some files are created and I get error

ERROR: Could not get unknown property 'com' for root project 'myApp'
  of type org.gradle.api.Project.

答:
I solved it in this mode:

1) Go to File;

2) Invalidate Caches/Restart...

3) Click on Just Restart...

Now go on explorer:

1) this PC/Local Disk/Users/user

2) now delete the folder called: ".gradle"

3) Launch Android Studio

4) Wait for uploads

5) And now click sync

It will probably give you an error, click on written underlined in blue under the error, and wait;

FINISH


问:
Dataframe column not converting to date after groupby
I am reading a dataset in which there are few columns. In the one column is of date. Date contains mixed format for date (both 01 and 1) and year(both 2020 and 20).

I wanted to group data based on date and merge the content of other columns so I used this:

```<code>covid_df['Date'] = pd.to_datetime(covid_df['Date'],format="%d/%m/%y").dt.strftime("%d/%m/%y")
covid_df=covid_df.groupby('Date').agg(lambda col: col.tolist()).reset_index()
</code>```

Now, that I have what I wanted I checked the columns data type again and found that now date column is again having object data type which means a string. So I converted my data frame one more time and sort it based on date column and do a tail operation. But sort is not happening correctly:

```<code>covid_df['Date'] = pd.to_datetime(covid_df['Date'],format="%d/%m/%y").dt.strftime("%d/%m/%y")
covid_df.sort_values(by='Date')
print(covid_df.tail(10))
</code>```

Output:

```<code>'
'
'
118  30/04/20  ...  [33, 1403, 1, 42, 403, 56, 38, 3439, 7, 4082, ...
119  30/05/20  ...  [33, 3436, 3, 1024, 3376, 289, 415, 2, 17386, ...
120  31/01/20  ...                                                [1]
121  31/03/20  ...  [40, 10, 15, 13, 8, 97, 5, 73, 40, 3, 54, 83, ...

[10 rows x 5 columns]

</code>```

You can clearly see the date is not in sorted order.

答:
I think that the

```<code>covid_df.sort_values(by='Date')
</code>```

creates a copy of your dataframe, but not saving it. So in order to do that, you should probably use

```<code>covid_df = covid_df.sort_values(by='Date')
</code>```

Body:
I am reading a dataset in which there are few columns. In the one column is of date. Date contains mixed format for date (both 01 and 1) and year(both 2020 and 20).

I wanted to group data based on date and merge the content of other columns so I used this:

covid_df['Date'] = pd.to_datetime(covid_df['Date'],format="%d/%m/%y").dt.strftime("%d/%m/%y")
covid_df=covid_df.groupby('Date').agg(lambda col: col.tolist()).reset_index()

Now, that I have what I wanted I checked the columns data type again and found that now date column is again having object data type which means a string. So I converted my data frame one more time and sort it based on date column and do a tail operation. But sort is not happening correctly:

covid_df['Date'] = pd.to_datetime(covid_df['Date'],format="%d/%m/%y").dt.strftime("%d/%m/%y")
covid_df.sort_values(by='Date')
print(covid_df.tail(10))

Output:

'
'
'
118  30/04/20  ...  [33, 1403, 1, 42, 403, 56, 38, 3439, 7, 4082, ...
119  30/05/20  ...  [33, 3436, 3, 1024, 3376, 289, 415, 2, 17386, ...
120  31/01/20  ...                                                [1]
121  31/03/20  ...  [40, 10, 15, 13, 8, 97, 5, 73, 40, 3, 54, 83, ...

[10 rows x 5 columns]

You can clearly see the date is not in sorted order.

Body:
I think that the

covid_df.sort_values(by='Date')

creates a copy of your dataframe, but not saving it. So in order to do that, you should probably use

covid_df = covid_df.sort_values(by='Date')


问:
I want to make \ into a string
Edit= Some moderators recommended me to make my self more clear, so here we go.

As a personal project in python, I'm making a very simple software that asks the user for an email address and then checks if the syntaxis of the email is correct.

I made a tuple of special characters that are not allowed in an email address, one of those characters is "\". I was looking online like crazy for how to make \ into a str with no result. I try looking online for the use of the function \ with no result either.

V = "\" doesn't work, it gives me a syntax error. I know it is possible to make it into a string because I've done it with an Input() command.

Please help.

答:
It's not clear to me what language you're using - but in most cases you need to escape the backslash, as it is an escape character itself.

```<code>V="\\"
</code>```

This functionality exists that you can include special characters (in this case, a double quote) in the string:

```<code>V="The following will be in quotes: \"Hello, World\""
</code>```

In this case, the escaped double quotes will be treated as literal characters in the string, and will not signal the end of the string as they would without the escape character.

Title: I want to make \ into a string

Body:
It's not clear to me what language you're using - but in most cases you need to escape the backslash, as it is an escape character itself.

V="\\"

This functionality exists that you can include special characters (in this case, a double quote) in the string:

V="The following will be in quotes: \"Hello, World\""

In this case, the escaped double quotes will be treated as literal characters in the string, and will not signal the end of the string as they would without the escape character.


问:
Java - Generic Drools rule
I would like to create my rule more Generic format which mean it should be validate the fields and values. Following my POJO structure.

```<code> public class RulesModel
private String field;
private List<String> values;
// other stuff
</code>```

And my rule

```<code>rule "sample"
when
    $rule : RulesModel( field == "source", values contains "facebook", values contains "youtube", value not contains "instagram" )
then
    // actions
end
</code>```

It's working fine to validate single field, but i want to validate the multiple fields of RulesModel.
So i desire to create the POJO

```<code>public class RulesModelList {

    private List<RulesModel> ruleList;
    // Getter & Setter
}
</code>```

So now when i pass the list of RulesModel by using RulesModelList class the rule should be validate like below

```<code>$rule : RulesModel( field == "source", values contains "facebook") && $rule : RulesModel( field == "createdBy", values contains "admin")
</code>```

How to validate that in Drools?

Thanks in advance.

答:
If all you want to do is verify that those two (or three or however many) RulesModels are in the list, it's quite simple:

```<code>// Example from question
rule "Verify Facebook source and admin createdBy"
when
  RulesModelList( $list: ruleList)
  exists(RulesModel( field == "source", values contains "facebook") from $list)
  exists(RulesModel( field == "createdBy", values contains "admin") from $list)
then
  // do something
end
</code>```

Basically I get the list of RulesModel out of the RulesModelList input and assign to $list. Then I verify that there exists a RulesModel instance that matches my 'source' criteria, and then one that matches the 'createdBy' criteria.

In the example I used exists() instead of assigning a variable because my sample rule doesn't need to make use of the RulesModel instance on the right hand side. If you do need to do something with the RulesModel instance, simply replace exists() with an assignment like this:

```<code>$source: RulesModel( field == "source", values contains "facebook") from $list
$createdBy: RulesModel( field == "createdBy", values contains "admin") from $list
</code>```

There is no need to do an accumulate unless you're trying to iterate over the list and find things that match a certain criteria. For example, let's say that one of the "field" values is "updatedBy", and there can be multiple RulesModel instances with that field name. To get the subset of the RulesModel instances with field name "updatedBy", you'd use accumulate, as Mykhaylo demonstrated in his answer.

But if all you want to do is verify that a list contains an object that meets your criteria, accumulate is overkill and this here is the appropriate solution.

Title: Java - Generic Drools rule

Body:
I would like to create my rule more Generic format which mean it should be validate the fields and values. Following my POJO structure.

 public class RulesModel
private String field;
private List<String> values;
// other stuff

And my rule

rule "sample"
when
    $rule : RulesModel( field == "source", values contains "facebook", values contains "youtube", value not contains "instagram" )
then
    // actions
end

It's working fine to validate single field, but i want to validate the multiple fields of RulesModel.
So i desire to create the POJO

public class RulesModelList {

    private List<RulesModel> ruleList;
    // Getter & Setter
}

So now when i pass the list of RulesModel by using RulesModelList class the rule should be validate like below

$rule : RulesModel( field == "source", values contains "facebook") && $rule : RulesModel( field == "createdBy", values contains "admin")

How to validate that in Drools?

Thanks in advance.

Body:
If all you want to do is verify that those two (or three or however many) RulesModels are in the list, it's quite simple:

// Example from question
rule "Verify Facebook source and admin createdBy"
when
  RulesModelList( $list: ruleList)
  exists(RulesModel( field == "source", values contains "facebook") from $list)
  exists(RulesModel( field == "createdBy", values contains "admin") from $list)
then
  // do something
end

Basically I get the list of RulesModel out of the RulesModelList input and assign to $list. Then I verify that there exists a RulesModel instance that matches my 'source' criteria, and then one that matches the 'createdBy' criteria.

In the example I used exists() instead of assigning a variable because my sample rule doesn't need to make use of the RulesModel instance on the right hand side. If you do need to do something with the RulesModel instance, simply replace exists() with an assignment like this:

$source: RulesModel( field == "source", values contains "facebook") from $list
$createdBy: RulesModel( field == "createdBy", values contains "admin") from $list

There is no need to do an accumulate unless you're trying to iterate over the list and find things that match a certain criteria. For example, let's say that one of the "field" values is "updatedBy", and there can be multiple RulesModel instances with that field name. To get the subset of the RulesModel instances with field name "updatedBy", you'd use accumulate, as Mykhaylo demonstrated in his answer.

But if all you want to do is verify that a list contains an object that meets your criteria, accumulate is overkill and this here is the appropriate solution.


问:
spring jwt decoder openid token
External OAuth2 Provider doesn't have public JwkUri, so I tried too override default behavior using following code snippet:

```<code>@EnableWebSecurity
public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter {
 @Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("**/oauth2/code/esia**", "**/code/esia**", "**esia**").permitAll()
            .antMatchers("/user").fullyAuthenticated()
            .anyRequest().authenticated()
            .and()
            .csrf().disable()
            .cors().disable()
            .oauth2Client()
            .clientRegistrationRepository(this.clientRegistrationRepository)
            .authorizationCodeGrant()
            .authorizationRequestResolver(new CustomAuthorizationRequestResolver(
                    this.clientRegistrationRepository, esiaConfig, signatureUtil, timeUtil))
            .accessTokenResponseClient(customAccessTokenResponseClient())
            .and().and().oauth2Login().tokenEndpoint().accessTokenResponseClient(customAccessTokenResponseClient())
            .and().and().oauth2ResourceServer().jwt();
}
@Bean
JwtDecoder jwtDecoder() {
 return  new CustomJwtDecoder();
}
}

class CustomJwtDecoder implements JwtDecoder {
@Override
public Jwt decode(String token) throws JwtException {
    System.out.println(token);
    return null;
}
}
</code>```

However Spring Security somehow still uses default realization and I am getting the following error...

```<code>[missing_signature_verifier] Failed to find a Signature Verifier for Client Registration: 'esia'. Check to ensure you have configured the JwkSet URI.
</code>```

Also, I tried to set custom AuthenticationProvider but spring ignores it.

I guess the catch is that spring`s OAuth2LoginConfigurer method init(B http) calls new OidcAuthorizationCodeAuthenticationProvider(accessTokenResponseClient, oidcUserService)

答:
I was facing the same issue even with 5.2.x release. In my case, the real problem was not in the  JwtDecoder. I have fixed the issue by setting the jwk-set-uri property (you can change the provider name by the provider which you are using e.g okta, google etc.) :</p>

```<code>security.oauth2.client.provider.azure.jwk-set-uri: https://login.microsoftonline.com/{tenant}/discovery/keys

</code>```

Title: spring jwt decoder openid token

Body:
External OAuth2 Provider doesn't have public JwkUri, so I tried too override default behavior using following code snippet:

@EnableWebSecurity
public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter {
 @Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("**/oauth2/code/esia**", "**/code/esia**", "**esia**").permitAll()
            .antMatchers("/user").fullyAuthenticated()
            .anyRequest().authenticated()
            .and()
            .csrf().disable()
            .cors().disable()
            .oauth2Client()
            .clientRegistrationRepository(this.clientRegistrationRepository)
            .authorizationCodeGrant()
            .authorizationRequestResolver(new CustomAuthorizationRequestResolver(
                    this.clientRegistrationRepository, esiaConfig, signatureUtil, timeUtil))
            .accessTokenResponseClient(customAccessTokenResponseClient())
            .and().and().oauth2Login().tokenEndpoint().accessTokenResponseClient(customAccessTokenResponseClient())
            .and().and().oauth2ResourceServer().jwt();
}
@Bean
JwtDecoder jwtDecoder() {
 return  new CustomJwtDecoder();
}
}

class CustomJwtDecoder implements JwtDecoder {
@Override
public Jwt decode(String token) throws JwtException {
    System.out.println(token);
    return null;
}
}

However Spring Security somehow still uses default realization and I am getting the following error...

[missing_signature_verifier] Failed to find a Signature Verifier for Client Registration: 'esia'. Check to ensure you have configured the JwkSet URI.

Also, I tried to set custom AuthenticationProvider but spring ignores it.

I guess the catch is that spring`s OAuth2LoginConfigurer method init(B http) calls new OidcAuthorizationCodeAuthenticationProvider(accessTokenResponseClient, oidcUserService)

Body:
I was facing the same issue even with 5.2.x release. In my case, the real problem was not in the  JwtDecoder. I have fixed the issue by setting the jwk-set-uri property (you can change the provider name by the provider which you are using e.g okta, google etc.) :

security.oauth2.client.provider.azure.jwk-set-uri: https://login.microsoftonline.com/{tenant}/discovery/keys


问:
Changing backgroundcolor on custom UITableViewCell won't show
I'm trying to change the background color of a custom cell when clicked..  Here is my code:

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    UITableViewCell *cell = [tableView cellForRowAtIndexPath: indexPath];
    if (...condition...) {
        cell.backgroundColor = [UIColor clearColor];
    } else {
        cell.backgroundColor = [UIColor yellowColor];
    }
}
</code>```

Now, I did debug, and the cell.backgroundColor = [UIColor clearColor]; gets executed, but the cell stays yellow!!!  This only happens to some of the cells (ones that are yellow, and reused)..

Any suggestions?

答:
I got it to work.  Had to use
   aCell.contentView.backgroundColor
instead of
   aCell.backgroundColor

That did the trick for me.

Body:
I'm trying to change the background color of a custom cell when clicked..  Here is my code:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    UITableViewCell *cell = [tableView cellForRowAtIndexPath: indexPath];
    if (...condition...) {
        cell.backgroundColor = [UIColor clearColor];
    } else {
        cell.backgroundColor = [UIColor yellowColor];
    }
}

Now, I did debug, and the cell.backgroundColor = [UIColor clearColor]; gets executed, but the cell stays yellow!!!  This only happens to some of the cells (ones that are yellow, and reused)..

Any suggestions?


问:
restructure elasticsearch index to allow filtering on sum of values
I've an index of products.

Each product, has several variants (can be a few or hundreds, each has a color & size e.g. Red)

Each variant, is available (in a certain quantity) at several warehouses (aronud 100 warehouses).

Warehouses have codes e.g. AB, XY, CD etc.

If I had my choice, I'd index it as:

```<code>stock: {
  Red: {
    S: { AB: 100, XY: 200, CD: 20 },
    M: { AB: 0, XY: 500, CD: 20 },
    2XL: { AB: 5, XY: 0, CD: 9 }
  },
  Blue: {
    ...
  }
}
</code>```

Here's a kind of customer query I might receive:

Show me all products, that have Red.S color in stock (minimum 100) at warehouses AB & XY.

So this would probably be a filter like

```<code>Red.S.AB > 100 AND Red.S.XY > 100
</code>```

I'm not writing whole filter query here, but its straightforward in elastic.

We might also get SUM queries, e.g. the sum of inventories at AB & XY should be > 500.

That'd be easy through a script filter, say Red.S.AB + Red.S.XY > 500

The problem is, given 100 warehouses, 100 sizes, 25 colors, this easily needs 100*100*25 = 250k mappings. Elasticsearch simply can't handle that many number of keys.

The easy answer is use nested documents, but nested documents pose a particular problem. We cannot sum across a given selection of nested documents, and nested docs are slow, specially when we're going to have 250k per product.

I'm open to external solutions than elastic as well. We're rails/postgres stack.

答:
The best possible solution will be to create separate indexes for the warehouses and each warehouse index will have documents. One document per product/size/color/warehouse with related values like this:

```<code>{
  "product": 123,
  "color": "Red",
  "size": "S",
  "warehouse": "AB",
  "quantity": 100
}
</code>```

This will reduce your mappings 100 * 25 = 2500 mappings per index.

Rest for other operations, I feel @Val has mentioned in his answer which is quite impressive and beautiful.

Coming to external solutions, I would say you want to carry to out task of storing data, searching it and fetching it. Elasticsearch and Apache Solr are the best search engines to carry out these kind of tasks. I have not tried Apache Solr but I would highly recommend to go with Elasticsearch because of it's features, active community support and searching is really fast. Searching can also be made fast using analyzers and tokenizers. It also has some features like Full-Text Searching and Term Level Searching to customize searching according to situation or problem statement.

Body:
I've an index of products.

Each product, has several variants (can be a few or hundreds, each has a color & size e.g. Red)

Each variant, is available (in a certain quantity) at several warehouses (aronud 100 warehouses).

Warehouses have codes e.g. AB, XY, CD etc.

If I had my choice, I'd index it as:

stock: {
  Red: {
    S: { AB: 100, XY: 200, CD: 20 },
    M: { AB: 0, XY: 500, CD: 20 },
    2XL: { AB: 5, XY: 0, CD: 9 }
  },
  Blue: {
    ...
  }
}

Here's a kind of customer query I might receive:

Show me all products, that have Red.S color in stock (minimum 100) at warehouses AB & XY.

So this would probably be a filter like

Red.S.AB > 100 AND Red.S.XY > 100

I'm not writing whole filter query here, but its straightforward in elastic.

We might also get SUM queries, e.g. the sum of inventories at AB & XY should be > 500.

That'd be easy through a script filter, say Red.S.AB + Red.S.XY > 500

The problem is, given 100 warehouses, 100 sizes, 25 colors, this easily needs 100*100*25 = 250k mappings. Elasticsearch simply can't handle that many number of keys.

The easy answer is use nested documents, but nested documents pose a particular problem. We cannot sum across a given selection of nested documents, and nested docs are slow, specially when we're going to have 250k per product.

I'm open to external solutions than elastic as well. We're rails/postgres stack.

Body:
The best possible solution will be to create separate indexes for the warehouses and each warehouse index will have documents. One document per product/size/color/warehouse with related values like this:

{
  "product": 123,
  "color": "Red",
  "size": "S",
  "warehouse": "AB",
  "quantity": 100
}

This will reduce your mappings 100 * 25 = 2500 mappings per index.

Rest for other operations, I feel @Val has mentioned in his answer which is quite impressive and beautiful.

Coming to external solutions, I would say you want to carry to out task of storing data, searching it and fetching it. Elasticsearch and Apache Solr are the best search engines to carry out these kind of tasks. I have not tried Apache Solr but I would highly recommend to go with Elasticsearch because of it's features, active community support and searching is really fast. Searching can also be made fast using analyzers and tokenizers. It also has some features like Full-Text Searching and Term Level Searching to customize searching according to situation or problem statement.


问:
How to configure S3 bucket policies for my app
I have a bucket called prod, with a directory tree that looks like this:

```<code>prod
 logs
 uploads
  user
   doc
    1
     a.jpg
     b.jpg
    2
     a.jpg
     b.jpg
  thing
   photos
    1
     a.jpg
     b.jpg
    2
     a.jpg
     b.jpg
</code>```

Everything in thing/photos should be public. GET requests should be allowed for everyone, but PUT and POST requests should only be allowed when users upload a file through my app.

The user/doc directory on the other hand, I want to be completely private. POST requests should be allowed for users who upload a file through my app, but the only person who should be able to GET those resources is an admin. That data is encrypted before it is stored, but I want to make sure that the folder is not accessible to the public or to other users of my app.

After reading A deep dive into AWS S3 access controls – taking full control over your assets and ACLs - What Permissions Can I Grant? I remain confused about how to accomplish what I want. The overlapping access controls leave me feeling bewildered, and I cannot find a tutorial that explains any of this in an action-oriented approach. Given the number of data leaks caused by improperly set S3 bucket policies, it seems likely that I'm not the only person who misunderstands this.

How are your policies set? Do you have a link to a better tutorial than the ones I've found? Thank you!

答:
Disclamer: I'm assuming that your mobile app is not directly talking to S3, but instead you have a backend API server that manages the S3 access.

When you PUT the objects from your app to thing/photos you simply use "public read" permissions, or

```<code><Grant>
  <Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Group">
    <URI>http://acs.amazonaws.com/groups/global/AllUsers</URI>
  </Grantee>
  <Permission>READ</Permission>
</Grant>
</code>```

from your second link. For user/doc just keep things "private" for the owner (your AWS account has FULL_ACCESS grant) of the bucket and then control the access to objects via application logic, e.g only the admin can see the content by proxing the S3 "private" objects via, let's say presigned URLs.

Finally, make sure that the user/role that accesses the bucket from your app has an attached policy like:

```<code>{
   "Version":"2012-10-17",
   "Statement":[
      {
         "Effect":"Allow",
         "Action": ["s3:GetObject", "s3:PutObject"],
         "Resource": ["arn:aws:s3:::examplebucket/*", arn:aws:s3:::examplebucket/"]
      }
   ]
}
</code>```

Another way to make the thing/photos public to anyone is via a bucket policy, like:

```<code>{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Sid":"Example",
      "Effect":"Allow",
      "Principal": "*",
      "Action":["s3:GetObject"],
      "Resource":["arn:aws:s3:::examplebucket/things/photos/*"]
      }
  ]
}
</code>```

You're mostly confused because of the different kind of options to control the access – bucket policies and object level ACL.

Body:
I have a bucket called prod, with a directory tree that looks like this:

prod
 logs
 uploads
  user
   doc
    1
     a.jpg
     b.jpg
    2
     a.jpg
     b.jpg
  thing
   photos
    1
     a.jpg
     b.jpg
    2
     a.jpg
     b.jpg

Everything in thing/photos should be public. GET requests should be allowed for everyone, but PUT and POST requests should only be allowed when users upload a file through my app.

The user/doc directory on the other hand, I want to be completely private. POST requests should be allowed for users who upload a file through my app, but the only person who should be able to GET those resources is an admin. That data is encrypted before it is stored, but I want to make sure that the folder is not accessible to the public or to other users of my app.

After reading A deep dive into AWS S3 access controls – taking full control over your assets and ACLs - What Permissions Can I Grant? I remain confused about how to accomplish what I want. The overlapping access controls leave me feeling bewildered, and I cannot find a tutorial that explains any of this in an action-oriented approach. Given the number of data leaks caused by improperly set S3 bucket policies, it seems likely that I'm not the only person who misunderstands this.

How are your policies set? Do you have a link to a better tutorial than the ones I've found? Thank you!

Body:
Disclamer: I'm assuming that your mobile app is not directly talking to S3, but instead you have a backend API server that manages the S3 access.

When you PUT the objects from your app to thing/photos you simply use "public read" permissions, or

<Grant>
  <Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Group">
    <URI>http://acs.amazonaws.com/groups/global/AllUsers</URI>
  </Grantee>
  <Permission>READ</Permission>
</Grant>

from your second link. For user/doc just keep things "private" for the owner (your AWS account has FULL_ACCESS grant) of the bucket and then control the access to objects via application logic, e.g only the admin can see the content by proxing the S3 "private" objects via, let's say presigned URLs.

Finally, make sure that the user/role that accesses the bucket from your app has an attached policy like:

{
   "Version":"2012-10-17",
   "Statement":[
      {
         "Effect":"Allow",
         "Action": ["s3:GetObject", "s3:PutObject"],
         "Resource": ["arn:aws:s3:::examplebucket/*", arn:aws:s3:::examplebucket/"]
      }
   ]
}

Another way to make the thing/photos public to anyone is via a bucket policy, like:

{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Sid":"Example",
      "Effect":"Allow",
      "Principal": "*",
      "Action":["s3:GetObject"],
      "Resource":["arn:aws:s3:::examplebucket/things/photos/*"]
      }
  ]
}

You're mostly confused because of the different kind of options to control the access – bucket policies and object level ACL.