问:
find the start of a matched region (java regex)
Suppose the string I am interested is similar to these num3.a, num4.b, etc.
(but I don't want it to match these foo.num3.a, whatever.num2.b)

I have this regex to match them Pattern p = Pattern.compile("[^\\.]\\bnum(\\d*)(?=\\.)";

Given this input string : (num3.a)

```<code>Matcher m = p.matcher("(num3.a)");
if (m.find())
    System.out.println(m.start()); // This would print 0 rather than 1  WHY?
</code>```

How do I change the code so it prints 1 instead? (because 1 is the index of n, which is the start of my interested pattern)

答:
```<code>Pattern p = Pattern.compile("\\,\\d*");
    String inpu = "Hotel Class : 5,106936 ";
    Matcher m = p.matcher(inpu);

    if (m.find())
    {
        System.out.println(inpu.substring(m.start(0), m.end(0)));
    }
</code>```

The output is "5,106936"

Body:
Suppose the string I am interested is similar to these num3.a, num4.b, etc.
(but I don't want it to match these foo.num3.a, whatever.num2.b)

I have this regex to match them Pattern p = Pattern.compile("[^\\.]\\bnum(\\d*)(?=\\.)";

Given this input string : (num3.a)

Matcher m = p.matcher("(num3.a)");
if (m.find())
    System.out.println(m.start()); // This would print 0 rather than 1  WHY?

How do I change the code so it prints 1 instead? (because 1 is the index of n, which is the start of my interested pattern)

Body:
Pattern p = Pattern.compile("\\,\\d*");
    String inpu = "Hotel Class : 5,106936 ";
    Matcher m = p.matcher(inpu);

    if (m.find())
    {
        System.out.println(inpu.substring(m.start(0), m.end(0)));
    }

The output is "5,106936"


来源: stackexchange

问:
Gracefully stopping an std::thread?
I have a worker std::thread and I want its main loop to check if some other thread tells it to stop looping and exit.

What is a good cross platform way to do this? Does boost provide some event object for it?

Is using just a bool considered thread-safe?

答:
.. well it depends. What is the thread doing?  Does it block on anything, I/O, sleep, or some other API?

If it's just CPU-looping all the time and it does not matter about exactly when it stops and it stops and exits, then just use a boolean.  There's no point, in this case, in locking up a 'stopAndExit' boolean.

If the work thread does not read it as true on one loop when perhaps it should, because of some lack of atomicity, it will get it next time round.  Why perform locks/API calls when you don't have to?  A kernel level call from user to acquire/release a synchronisation object will take ages compared with a simple 'if (stop) exit;', wasting time on each loop that could have been used for calculation, or whatever you do in your CPU-bound thread.

It is cross-platform

Regards,
Martin

ContentLicense: CC BY-SA 3.0

Title: Gracefully stopping an std::thread?


问:
Hypothesis - reuse @given between tests
I've been using hypothesis for some time now. I'm wondering how I could reuse @given parts.

Some of the ones I have are like 20 lines and I copy the whole @given part above a couple of the test cases.

A simple example of a test

@given(
    some_dict=st.fixed_dictionaries(
        {
            "test1": st.just("name"),
            "test2": st.integers()
            }
        )
    )
def test_that uses_some_dict_to_initialize_object_im_testing(some_dict):
    pass
```

What would be the best way to go around reusing @given blocks?

答:
Strategies are designed as composable objects, there is no problem with reusing them.

Thus an alternative to the accepted answer simply store configured sub-strategies as reusable globals e.g.

a_strategy = st.fixed_dictionaries({ "test1": st.just("name"), "test2": st.integers()})

@given(some_dict=a_strategy)
def test_uses_some_dict_to_initialize_object_im_testing(some_dict):
    ...

@given(some_dict=a_strategy, value=st.integers())
def test_other(some_dict, value):
    ...
```

The timezones examples shows that pattern, it defines an aware_datetimes strategy and uses that strategy in multiple tests, composed with a variable number of siblings.

ContentLicense: CC BY-SA 4.0

Title: Hypothesis - reuse @given between tests

Body:
I've been using hypothesis for some time now. I'm wondering how I could reuse @given parts.

Some of the ones I have are like 20 lines and I copy the whole @given part above a couple of the test cases.

A simple example of a test

@given(
    some_dict=st.fixed_dictionaries(
        {
            "test1": st.just("name"),
            "test2": st.integers()
            }
        )
    )
def test_that uses_some_dict_to_initialize_object_im_testing(some_dict):
    pass

What would be the best way to go around reusing @given blocks?

Body:
Strategies are designed as composable objects, there is no problem with reusing them.

Thus an alternative to the accepted answer simply store configured sub-strategies as reusable globals e.g.

a_strategy = st.fixed_dictionaries({ "test1": st.just("name"), "test2": st.integers()})

@given(some_dict=a_strategy)
def test_uses_some_dict_to_initialize_object_im_testing(some_dict):
    ...

@given(some_dict=a_strategy, value=st.integers())
def test_other(some_dict, value):
    ...

The timezones examples shows that pattern, it defines an aware_datetimes strategy and uses that strategy in multiple tests, composed with a variable number of siblings.


问:
Convert ARRAY_UPPER() to Hive query
I have to convert a postgres query to a hive query as :

```<code>Select
SUBSTRING(col_name[ARRAY_UPPER(col_name)][2],1,8)
from tab
</code>```

As hive does not have anything called ARRAY_UPPER then how can we covert?
In my hive table corresponding col_name is of String type, so I tried as below but not getting desired output.

```<code>select substring(col_name,-10,8) from hive_tab
</code>```

Input and output are:

答:
```<code>with data_example as(
select
array(1476290200, 35525707293822) as a
)

select substr(a[size(a)-1],-7)
  from data_example
</code>```

Result:

```<code>7293822
</code>```

Title: Convert ARRAY_UPPER() to Hive query

Body:
I have to convert a postgres query to a hive query as :

Select
SUBSTRING(col_name[ARRAY_UPPER(col_name)][2],1,8)
from tab

As hive does not have anything called ARRAY_UPPER then how can we covert?
In my hive table corresponding col_name is of String type, so I tried as below but not getting desired output.

select substring(col_name,-10,8) from hive_tab

Input and output are:

Body:
with data_example as(
select
array(1476290200, 35525707293822) as a
)

select substr(a[size(a)-1],-7)
  from data_example

Result:

7293822


问:
Numbering and referencing images in Pandoc
I would like to add captions such as "Figure 1: Blah Blah" to my images in Pandoc and be able to refer to them like see @Figure1. I am using gpp (a pre-processor) to add captions to my images and do all sorts of fancy things like change size, format etc. However, I am unable to implement a counter for images like Figure1, Figure2, etc.

I have defined the following function in my gpp script:

```<code>\define{\counter}{0}

\defeval{count}{\eval{\counter+ 1}
</code>```

and I call it like this in my script: \count

However, \counter doesnt get evaluated in my gpp script and I see the following error: unfinished macro

How should I implement this counter? I am using -T (tex) mode in gpp

答:
Multilingual CSS numbering without cross-referencing

Here is a simple method for automatic CSS numbering with labels dependent on the document language. This simple CSS method does not allow for referencing.

For automatic numbering with referencing, rather use pandoc-fignos of the pandoc-xnos suite.

```<code>body {
    counter-reset: figure;
}

p.caption:before {
    counter-increment: figure;
}

p.caption:lang(en):before {
    content: 'Figure ' counter(figure) ': ';
}

p.caption:lang(nl):before {
    content: 'Figuur ' counter(figure) ': ';
}
</code>```

Body:
I would like to add captions such as "Figure 1: Blah Blah" to my images in Pandoc and be able to refer to them like see @Figure1. I am using gpp (a pre-processor) to add captions to my images and do all sorts of fancy things like change size, format etc. However, I am unable to implement a counter for images like Figure1, Figure2, etc.

I have defined the following function in my gpp script:

\define{\counter}{0}

\defeval{count}{\eval{\counter+ 1}

and I call it like this in my script: \count

However, \counter doesnt get evaluated in my gpp script and I see the following error: unfinished macro

How should I implement this counter? I am using -T (tex) mode in gpp

Body:
Multilingual CSS numbering without cross-referencing

Here is a simple method for automatic CSS numbering with labels dependent on the document language. This simple CSS method does not allow for referencing.

For automatic numbering with referencing, rather use pandoc-fignos of the pandoc-xnos suite.

body {
    counter-reset: figure;
}

p.caption:before {
    counter-increment: figure;
}

p.caption:lang(en):before {
    content: 'Figure ' counter(figure) ': ';
}

p.caption:lang(nl):before {
    content: 'Figuur ' counter(figure) ': ';
}


问:
How to avoid using random_id for Managed Instance Group creation in GCP
Please help me to understand if I may avoid "random_id" using for Managed Instance group creation in GCP.
I know it is possible for the Unmanaged instance group where I can specify the exact names for instances.
But for MIG I always have some suffix with random_id

答:
Stateful Managed Instance Groups support assigning names to each instance.

gcloud compute instance-groups managed create-instance instance-group-name \
    --instance managed-instance-name \
    [--region region | --zone zone]

You can find more examples here.


问:
Any visual studio 2010 extension for auto concatenation on new line?
i have this question about visual studio 2010... in mono develop, when i have a string like this:

```<code>string s = "hello, how are you";
</code>```

and if i press enter key on the beginning of the "how...", the code changes automatically to this:

```<code>string s = "hello, " +
"how are you?";
</code>```

Is some extension in visual studio 2010 for this auto concatenation on a new string line?

Thanks!

答:
Are you expecting any escape sequences in your string? If not, you can just use a Verbatim String Literal:

```<code>string s = @"Hello,
how are you?";
</code>```

Then you have no need for a VS extension.

Obviously, this will only work if you are not concerned with the additional whitespace which will get added. If you need to just split the lines in code, but have them on one line in the resulting application, this will not work.

Body:
i have this question about visual studio 2010... in mono develop, when i have a string like this:

string s = "hello, how are you";

and if i press enter key on the beginning of the "how...", the code changes automatically to this:

string s = "hello, " +
"how are you?";

Is some extension in visual studio 2010 for this auto concatenation on a new string line?

Thanks!

Body:
Are you expecting any escape sequences in your string? If not, you can just use a Verbatim String Literal:

string s = @"Hello,
how are you?";

Then you have no need for a VS extension.

Obviously, this will only work if you are not concerned with the additional whitespace which will get added. If you need to just split the lines in code, but have them on one line in the resulting application, this will not work.


问:
Spring Query with optional nulls and case insensitive
I'm using Spring Boot 2.2.5.RELEASE with Java 8 and PostgreSQL and I need to retrieve some data from a table. To do that I can receive some optional values and they need to be case sensitive (mostly because some of them are Hex Strings). To handle that I'm using a CRUD repository with a query like the example bellow:

```<code>@Repository
public interface MyRepository extends CrudRepository<MyStuff, String> {

    @Query("SELECT s FROM Stuff s WHERE (:name is null or upper(s.name) = upper(:name)) "
            + "and (:age is null or upper(s.age) = upper(:age)) "
            + "and (:status is null or upper(s.status) = upper(:status))")
    List<MyStuff> findStuff(@Param("name") String name,
                            @Param("age") String age,
                            @Param("status") String status);
</code>```

I've removed some information to make it clear, but the gist of it is there. The problem is, only one field must have a value, the others can be null. It should be simple enough, because I'm checking for null before casting the fields to upper case, but when I try to run it I get an error because the null values are being interpreted as bytea and so there is no method to change its case.
How can I handle it without having a method in java to check for nulls and change to upper case on Java side?

答: I wouldn't recommend that you do that. A DBMS will use a pretty conservative query plan when encountering something like that. You should use Spring-Data Specifications for conditional filters like this.</p>

Body:
I'm using Spring Boot 2.2.5.RELEASE with Java 8 and PostgreSQL and I need to retrieve some data from a table. To do that I can receive some optional values and they need to be case sensitive (mostly because some of them are Hex Strings). To handle that I'm using a CRUD repository with a query like the example bellow:

@Repository
public interface MyRepository extends CrudRepository<MyStuff, String> {

    @Query("SELECT s FROM Stuff s WHERE (:name is null or upper(s.name) = upper(:name)) "
            + "and (:age is null or upper(s.age) = upper(:age)) "
            + "and (:status is null or upper(s.status) = upper(:status))")
    List<MyStuff> findStuff(@Param("name") String name,
                            @Param("age") String age,
                            @Param("status") String status);

I've removed some information to make it clear, but the gist of it is there. The problem is, only one field must have a value, the others can be null. It should be simple enough, because I'm checking for null before casting the fields to upper case, but when I try to run it I get an error because the null values are being interpreted as bytea and so there is no method to change its case.
How can I handle it without having a method in java to check for nulls and change to upper case on Java side?


问:
How to insert a string to a text field programatically in JavaScript
I would like to add a string of text to a text field using JavaScript but I don't want to use the onClick or onLoad events to do so.

I simply want the JavaScript to be executed as soon as the browser reads it and the JavaScript will be within the body of the html.

The text field is something like:

```<code><form action="" method="post" name="formname" id="user-registration-form">
    <input type="text" name="edit-form" id="edit-form" />
</form>
</code>```

I have tried something like this but it doesn't work:

```<code><script type="text/javascript"> edit-form.value="the new value"; </script>
</code>```

How can I do this?

答:
```
<script type="text/javascript">
document.formname.edit-mail.value="the new value";
</script>
```

Body:
I would like to add a string of text to a text field using JavaScript but I don't want to use the onClick or onLoad events to do so.

I simply want the JavaScript to be executed as soon as the browser reads it and the JavaScript will be within the body of the html.

The text field is something like:

<form action="" method="post" name="formname" id="user-registration-form">
    <input type="text" name="edit-form" id="edit-form" />
</form>

I have tried something like this but it doesn't work:

How can I do this?


问:
Delete all versions of an object in S3 using python?
I have a versioned bucket and would like to delete the object (and all of its versions) from the bucket. However, when I try to delete the object from the console, S3 simply adds a delete marker but does not perform a hard delete.

Is it possible to delete all versions of the object (hard delete) with a particular key?:

```<code>s3resource = boto3.resource('s3')
bucket = s3resource.Bucket('my_bucket')
obj = bucket.Object('my_object_key')

# I would like to delete all versions for the object like so:
obj.delete_all_versions()

# or delete all versions for all objects like so:
bucket.objects.delete_all_versions()
</code>```

答:
this script will delete all version of all object with prefix - </p>

```<code>s3 = boto3.resource("s3")
client = boto3.client("s3")
s3_bucket = s3.Bucket(bucket_name)
for obj in s3_bucket.objects.filter(Prefix=""):

    response = client.list_object_versions(Bucket=bucket_name, Prefix=obj.key)

    while "Versions" in response:
        to_delete = [
            {"Key": ver["Key"], "VersionId": ver["VersionId"]}
            for ver in response["Versions"]
        ]

        delete = {"Objects": to_delete}

        client.delete_objects(Bucket=bucket_name, Delete=delete)
        response = client.list_object_versions(Bucket=bucket_name, Prefix=obj.key)

    client.delete_object(Bucket=bucket_name, Key=obj.key)
</code>```

Body:
I have a versioned bucket and would like to delete the object (and all of its versions) from the bucket. However, when I try to delete the object from the console, S3 simply adds a delete marker but does not perform a hard delete.

Is it possible to delete all versions of the object (hard delete) with a particular key?:

s3resource = boto3.resource('s3')
bucket = s3resource.Bucket('my_bucket')
obj = bucket.Object('my_object_key')

# I would like to delete all versions for the object like so:
obj.delete_all_versions()

# or delete all versions for all objects like so:
bucket.objects.delete_all_versions()

Body:
this script will delete all version of all object with prefix -

s3 = boto3.resource("s3")
client = boto3.client("s3")
s3_bucket = s3.Bucket(bucket_name)
for obj in s3_bucket.objects.filter(Prefix=""):

    response = client.list_object_versions(Bucket=bucket_name, Prefix=obj.key)

    while "Versions" in response:
        to_delete = [
            {"Key": ver["Key"], "VersionId": ver["VersionId"]}
            for ver in response["Versions"]
        ]

        delete = {"Objects": to_delete}

        client.delete_objects(Bucket=bucket_name, Delete=delete)
        response = client.list_object_versions(Bucket=bucket_name, Prefix=obj.key)

    client.delete_object(Bucket=bucket_name, Key=obj.key)


问:
dropdown is populating empty list in laravel 6
Laravel Version 6. PHP 7.4.

I simply wants to populate my dropdown values form database table. Initially, It was returning error "variable undefined" but when I enclosed my code into if condition, my error was gone but drop-down list is empty.

Please suggest where I' m stuck.

Route.php

```<code>Route::get('products/qrcodes/basic','niceActionController@getMake');
</code>```

Controller

```<code><?php

namespace App\Http\Controllers;
use \Illuminate\Http\Request;
use App\NiceAction;
use App\NiceActionLogged;

public function getMake()
{
$records = DB::table('users')->get();
return view('products.qrcodes.basic', ['records' => $records]);
}
</code>```

View

```<code><form>
   <select  required>
     @if ((empty($records)))
        Whoops! Something went wrong
     @else
     @foreach ($records as $item)
     <option value="{{ $item->id }}">{{ $item->name }}</option>
     @endforeach
     @endif
   </select>
</form>
</code>```

I also tried "dd($records);" but nothing happens.

答:
First Make sure that your table have data.
And then change your controller and view like this.

Controller Code

```<code><?php

   namespace App\Http\Controllers;

   use DB;
   use \Illuminate\Http\Request;
   use App\NiceAction;
   use App\NiceActionLogged;

   public function getMake() {
       $records = DB::table('users')->get()->toArray();
       return view('products.qrcodes.basic', compact('records'));
   }
</code>```

View Code:

```<code><form>
    <select required>
        @if(empty($records))
            Whoops! Something went wrong
        @else
            @foreach ($records as $key => $item)
                <option value="{{ $item['id'] }}">{{ $item['name'] }}</option>
            @endforeach
        @endif
    </select>
</form>
</code>```

I hope it will help you :)

Body:
Laravel Version 6. PHP 7.4.

I simply wants to populate my dropdown values form database table. Initially, It was returning error "variable undefined" but when I enclosed my code into if condition, my error was gone but drop-down list is empty.

Please suggest where I' m stuck.

Route.php

Route::get('products/qrcodes/basic','niceActionController@getMake');

Controller

<?php

namespace App\Http\Controllers;
use \Illuminate\Http\Request;
use App\NiceAction;
use App\NiceActionLogged;

public function getMake()
{
$records = DB::table('users')->get();
return view('products.qrcodes.basic', ['records' => $records]);
}

View

<form>
   <select  required>
     @if ((empty($records)))
        Whoops! Something went wrong
     @else
     @foreach ($records as $item)
     <option value="{{ $item->id }}">{{ $item->name }}</option>
     @endforeach
     @endif
   </select>
</form>

I also tried "dd($records);" but nothing happens.

Body:
First Make sure that your table have data.
And then change your controller and view like this.

Controller Code

<?php

   namespace App\Http\Controllers;

   use DB;
   use \Illuminate\Http\Request;
   use App\NiceAction;
   use App\NiceActionLogged;

   public function getMake() {
       $records = DB::table('users')->get()->toArray();
       return view('products.qrcodes.basic', compact('records'));
   }

View Code:

<form>
    <select required>
        @if(empty($records))
            Whoops! Something went wrong
        @else
            @foreach ($records as $key => $item)
                <option value="{{ $item['id'] }}">{{ $item['name'] }}</option>
            @endforeach
        @endif
    </select>
</form>

I hope it will help you :)


问:
I need to pass username and password to typeORM on runtime
On NodeJS (NestJS) I used TypeORM to connect to Database (Oracle). I would like to pass the username and password during runtime of the application.

Due to security reasons, in my company, the security is configured in away that for each user, we create a database schema. He log into The application using his DB credential. I know I t is not very popular practice in the industry.

```<code>const connection = await createConnection({
    type: "oracle",
    host: "localhost",
    port: 3306,
    username: "test", // this need to pass during run time
    password: "test", // same thing for the password
    database: "test"
});
</code>```

Could you please share with me any reference/ hints on how to achieve this on typeORM and nodeJs/NestJs?

Thanks

答:
You can use register TypeORM in the root level, and use a configuration service to provide the connection details:

```<code>    TypeOrmModule.forRootAsync({
        imports: [ConfigModule],
        useFactory: (config: ConfigService) => ({
            host: config.get('DB_HOST'),
            username: config.get('DB_USER'),
            password: config.get('DB_PASSWORD'),
            database: config.get('DB_NAME'),
            entities: [__dirname + '/**/*.entity{.ts,.js}'],
            port: 3306,
            type: 'oracle',
        }),
        inject: [ConfigService],
    }),
</code>```

ConfigService is just a simple service that implements a get function that provides the specific requested configuration.

More on that here: https://docs.nestjs.com/techniques/database#async-configuration

Body:
On NodeJS (NestJS) I used TypeORM to connect to Database (Oracle). I would like to pass the username and password during runtime of the application.

Due to security reasons, in my company, the security is configured in away that for each user, we create a database schema. He log into The application using his DB credential. I know I t is not very popular practice in the industry.

const connection = await createConnection({
    type: "oracle",
    host: "localhost",
    port: 3306,
    username: "test", // this need to pass during run time
    password: "test", // same thing for the password
    database: "test"
});

Could you please share with me any reference/ hints on how to achieve this on typeORM and nodeJs/NestJs?

Thanks

Body:
You can use register TypeORM in the root level, and use a configuration service to provide the connection details:

    TypeOrmModule.forRootAsync({
        imports: [ConfigModule],
        useFactory: (config: ConfigService) => ({
            host: config.get('DB_HOST'),
            username: config.get('DB_USER'),
            password: config.get('DB_PASSWORD'),
            database: config.get('DB_NAME'),
            entities: [__dirname + '/**/*.entity{.ts,.js}'],
            port: 3306,
            type: 'oracle',
        }),
        inject: [ConfigService],
    }),

ConfigService is just a simple service that implements a get function that provides the specific requested configuration.

More on that here: https://docs.nestjs.com/techniques/database#async-configuration


问:
How can I draw a grid of squares?
My current code only draws 1 row of squares, however I want to draw a whole grid of squares? How do I do this?</p>

```<code>from turtle import*

bob=Turtle()
def square():
    x = 0
    y=0
    for i in range(4):
        bob.forward(50)
        bob.left(90)
        bob.forward(50)
        bob.left(90)
        bob.forward(50)
        bob.left(90)
        bob.forward(50)
        bob.left(90)
        bob.goto(50+x,0)
        x+=50
    bob.goto(0,-50)
    bob.right(90)
square()
square()
square()
input()
</code>```

答:
Result Image</p>

```<code>import turtle as t

t.tracer(0, 0)
t.speed(0)

grid={
    'left':-500,
    'right':500,
    'top':-500,
    'bottom':500,
    'interval':10
    }

x_positions=range(grid['left'],grid['right'],grid['interval'])
y_positions=range(grid['top'],grid['bottom'],grid['interval'])

for x in x_positions:
    t.penup()
    t.setpos(x,grid['top'])
    t.pendown()
    t.setpos(x,grid['bottom'])

for y in y_positions:
    t.penup()
    t.setpos(grid['left'],y)
    t.pendown()
    t.setpos(grid['right'],y)

t.update()
</code>```

Title: How can I draw a grid of squares?

Body:
My current code only draws 1 row of squares, however I want to draw a whole grid of squares? How do I do this?

from turtle import*

bob=Turtle()
def square():
    x = 0
    y=0
    for i in range(4):
        bob.forward(50)
        bob.left(90)
        bob.forward(50)
        bob.left(90)
        bob.forward(50)
        bob.left(90)
        bob.forward(50)
        bob.left(90)
        bob.goto(50+x,0)
        x+=50
    bob.goto(0,-50)
    bob.right(90)
square()
square()
square()
input()

Body:
Result Image

import turtle as t

t.tracer(0, 0)
t.speed(0)

grid={
    'left':-500,
    'right':500,
    'top':-500,
    'bottom':500,
    'interval':10
    }

x_positions=range(grid['left'],grid['right'],grid['interval'])
y_positions=range(grid['top'],grid['bottom'],grid['interval'])

for x in x_positions:
    t.penup()
    t.setpos(x,grid['top'])
    t.pendown()
    t.setpos(x,grid['bottom'])

for y in y_positions:
    t.penup()
    t.setpos(grid['left'],y)
    t.pendown()
    t.setpos(grid['right'],y)

t.update()


问:
How do I print subscribed dictinary value in RxSwift?
I have an Observable that returns a dictionary:

```<code>func myFunc() -> Observable<[String : MyClass]> {
    return service.getDictionary()
}
</code>```

How do I get ahold of the keys and values?

```<code>viewModel.myFunc().subscribe(onNext: {
    print("", $0 )
}).disposed(by: disposeBag)
</code>```

There's no property like .key or .value. Do I use map or flatMap or how does it work?

答:
RxSwift 5.0 Tested

```<code>    func myFunc() -> Observable<[String : String]> {
        let dict:[String:String] = ["key0": "value0", "key1": "value1", "key2": "value2","key3" : "value3"]
        return Observable.just(dict)
    }

    myFunc()
    .map { (dict) -> [(String,String)] in
            let keys = Array(dict.keys)
            var key_value_array = Array<(String,String)>()
            for key in keys {
                let key_value_tuple = (key,dict[key]!)
                key_value_array.append(key_value_tuple)
            }

        return key_value_array
    }.flatMap { Observable.from($0) }
        .subscribe(onNext: { (tuple) in
        print("Key is \(tuple.0)")
        print("Value is \(tuple.1)")
    }).disposed(by: disposeBag)
</code>```

Then log in console is

```<code>Key is key0
Value is value0
Key is key1
Value is value1
Key is key3
Value is value3
Key is key2
Value is value2
</code>```

Body:
I have an Observable that returns a dictionary:

func myFunc() -> Observable<[String : MyClass]> {
    return service.getDictionary()
}

How do I get ahold of the keys and values?

viewModel.myFunc().subscribe(onNext: {
    print("", $0 )
}).disposed(by: disposeBag)

There's no property like .key or .value. Do I use map or flatMap or how does it work?

Body:
RxSwift 5.0 Tested

    func myFunc() -> Observable<[String : String]> {
        let dict:[String:String] = ["key0": "value0", "key1": "value1", "key2": "value2","key3" : "value3"]
        return Observable.just(dict)
    }

    myFunc()
    .map { (dict) -> [(String,String)] in
            let keys = Array(dict.keys)
            var key_value_array = Array<(String,String)>()
            for key in keys {
                let key_value_tuple = (key,dict[key]!)
                key_value_array.append(key_value_tuple)
            }

        return key_value_array
    }.flatMap { Observable.from($0) }
        .subscribe(onNext: { (tuple) in
        print("Key is \(tuple.0)")
        print("Value is \(tuple.1)")
    }).disposed(by: disposeBag)

Then log in console is

Key is key0
Value is value0
Key is key1
Value is value1
Key is key3
Value is value3
Key is key2
Value is value2


问:
How do I do strikethrough (line-through) in asciidoc?
How do I render a strikethrough (or line-through) in an adoc file?

Let's  presume I want to write "That technology is -c-r-a-p- not perfect."

答:
If you're only targeting the HTML backend, you can insert HTML code verbatim via a passthrough context. This can be done inline by wrapping the parts in +++:

```<code>That technology is +++<del>+++crap+++</del>+++ not perfect.
</code>```

This won't help you for PDF, DocBook XML, or other output formats, though.

Body:
If you're only targeting the HTML backend, you can insert HTML code verbatim via a passthrough context. This can be done inline by wrapping the parts in +++:

That technology is +++<del>+++crap+++</del>+++ not perfect.

This won't help you for PDF, DocBook XML, or other output formats, though.


问:
Subquery with multiple sorted results
Struggling on a most probably very simple query for MS Access, but couldn't nail it for 3 days already.

Any help would be highly appreciated..

There are 2 tables - Regions (REGNAME) and Cities (REGNAME, NAME, POPULATION)

I need to get the top 10 cities sorted by the population in descending order for each region.

There's no problem to do this for some certain Region:

```<code>SELECT TOP 10 Cities.REGNAME, NAME from Cities, Regions
WHERE Cities.REGNAME = Regions.REGNAME
AND Regions.REGNAME = 'SOME_REGION_NAME'
ORDER BY POPULATION DESC
</code>```

But I need to see the similar list of Cities for any number of Regions.
For every region in subquery I should see sorded 10 cities' list.

Like below:

```<code>SOME_REGION_NAME - CITY 1
SOME_REGION_NAME - CITY 2
SOME_REGION_NAME - ..
SOME_REGION_NAME - CITY 10

ANOTHER_REGION_NAME - CITY 1
ANOTHER_REGION_NAME - CITY 2
ANOTHER_REGION_NAME - ..
ANOTHER_REGION_NAME - CITY 10

SOME_OTHER_REGION_NAME - CITY 1
SOME_OTHER_REGION_NAME - CITY 2
SOME_OTHER_REGION_NAME - ..
SOME_OTHER_REGION_NAME - CITY 10
</code>```

This query gives 10 cities in total from 3 regions:

```<code>SELECT TOP 10 Cities.REGNAME, NAME from Cities, Regions
WHERE Cities.REGNAME = Regions.REGNAME
AND Regions.REGNAME IN ('SOME_REGION_NAME' , 'ANOTHER_REGION_NAME', 'SOME_OTHER_REGION_NAME')
ORDER BY POPULATION DESC
</code>```

But I expect to see a 30 cities table, not 10.

Please, someone, show me the way :)

Thank you

答:
In MS Access, this is often handled using IN with a correlated subquery:

```<code>SELECT TOP 10 ci.REGNAME, ci.NAME
FROM Cities as ci
WHERE ci.NAME IN (SELECT TOP 10 ci2.Name
                  FROM Cities as ci2
                  ORDER BY ci.POPULATION DESC
                 )
ORDER BY ci.REGNAME, ci.POPULATION DESC;
</code>```

Notice that this does not require the Regions table.

Title: Subquery with multiple sorted results

Body:
Struggling on a most probably very simple query for MS Access, but couldn't nail it for 3 days already.

Any help would be highly appreciated..

There are 2 tables - Regions (REGNAME) and Cities (REGNAME, NAME, POPULATION)

I need to get the top 10 cities sorted by the population in descending order for each region.

There's no problem to do this for some certain Region:

SELECT TOP 10 Cities.REGNAME, NAME from Cities, Regions
WHERE Cities.REGNAME = Regions.REGNAME
AND Regions.REGNAME = 'SOME_REGION_NAME'
ORDER BY POPULATION DESC

But I need to see the similar list of Cities for any number of Regions.
For every region in subquery I should see sorded 10 cities' list.

Like below:

SOME_REGION_NAME - CITY 1
SOME_REGION_NAME - CITY 2
SOME_REGION_NAME - ..
SOME_REGION_NAME - CITY 10

ANOTHER_REGION_NAME - CITY 1
ANOTHER_REGION_NAME - CITY 2
ANOTHER_REGION_NAME - ..
ANOTHER_REGION_NAME - CITY 10

SOME_OTHER_REGION_NAME - CITY 1
SOME_OTHER_REGION_NAME - CITY 2
SOME_OTHER_REGION_NAME - ..
SOME_OTHER_REGION_NAME - CITY 10

This query gives 10 cities in total from 3 regions:

SELECT TOP 10 Cities.REGNAME, NAME from Cities, Regions
WHERE Cities.REGNAME = Regions.REGNAME
AND Regions.REGNAME IN ('SOME_REGION_NAME' , 'ANOTHER_REGION_NAME', 'SOME_OTHER_REGION_NAME')
ORDER BY POPULATION DESC

But I expect to see a 30 cities table, not 10.

Please, someone, show me the way :)

Thank you

Body:
In MS Access, this is often handled using IN with a correlated subquery:

SELECT TOP 10 ci.REGNAME, ci.NAME
FROM Cities as ci
WHERE ci.NAME IN (SELECT TOP 10 ci2.Name
                  FROM Cities as ci2
                  ORDER BY ci.POPULATION DESC
                 )
ORDER BY ci.REGNAME, ci.POPULATION DESC;

Notice that this does not require the Regions table.


问:
fsockopen returns 'bool(false)' from browser but 'resource(4) of type (stream)' from command line
I cannot send mail in sugarcrm. Suagrcrm sends mail with phpmailer using SMTP. I have identified that the error occurs when an attempt to open a socket connection using fsockopen is made. The call to fsockopen returns boolean (false).

The arguments given to fsockopen are 5 variables containing the following values
'mail.example.com'(hostname), 25(port), ''(errno), ''(errstr), 10(timeout)

The error message is

Code: 10107 Reply: A system call that should never fail has failed.

The error code is present in microsoft website under 'Windows Sockets Error Codes' and is partly explained as:

Returned when a provider does not return SUCCESS and does not provide an extended error code. Can indicate a service provider implementation error.

The issue occurs when I call the script from a broswer. If I execute the script from command line, fsockopen returns a resource.

Program Info:

Windows XP

Apache/2.0.63 (Win32) mod_ssl/2.0.63 OpenSSL/0.9.8i PHP/5.2.8 Server

PHP Version => 5.2.8

Can anyone suggest any possible solutions for this issue. Thanks in advance for any suggestion.

答: The error was caused due to the presence of a firewall in the system used as the web server. It worked fine when I uninstalled the firewall.</p>

ContentLicense: CC BY-SA 2.5


问:
How to nest Less class to inherit parent styles?
LESS code:

```<code>.btn-default:hover {
    background-color: rgba(217, 217, 217, 0.65);
    background-clip: content-box;

    .btn-default:focus {
        outline: 2px solid #047a9c;
    }
}
</code>```

What i want to do here is that btn-default:focus should have background color of hover state but only focus state should have the outline. so the output CSS should be:

```<code> .btn-default:hover {
     background-color: rgba(217, 217, 217, 0.65);
     background-clip: content-box;
 }

 .btn-default:focus {
     background-color: rgba(217, 217, 217, 0.65);
     background-clip: content-box;
     outline: 2px solid #047a9c;
 }
</code>```

I am bit lost at the LESS nesting part, is this something possible with less? So that i don't have to duplicate the code.

答:
You will have to nest pseudo-classes only into main selector. In this case .btn-default.

This is how it should look:

```<code>.btn-default {
  /* some code here */

  &:hover, &:focus {
    background-color: rgba(217, 217, 217, 0.65);
    background-clip: content-box;
  }

  &:focus {
    outline: 2px solid #047a9c;
  }
}
</code>```

The & character has the function of a "this" keyword

From your original question:

```<code>.btn-default:hover {
  background-color: rgba(217, 217, 217, 0.65);
  background-clip: content-box;

  .btn-default:focus {
    outline: 2px solid #047a9c;
  }
}
</code>```

Less doesn't work this way. Try to pronounce your code. Your code would be like this in CSS:

```<code>.btn-default:hover {
  background-color: rgba(217, 217, 217, 0.65);
  background-clip: content-box;
}

.btn-default:hover.btn-default:focus {
    outline: 2px solid #047a9c;
}
</code>```

You have to nest pseudo-classes and pseudo-elements into main selector (.btn-default)

If you want more selectors, pseudo-elements or pseudo-classes to have same properties, you should use ,, not to nest one inside another.

Here are some helpful links:

Less to CSS compiler

LESS CSS nesting classes

Pseudo classes

Body:
LESS code:

.btn-default:hover {
    background-color: rgba(217, 217, 217, 0.65);
    background-clip: content-box;

    .btn-default:focus {
        outline: 2px solid #047a9c;
    }
}

What i want to do here is that btn-default:focus should have background color of hover state but only focus state should have the outline. so the output CSS should be:

 .btn-default:hover {
     background-color: rgba(217, 217, 217, 0.65);
     background-clip: content-box;
 }

 .btn-default:focus {
     background-color: rgba(217, 217, 217, 0.65);
     background-clip: content-box;
     outline: 2px solid #047a9c;
 }

I am bit lost at the LESS nesting part, is this something possible with less? So that i don't have to duplicate the code.

Body:
You will have to nest pseudo-classes only into main selector. In this case .btn-default.

This is how it should look:

.btn-default {
  /* some code here */

  &:hover, &:focus {
    background-color: rgba(217, 217, 217, 0.65);
    background-clip: content-box;
  }

  &:focus {
    outline: 2px solid #047a9c;
  }
}

The & character has the function of a "this" keyword

From your original question:

.btn-default:hover {
  background-color: rgba(217, 217, 217, 0.65);
  background-clip: content-box;

  .btn-default:focus {
    outline: 2px solid #047a9c;
  }
}

Less doesn't work this way. Try to pronounce your code. Your code would be like this in CSS:

.btn-default:hover {
  background-color: rgba(217, 217, 217, 0.65);
  background-clip: content-box;
}

.btn-default:hover.btn-default:focus {
    outline: 2px solid #047a9c;
}

You have to nest pseudo-classes and pseudo-elements into main selector (.btn-default)

If you want more selectors, pseudo-elements or pseudo-classes to have same properties, you should use ,, not to nest one inside another.

Here are some helpful links:

Less to CSS compiler

LESS CSS nesting classes

Pseudo classes


问:
Rails 6 Drag and Drop ( Sortable )
I have problem with my HTML sortable update in rails 6. I drag and drop some portfolio images through web page and that is working good but when i want to update the web page with updated position i got NoMethodError (undefined method `each' for nil:NilClass):

I use this script for HTML Sortable

https://github.com/jordanhudgens/devcamp-portfolio/blob/master/app/assets/javascripts/html.sortable.js

portfolio_controller:

```<code>class PortfoliosController < ApplicationController
    before_action :set_portfolio_item, only: [:edit, :show,:update, :destroy]
    layout "portfolio"
    access all: [:show, :index, :angular], user: {except: [:destroy, :new, :create, :update, :edit]}, site_admin: :all

    def index
        @portfolio_items = Portfolio.by_position
    end

    def sort
        params[:order].each do |key, value|
          Portfolio.find(value[:id]).update(position: value[:position])
        end

        head :ok
    end

    def angular
        @angular_portfolio_items = Portfolio.angular
    end

    def new
        @portfolio_item = Portfolio.new
        3.times { @portfolio_item.technologies.build }
    end

    def create
        @portfolio_item = Portfolio.new(portfolio_params)
            respond_to do |format|
            if @portfolio_item.save
              format.html { redirect_to portfolios_path, notice: 'Your Portfolio item is now live.' }
            else
              format.html { render :new }
            end
        end
    end

    def edit
    end

    def update
        respond_to do |format|
            if @portfolio_item.update(portfolio_params)
                format.html { redirect_to portfolios_path, notice: 'The Record successfully updated.' }
            else
                format.html { render :edit }
            end
        end
    end

    def show
    end

    def destroy
        #Destroy/delete the record
        @portfolio_item.destroy

        #Redirect
        respond_to do |format|
          format.html { redirect_to portfolios_url, notice: 'Record was removed' }
        end
    end

    private

    def set_portfolio_item
        @portfolio_item = Portfolio.find(params[:id])
    end

    def portfolio_params
        params.require(:portfolio).permit(:title,
                                          :subtitle,
                                          :body,
                                          technologies_attributes: [:name]
                                        )
    end
end
</code>```

routes.rb:

```<code>Rails.application.routes.draw do
  devise_for :users, path: '', path_names: { sign_in: 'login', sign_out: 'logout', sign_up: 'register'}
  resources :portfolios, except: [:show] do
    put :sort, on: :collection
  end
  get 'angular-items', to: 'portfolios#angular'
  get 'portfolio/:id', to: 'portfolios#show', as: 'portfolio_show'

  get 'about-me', to: 'pages#about'
  get 'contact', to: 'pages#contact'
  resources :blogs do
     member do
        get :toggle_status
     end
  end

  root to: 'pages#home'
end
</code>```

Here is my portfolio.js :

```<code>var ready, set_position;

ready = void 0;

set_position = void 0;

set_position = function() {
  $(".card").each(function(i) {
    $(this).attr('data-pos', i + 1);
  });
};

ready = function() {
  set_position();
  $('#sortable').sortable();
  $('#sortable').sortable().bind('sortupdate', function(e, ui) {
    var updated_order;
    updated_order = [];
    set_position();
    $(".card").each(function(i) {
      updated_order.push;
      ({
        id: $(this).data('id'),
        position: i + 1
      });
    });
    $.ajax({
      type: 'PUT',
      url: '/portfolios/sort',
      data: {
        order: updated_order
      }
    });
  });
};

$(document).ready(ready);
</code>```

_portfolio_item.html.erb :

```<code><div class="card" data-id="<%= portfolio_item.id %>">
    <%= image_tag portfolio_item.thumb_image unless portfolio_item.thumb_image.nil? %>
    <p class="card-text">
        <span>
            <%= link_to portfolio_item.title, portfolio_show_path(portfolio_item) %>
        </span>
        <%= portfolio_item.subtitle %>
    </p>
</div>
</code>```

Thank you for your helps!

答:
The only place I see an each statement is in the sort method of your PortfoliosController.

params[:order].each
```

<p>You need to set your params[:order] or prevent this error from happening by checking if it is set. You could use the save navigation operator:</p>

<pre class="lang-rb prettyprint-override"><code>params[:order]&.each
</code>```

Or you could check if the order parameter is set with the present? method.

if params[:order].present?
  params[:order]&.each
```

Title: Rails 6 Drag and Drop ( Sortable )

Body:
I have problem with my HTML sortable update in rails 6. I drag and drop some portfolio images through web page and that is working good but when i want to update the web page with updated position i got NoMethodError (undefined method `each' for nil:NilClass):

I use this script for HTML Sortable

https://github.com/jordanhudgens/devcamp-portfolio/blob/master/app/assets/javascripts/html.sortable.js

portfolio_controller:

class PortfoliosController < ApplicationController
    before_action :set_portfolio_item, only: [:edit, :show,:update, :destroy]
    layout "portfolio"
    access all: [:show, :index, :angular], user: {except: [:destroy, :new, :create, :update, :edit]}, site_admin: :all

    def index
        @portfolio_items = Portfolio.by_position
    end

    def sort
        params[:order].each do |key, value|
          Portfolio.find(value[:id]).update(position: value[:position])
        end

        head :ok
    end

    def angular
        @angular_portfolio_items = Portfolio.angular
    end

    def new
        @portfolio_item = Portfolio.new
        3.times { @portfolio_item.technologies.build }
    end

    def create
        @portfolio_item = Portfolio.new(portfolio_params)
            respond_to do |format|
            if @portfolio_item.save
              format.html { redirect_to portfolios_path, notice: 'Your Portfolio item is now live.' }
            else
              format.html { render :new }
            end
        end
    end

    def edit
    end

    def update
        respond_to do |format|
            if @portfolio_item.update(portfolio_params)
                format.html { redirect_to portfolios_path, notice: 'The Record successfully updated.' }
            else
                format.html { render :edit }
            end
        end
    end

    def show
    end

    def destroy
        #Destroy/delete the record
        @portfolio_item.destroy

        #Redirect
        respond_to do |format|
          format.html { redirect_to portfolios_url, notice: 'Record was removed' }
        end
    end

    private

    def set_portfolio_item
        @portfolio_item = Portfolio.find(params[:id])
    end

    def portfolio_params
        params.require(:portfolio).permit(:title,
                                          :subtitle,
                                          :body,
                                          technologies_attributes: [:name]
                                        )
    end
end

routes.rb:

Rails.application.routes.draw do
  devise_for :users, path: '', path_names: { sign_in: 'login', sign_out: 'logout', sign_up: 'register'}
  resources :portfolios, except: [:show] do
    put :sort, on: :collection
  end
  get 'angular-items', to: 'portfolios#angular'
  get 'portfolio/:id', to: 'portfolios#show', as: 'portfolio_show'

  get 'about-me', to: 'pages#about'
  get 'contact', to: 'pages#contact'
  resources :blogs do
     member do
        get :toggle_status
     end
  end

  root to: 'pages#home'
end

Here is my portfolio.js :

var ready, set_position;

ready = void 0;

set_position = void 0;

set_position = function() {
  $(".card").each(function(i) {
    $(this).attr('data-pos', i + 1);
  });
};

ready = function() {
  set_position();
  $('#sortable').sortable();
  $('#sortable').sortable().bind('sortupdate', function(e, ui) {
    var updated_order;
    updated_order = [];
    set_position();
    $(".card").each(function(i) {
      updated_order.push;
      ({
        id: $(this).data('id'),
        position: i + 1
      });
    });
    $.ajax({
      type: 'PUT',
      url: '/portfolios/sort',
      data: {
        order: updated_order
      }
    });
  });
};

$(document).ready(ready);

_portfolio_item.html.erb :

<div class="card" data-id="<%= portfolio_item.id %>">
    <%= image_tag portfolio_item.thumb_image unless portfolio_item.thumb_image.nil? %>

            <%= link_to portfolio_item.title, portfolio_show_path(portfolio_item) %>

        <%= portfolio_item.subtitle %>

Thank you for your helps!

Body:
The only place I see an each statement is in the sort method of your PortfoliosController.

params[:order].each

You need to set your params[:order] or prevent this error from happening by checking if it is set. You could use the save navigation operator:

params[:order]&.each

Or you could check if the order parameter is set with the present? method.

if params[:order].present?
  params[:order]&.each


问:
Table search should wait for result
Hey guys and thanks for your attention!

Testcase: Im having a table and in this table i got a couple of settings i can search for via a search box!
I want to search for a setting name and as soon as it is found and shown as a single element in the table i want to click the "Edit" button in the last column of the table! There i can do some further changes.

Current issue: After i've entered the setting name in the search bar... cypress immediately clicks the "Edit" button for the first setting in the table. So it is not waiting for my searched setting is shown as the single element in the table!

I worked with a "wait" already... and it workd. But my boss is not happy with this solution!

So is there any other way to wait for the search to be finished?

Thanks for your help!

答:
For client-side search: you can try:

```<code>cy.get('input[type=search]').type(searchTerm).then(() => <expect_single_row>);
</code>```

For server-side search: you can listen to the 'search' request and wait for the response to update the table:

```<code>function openSpecificRow(searchTerm) {
  search(searchTerm).then(() => {
    // if searchTerm is present in the row field
    cy.contains(searchTerm).parent('tr').siblings('.menu').click();
  });
}

function search(searchTerm) {
  cy.server();
  cy.route({
    method: 'GET',
    url: `/<url_path>?*&search=${searchTerm}*`
  }).as('searchResult');

  cy.get('input[type=search]').type(searchTerm);
  return cy.wait('@searchResult');
}
</code>```

Note: Format the route url exactly the way it will be formed when search request will be triggered.

Title: Table search should wait for result

Body:
For client-side search: you can try:

cy.get('input[type=search]').type(searchTerm).then(() => <expect_single_row>);

For server-side search: you can listen to the 'search' request and wait for the response to update the table:

function openSpecificRow(searchTerm) {
  search(searchTerm).then(() => {
    // if searchTerm is present in the row field
    cy.contains(searchTerm).parent('tr').siblings('.menu').click();
  });
}

function search(searchTerm) {
  cy.server();
  cy.route({
    method: 'GET',
    url: `/<url_path>?*&search=${searchTerm}*`
  }).as('searchResult');

  cy.get('input[type=search]').type(searchTerm);
  return cy.wait('@searchResult');
}

Note: Format the route url exactly the way it will be formed when search request will be triggered.


问:
What to do in Error in React Installation
I'm trying to install react but I'm encountering an error while doing npm start.
I have tried many solutions regarding changing babel versions but still not able to fully fix it.

Error:

```<code>C:\Users\support\Desktop\reactApp>npm start

> reactapp@1.0.0 start C:\Users\support\Desktop\reactApp
> webpack-dev-server --mode development --open --hot

i ｢wds｣: Project is running at http://localhost:8001/
i ｢wds｣: webpack output is served from /
i ｢wds｣: Content not from webpack is served from C:\Users\support\Desktop\reactApp
i ｢wdm｣: wait until bundle finished: /
× ｢wdm｣: Hash: 8012f13b5074e55019d9
Version: webpack 4.43.0
Time: 645ms
Built at: 06/02/2020 2:29:04 PM
          Asset       Size  Chunks             Chunk Names
     index.html  272 bytes          [emitted]
index_bundle.js    395 KiB    main  [emitted]  main
Entrypoint main = index_bundle.js
[0] multi (webpack)-dev-server/client?http://localhost:8001 (webpack)/hot/dev-server.js ./main.js 52 bytes {main} [built]
[./main.js] 1.37 KiB {main} [built] [failed] [1 error]
[./node_modules/webpack-dev-server/client/index.js?http://localhost:8001] (webpack)-dev-server/client?http://localhost:8001 4.29 KiB {main} [built]
[./node_modules/webpack-dev-server/client/overlay.js] (webpack)-dev-server/client/overlay.js 3.51 KiB {main} [built]
[./node_modules/webpack-dev-server/client/socket.js] (webpack)-dev-server/client/socket.js 1.53 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/createSocketUrl.js] (webpack)-dev-server/client/utils/createSocketUrl.js 2.91 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/log.js] (webpack)-dev-server/client/utils/log.js 964 bytes {main} [built]
[./node_modules/webpack-dev-server/client/utils/reloadApp.js] (webpack)-dev-server/client/utils/reloadApp.js 1.59 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/sendMessage.js] (webpack)-dev-server/client/utils/sendMessage.js 402 bytes {main} [built]
[./node_modules/webpack-dev-server/node_modules/strip-ansi/index.js] (webpack)-dev-server/node_modules/strip-ansi/index.js 161 bytes {main} [built]
[./node_modules/webpack/hot sync ^\.\/log$] (webpack)/hot sync nonrecursive ^\.\/log$ 170 bytes {main} [built]
[./node_modules/webpack/hot/dev-server.js] (webpack)/hot/dev-server.js 1.59 KiB {main} [built]
[./node_modules/webpack/hot/emitter.js] (webpack)/hot/emitter.js 75 bytes {main} [built]
[./node_modules/webpack/hot/log-apply-result.js] (webpack)/hot/log-apply-result.js 1.27 KiB {main} [built]
[./node_modules/webpack/hot/log.js] (webpack)/hot/log.js 1.34 KiB {main} [built]
    + 20 hidden modules

ERROR in ./main.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module 'babel-preset-env' from 'C:\Users\support\Desktop\reactApp'
- Did you mean "@babel/env"?
    at Function.resolveSync [as sync] (C:\Users\support\Desktop\reactApp\node_modules\resolve\lib\sync.js:89:15)
    at resolveStandardizedName (C:\Users\support\Desktop\reactApp\node_modules\@babel\core\lib\config\files\plugins.js:101:31)
    at resolvePreset (C:\Users\support\Desktop\reactApp\node_modules\@babel\core\lib\config\files\plugins.js:58:10)
    at loadPreset (C:\Users\support\Desktop\reactApp\node_modules\@babel\core\lib\config\files\plugins.js:77:20)
    at createDescriptor (C:\Users\support\Desktop\reactApp\node_modules\@babel\core\lib\config\config-descriptors.js:154:9)
    at C:\Users\support\Desktop\reactApp\node_modules\@babel\core\lib\config\config-descriptors.js:109:50
    at Array.map (<anonymous>)
    at createDescriptors (C:\Users\support\Desktop\reactApp\node_modules\@babel\core\lib\config\config-descriptors.js:109:29)
    at createPresetDescriptors (C:\Users\support\Desktop\reactApp\node_modules\@babel\core\lib\config\config-descriptors.js:101:10)
    at C:\Users\support\Desktop\reactApp\node_modules\@babel\core\lib\config\config-descriptors.js:58:104
Child HtmlWebpackCompiler:
     1 asset
    Entrypoint HtmlWebpackPlugin_0 = __child-HtmlWebpackPlugin_0
    [./node_modules/html-webpack-plugin/lib/loader.js!./index.html] 501 bytes {HtmlWebpackPlugin_0} [built]
i ｢wdm｣: Failed to compile.
</code>```

These are my following files

webpack.comfig.js

```<code>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
   entry: './main.js',
   output: {
      path: path.join(__dirname, '/bundle'),
      filename: 'index_bundle.js'
   },
   devServer: {
      inline: true,
      port: 8001
   },
   module: {
      rules: [
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
               presets: ['env', 'react']
            }
         }
      ]
   },
   plugins:[
      new HtmlWebpackPlugin({
         template: './index.html'
      })
   ]
}
</code>```

package.json

```<code>{
  "name": "reactapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --mode development --open --hot",
    "build": "webpack --mode production"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.11.0"
  },
  "devDependencies": {
    "@babel/core": "^7.10.2",
    "@babel/preset-env": "^7.10.2",
    "@babel/preset-react": "^7.10.1",
    "babel-loader": "^8.1.0",
    "html-webpack-plugin": "^4.3.0"
  }
}
</code>```

.babelrc

```<code>{
    "presets": [
        "@babel/preset-env",
        "@babel/preset-react"
    ]
}
</code>```

答:
You are using babel preset 7+

Do this in your webpack.config.js

```<code>presets: ['@babel/preset-env']

</code>```

Body:
I'm trying to install react but I'm encountering an error while doing npm start.
I have tried many solutions regarding changing babel versions but still not able to fully fix it.

Error:

C:\Users\support\Desktop\reactApp>npm start

> reactapp@1.0.0 start C:\Users\support\Desktop\reactApp
> webpack-dev-server --mode development --open --hot

i ｢wds｣: Project is running at http://localhost:8001/
i ｢wds｣: webpack output is served from /
i ｢wds｣: Content not from webpack is served from C:\Users\support\Desktop\reactApp
i ｢wdm｣: wait until bundle finished: /
× ｢wdm｣: Hash: 8012f13b5074e55019d9
Version: webpack 4.43.0
Time: 645ms
Built at: 06/02/2020 2:29:04 PM
          Asset       Size  Chunks             Chunk Names
     index.html  272 bytes          [emitted]
index_bundle.js    395 KiB    main  [emitted]  main
Entrypoint main = index_bundle.js
[0] multi (webpack)-dev-server/client?http://localhost:8001 (webpack)/hot/dev-server.js ./main.js 52 bytes {main} [built]
[./main.js] 1.37 KiB {main} [built] [failed] [1 error]
[./node_modules/webpack-dev-server/client/index.js?http://localhost:8001] (webpack)-dev-server/client?http://localhost:8001 4.29 KiB {main} [built]
[./node_modules/webpack-dev-server/client/overlay.js] (webpack)-dev-server/client/overlay.js 3.51 KiB {main} [built]
[./node_modules/webpack-dev-server/client/socket.js] (webpack)-dev-server/client/socket.js 1.53 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/createSocketUrl.js] (webpack)-dev-server/client/utils/createSocketUrl.js 2.91 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/log.js] (webpack)-dev-server/client/utils/log.js 964 bytes {main} [built]
[./node_modules/webpack-dev-server/client/utils/reloadApp.js] (webpack)-dev-server/client/utils/reloadApp.js 1.59 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/sendMessage.js] (webpack)-dev-server/client/utils/sendMessage.js 402 bytes {main} [built]
[./node_modules/webpack-dev-server/node_modules/strip-ansi/index.js] (webpack)-dev-server/node_modules/strip-ansi/index.js 161 bytes {main} [built]
[./node_modules/webpack/hot sync ^\.\/log$] (webpack)/hot sync nonrecursive ^\.\/log$ 170 bytes {main} [built]
[./node_modules/webpack/hot/dev-server.js] (webpack)/hot/dev-server.js 1.59 KiB {main} [built]
[./node_modules/webpack/hot/emitter.js] (webpack)/hot/emitter.js 75 bytes {main} [built]
[./node_modules/webpack/hot/log-apply-result.js] (webpack)/hot/log-apply-result.js 1.27 KiB {main} [built]
[./node_modules/webpack/hot/log.js] (webpack)/hot/log.js 1.34 KiB {main} [built]
    + 20 hidden modules

ERROR in ./main.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module 'babel-preset-env' from 'C:\Users\support\Desktop\reactApp'
- Did you mean "@babel/env"?
    at Function.resolveSync [as sync] (C:\Users\support\Desktop\reactApp\node_modules\resolve\lib\sync.js:89:15)
    at resolveStandardizedName (C:\Users\support\Desktop\reactApp\node_modules\@babel\core\lib\config\files\plugins.js:101:31)
    at resolvePreset (C:\Users\support\Desktop\reactApp\node_modules\@babel\core\lib\config\files\plugins.js:58:10)
    at loadPreset (C:\Users\support\Desktop\reactApp\node_modules\@babel\core\lib\config\files\plugins.js:77:20)
    at createDescriptor (C:\Users\support\Desktop\reactApp\node_modules\@babel\core\lib\config\config-descriptors.js:154:9)
    at C:\Users\support\Desktop\reactApp\node_modules\@babel\core\lib\config\config-descriptors.js:109:50
    at Array.map (<anonymous>)
    at createDescriptors (C:\Users\support\Desktop\reactApp\node_modules\@babel\core\lib\config\config-descriptors.js:109:29)
    at createPresetDescriptors (C:\Users\support\Desktop\reactApp\node_modules\@babel\core\lib\config\config-descriptors.js:101:10)
    at C:\Users\support\Desktop\reactApp\node_modules\@babel\core\lib\config\config-descriptors.js:58:104
Child HtmlWebpackCompiler:
     1 asset
    Entrypoint HtmlWebpackPlugin_0 = __child-HtmlWebpackPlugin_0
    [./node_modules/html-webpack-plugin/lib/loader.js!./index.html] 501 bytes {HtmlWebpackPlugin_0} [built]
i ｢wdm｣: Failed to compile.

These are my following files

webpack.comfig.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
   entry: './main.js',
   output: {
      path: path.join(__dirname, '/bundle'),
      filename: 'index_bundle.js'
   },
   devServer: {
      inline: true,
      port: 8001
   },
   module: {
      rules: [
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
               presets: ['env', 'react']
            }
         }
      ]
   },
   plugins:[
      new HtmlWebpackPlugin({
         template: './index.html'
      })
   ]
}

package.json

{
  "name": "reactapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --mode development --open --hot",
    "build": "webpack --mode production"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.11.0"
  },
  "devDependencies": {
    "@babel/core": "^7.10.2",
    "@babel/preset-env": "^7.10.2",
    "@babel/preset-react": "^7.10.1",
    "babel-loader": "^8.1.0",
    "html-webpack-plugin": "^4.3.0"
  }
}

.babelrc

{
    "presets": [
        "@babel/preset-env",
        "@babel/preset-react"
    ]
}

Body:
You are using babel preset 7+

Do this in your webpack.config.js

presets: ['@babel/preset-env']


问:
Fragmented MP4 video with multiple sets of SPS and PPS with avcc encoding
I am trying to capture image of screen very frequently and then encode it in avcc format. Using the SPS, PPS, and avccnalunits of the encoded frames I am creating fragmented mp4 video and pushing those fragments to cloud, and concat all those fragments to form a big video mp4 file. It works very well until and unless all the fragments have same SPS and PPS, but if there are multipe sets of SPS and PPS in single video its not playable. Please let me know which box should be modified to accommodate this. </p>

答:
You have multiple options here and you should investigate them since the behaviours could differ between players:

Use multiple AVCConfigurationBox entries and then reference the proper sample description index via sample_description_index in the stsc box. I think this should be the most reliable, but then you need to update moov when new SPS/PPS arrive.

There is a thing called parameter set stream (see
5.3.5 AVC parameter set stream definition of ISO 14496-15), each sample in that stream contains a new AVCConfigurationBox. No idea how widely supported this is.

Always put the new SPS/PPS inline. Again, parsers may ignore the inline SPS/PPS and use the ones from the sample description box.


问:
AG Grid - Suppress row selection inside a particular column/cell
Using AG Grid, i need to make a table with row selection on click, but where clicking on certain cells will NOT cause the row to be selected.

The best idea I've had so far is to disable on-click row selection when the mouse hovers over the non-selecting cell. Something like:

```<code>gridOptions.onCellMouseOver = (event) => {
 if (/*cell is from non-select column*/ )
   this.gridOptions.suppressRowClickSelection = true;
}

gridOptions.onCellMouseOut = (event) => {
 if (/*cell is from non-select column*/ )
   this.gridOptions.suppressRowClickSelection = false;
}
</code>```

The only issue with this is that onCellMouseOver and Out do not seem to trigger in a timely fashion; If you quickly move from selecting a row, to clicking inside the no-select cell, the row selection will still trigger. I have an additional onCellClicked function which fires and shows that gridOptions.suppressRowClickSelection is set to true as expected, but seems like the property is not set in time when the clicks come in too fast.

If anyone knows a way around this onMouseOver timing issue, I'd love to know. Or, if there is a better way overall to implement this functionality, I'm all ear.

Thanks

答:
I used this workaround because I need to fullWidth row on click, but after a click on the first column I should navigate

```<code><ag-grid-angular (gridReady)="onGridReady($event)" (rowClicked)="onRowClick($event)">

onRowClick(params: RowClickedEvent) {
    if(this.gridApi.getFocusedCell().column.getColId() === 'number'){
        this.goToItem(params.data.id);
        return;
    }

    //Other row logic
}
</code>```

Of course, you have to define gridAPI variable as defined in samples.

```<code>gridApi: GridApi;
gridColumnApi: ColumnApi;

onGridReady(params: any) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;
}
</code>```

Body:
Using AG Grid, i need to make a table with row selection on click, but where clicking on certain cells will NOT cause the row to be selected.

The best idea I've had so far is to disable on-click row selection when the mouse hovers over the non-selecting cell. Something like:

gridOptions.onCellMouseOver = (event) => {
 if (/*cell is from non-select column*/ )
   this.gridOptions.suppressRowClickSelection = true;
}

gridOptions.onCellMouseOut = (event) => {
 if (/*cell is from non-select column*/ )
   this.gridOptions.suppressRowClickSelection = false;
}

The only issue with this is that onCellMouseOver and Out do not seem to trigger in a timely fashion; If you quickly move from selecting a row, to clicking inside the no-select cell, the row selection will still trigger. I have an additional onCellClicked function which fires and shows that gridOptions.suppressRowClickSelection is set to true as expected, but seems like the property is not set in time when the clicks come in too fast.

If anyone knows a way around this onMouseOver timing issue, I'd love to know. Or, if there is a better way overall to implement this functionality, I'm all ear.

Thanks

Body:
I used this workaround because I need to fullWidth row on click, but after a click on the first column I should navigate

<ag-grid-angular (gridReady)="onGridReady($event)" (rowClicked)="onRowClick($event)">

onRowClick(params: RowClickedEvent) {
    if(this.gridApi.getFocusedCell().column.getColId() === 'number'){
        this.goToItem(params.data.id);
        return;
    }

    //Other row logic
}

Of course, you have to define gridAPI variable as defined in samples.

gridApi: GridApi;
gridColumnApi: ColumnApi;

onGridReady(params: any) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;
}


问:
submit button is not working. i have a mysql database and i am trying to make a php form
when i hit the submit button, nothing happens. perhaps the database is not connected. i am trying to make a form using php and html. i am using xampp, i wrote the code in notepad++ and i saved form.php in htdocs. i don't know what is wrong. maybe the names i used for the variables.

this is the html code:

```<code>    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    </head>

    <body>
        <form method="post" action="C:\xampp\htdocs\form.php">
    Nume de utilizator : <input type="text" name="nume_de_utilizator" placeholder="Enter Your Name" >
    Email : <input type="text" name="email" placeholder="Enter Your Email">
    Parola: <input type="password" name="parola">
    <input type="submit" value="submit" >
    </form>
    </body>
    </html>

this is form.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "autentificare";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}
$nume_de_utilizator = mysqli_real_escape_string($conn, $_POST['nume_de_utilizator']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$parola = mysqli_real_escape_string($conn, $_POST['parola']);

// Attempt insert query execution
$sql = "INSERT INTO utilizatori (nume_de_utilizator, email, parola) VALUES ('$nume_de_utilizator', '$email', '$parola')";
if(mysqli_query($conn, $sql))
     printf("%d Row inserted.\n", mysqli_affected_rows($con));
else
{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);}

// Close connection
mysqli_close($conn);
?>
</code>```

and this is the "autentificare", the database
my database

答:
Try to see the "online link"
eg: "http://localhost:8080/form.php"

 Do a simple echo msg - file to check and after replace

action="C:\xampp\htdocs\form.php" with action=http_link

Body:
when i hit the submit button, nothing happens. perhaps the database is not connected. i am trying to make a form using php and html. i am using xampp, i wrote the code in notepad++ and i saved form.php in htdocs. i don't know what is wrong. maybe the names i used for the variables.

this is the html code:

    <!doctype html>

    <meta charset="utf-8">
    <title>Untitled Document</title>

        <form method="post" action="C:\xampp\htdocs\form.php">
    Nume de utilizator : <input type="text" name="nume_de_utilizator" placeholder="Enter Your Name" >
    Email : <input type="text" name="email" placeholder="Enter Your Email">
    Parola: <input type="password" name="parola">
    <input type="submit" value="submit" >
    </form>

this is form.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "autentificare";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}
$nume_de_utilizator = mysqli_real_escape_string($conn, $_POST['nume_de_utilizator']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$parola = mysqli_real_escape_string($conn, $_POST['parola']);

// Attempt insert query execution
$sql = "INSERT INTO utilizatori (nume_de_utilizator, email, parola) VALUES ('$nume_de_utilizator', '$email', '$parola')";
if(mysqli_query($conn, $sql))
     printf("%d Row inserted.\n", mysqli_affected_rows($con));
else
{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);}

// Close connection
mysqli_close($conn);
?>

and this is the "autentificare", the database
my database


问:
How to change the directory/file path of a file being served by Firebase?
I am currently hosting a static website through Firebase, but the one file being served (index.html) exists in my Mac computer's Public folder. Since I would like to serve other files, I want to move the index to a project folder that will contain future linked files (e.g. /public/my-project/index.html).

How would I go about updating the file path/directory?

答:
In your project directory (the directory in which you run firebase deploy or firebase deploy --only hosting), open or create firebase.json and make sure it points to the correct public folder.

```<code>{
  "hosting": {
    "public": "public"
  }
}
</code>```

This is a relative path. If your project and your firebase.json are located in /projects/my-project, this will deploy everything in /projects/my-project/public.

All of this is set up automatically if you initialize your Firebase project with firebase init.

Since your project may contain lots of files that aren't supposed to be deployed (readme, node_modules, build scripts etc.), I'd recommend having a public folder inside the project folder, like described above. (You can, however, ignore files with the ignore option, but you'd like to keep this list of ignored files manageable.)

If you really don't want a public folder inside your project, you may try pointing to the current folder from your firebase.json:

```<code>{
  "hosting": {
    "public": "."
  }
}
</code>```

More information about hosting configuration: https://firebase.google.com/docs/hosting/full-config

Body:
In your project directory (the directory in which you run firebase deploy or firebase deploy --only hosting), open or create firebase.json and make sure it points to the correct public folder.

{
  "hosting": {
    "public": "public"
  }
}

This is a relative path. If your project and your firebase.json are located in /projects/my-project, this will deploy everything in /projects/my-project/public.

All of this is set up automatically if you initialize your Firebase project with firebase init.

Since your project may contain lots of files that aren't supposed to be deployed (readme, node_modules, build scripts etc.), I'd recommend having a public folder inside the project folder, like described above. (You can, however, ignore files with the ignore option, but you'd like to keep this list of ignored files manageable.)

If you really don't want a public folder inside your project, you may try pointing to the current folder from your firebase.json:

{
  "hosting": {
    "public": "."
  }
}

More information about hosting configuration: https://firebase.google.com/docs/hosting/full-config


问:
Joining item in list of strings with a string outside of list
Most of the solutions I've come across involve joining items within a list, but my question is about joining an item from a list of strings with another string outside of the list.

In the script below, the desired output is "USD.JPY.SPOT.SPR" as a string, and then the subsequent pairings.

I've tried pairing.join(".SPOT.SPR") and pairing+".SPOT.SPR" but they've not generated the desired output.

```<code>pairings = ["USD.JPY", "USD.HKD", "AUD.USD", "EUR.USD", "GBP.USD", "USD.SGD"]
for pairing in pairings:
    print(pairing.join(".SPOT.SPR"))
</code>```

答:
Try iterating through the list index and '+' to concatenate - </p>

```<code>pairings = ["USD.JPY", "USD.HKD", "AUD.USD", "EUR.USD", "GBP.USD", "USD.SGD"]
for i in range(len(pairings)):
    print(pairings[i]+(".SPOT.SPR"))
</code>```

Body:
Most of the solutions I've come across involve joining items within a list, but my question is about joining an item from a list of strings with another string outside of the list.

In the script below, the desired output is "USD.JPY.SPOT.SPR" as a string, and then the subsequent pairings.

I've tried pairing.join(".SPOT.SPR") and pairing+".SPOT.SPR" but they've not generated the desired output.

pairings = ["USD.JPY", "USD.HKD", "AUD.USD", "EUR.USD", "GBP.USD", "USD.SGD"]
for pairing in pairings:
    print(pairing.join(".SPOT.SPR"))

Body:
Try iterating through the list index and '+' to concatenate -

pairings = ["USD.JPY", "USD.HKD", "AUD.USD", "EUR.USD", "GBP.USD", "USD.SGD"]
for i in range(len(pairings)):
    print(pairings[i]+(".SPOT.SPR"))


问:
How to get the rules from one dataframe and apply it to other dataframe to get the stats in python?
I have two data frame df1 and df2 as shown

```<code>  type  follow  following  sum   count
0 i_12    hard    norm     250     1
1 i_45    norm    norm     450     2
2 k_2     ease    hard     345     5
3 i_8     hard    norm     56      1
4 j_9     ease    ease     5       5

    type   follow  following  sum   count
0  i_group  hard    norm       780   67
1  i_group  norm    norm       567   7
2  k_group  ease    hard       678   5
3  j_group  ease    ease       5     5
</code>```

here, the column [follow & following] is rules and [sum & count] is stats for the same.

I want to write a code that will take rules from df2 and type for which the rules will apply on df1 and get the row from df1 which will satisfy it.

for ex

[i_12, i_45, i_8] belongs to "i_group",  for which they have different stats for different rules.

So I just have to pass column[type, follow, following] from df2 and it should return the result from df1 as shown below.

```<code> type   follow  following  sum   count
i_group hard     norm      306    2           #WHICH IS A SUM OF ROW 0 AND 3
i_group norm     norm      56     1           #and so on.....
</code>```

答:
I believe you need first match type between both DataFrames, then for filter columns by df2 is used DataFrame.merge and last if necessary aggregate sum:

```<code>df = (df1.assign(type=df1['type'].replace('\d+', 'group', regex=True))
         .merge(df2[['type','follow','following']])
         .groupby(['type','follow','following'], as_index=False).sum())

print (df)
      type follow following  sum  count
0  i_group   hard      norm  306      2
1  i_group   norm      norm  450      2
2  j_group   ease      ease    5      5
3  k_group   ease      hard  345      5
</code>```

Body:
I have two data frame df1 and df2 as shown

  type  follow  following  sum   count
0 i_12    hard    norm     250     1
1 i_45    norm    norm     450     2
2 k_2     ease    hard     345     5
3 i_8     hard    norm     56      1
4 j_9     ease    ease     5       5

    type   follow  following  sum   count
0  i_group  hard    norm       780   67
1  i_group  norm    norm       567   7
2  k_group  ease    hard       678   5
3  j_group  ease    ease       5     5

here, the column [follow & following] is rules and [sum & count] is stats for the same.

I want to write a code that will take rules from df2 and type for which the rules will apply on df1 and get the row from df1 which will satisfy it.

for ex

[i_12, i_45, i_8] belongs to "i_group",  for which they have different stats for different rules.

So I just have to pass column[type, follow, following] from df2 and it should return the result from df1 as shown below.

 type   follow  following  sum   count
i_group hard     norm      306    2           #WHICH IS A SUM OF ROW 0 AND 3
i_group norm     norm      56     1           #and so on.....

Body:
I believe you need first match type between both DataFrames, then for filter columns by df2 is used DataFrame.merge and last if necessary aggregate sum:

df = (df1.assign(type=df1['type'].replace('\d+', 'group', regex=True))
         .merge(df2[['type','follow','following']])
         .groupby(['type','follow','following'], as_index=False).sum())

print (df)
      type follow following  sum  count
0  i_group   hard      norm  306      2
1  i_group   norm      norm  450      2
2  j_group   ease      ease    5      5
3  k_group   ease      hard  345      5


问:
How to assign data from pandas groupby function to a variable?
I have a question regarding Pandas.
I grouped data by column (Districts)

```<code>GroupByDistrict = df.groupby(['District'])
</code>```

and then I want to get data

```<code>print(GroupByDistrict['Price'].agg(['median','mean']))
</code>```

Output of this command shows average prices in different districts.

How can I assign this data to a variable (list or dictionary)?

If I do something like this

```<code>xx = GroupByDistrict['Price'].agg(['median','mean'])
print(xx)
</code>```

the output gives object

答:
You can do that as:</p>

```<code>district_prices = df.groupby('District').agg({'Price': [ 'median', 'mean']}).apply(list).to_dict()

print(district_prices)
</code>```

Body:
I have a question regarding Pandas.
I grouped data by column (Districts)

GroupByDistrict = df.groupby(['District'])

and then I want to get data

print(GroupByDistrict['Price'].agg(['median','mean']))

Output of this command shows average prices in different districts.

How can I assign this data to a variable (list or dictionary)?

If I do something like this

xx = GroupByDistrict['Price'].agg(['median','mean'])
print(xx)

the output gives object

Body:
You can do that as:

district_prices = df.groupby('District').agg({'Price': [ 'median', 'mean']}).apply(list).to_dict()

print(district_prices)