问:
AWS inter-subnet routing issue
I have a VPC ( say vpc-a ) with CIDR range 192.170.0.0/16 .

I have created 3 subnets in the VPC which are as follows:

```<code>   > aws ec2 describe-subnets --filters Name=vpc-id,Values=vpc-05d932bbfd4bfe3c5
    {
        "Subnets": [
            {
                "AvailabilityZone": "ap-south-1b",
                "AvailabilityZoneId": "aps1-az3",
                "AvailableIpAddressCount": 57,
                "CidrBlock": "192.170.80.0/26",
                "DefaultForAz": false,
                "MapPublicIpOnLaunch": true,
                "State": "available",
                "SubnetId": "subnet-0a4c7cc6faa094318",
                "VpcId": "vpc-05d932bbfd4bfe3c5",
                "OwnerId": "336282279309",
                "AssignIpv6AddressOnCreation": false,
                "Ipv6CidrBlockAssociationSet": [],
                "Tags": [
                    ...
                ],
                "SubnetArn": "arn:aws:ec2:ap-south-1:336282279309:subnet/subnet-0a4c7cc6faa094318"
            },
            {
                "AvailabilityZone": "ap-south-1a",
                "AvailabilityZoneId": "aps1-az1",
                "AvailableIpAddressCount": 48,
                "CidrBlock": "192.170.0.0/26",
                "DefaultForAz": false,
                "MapPublicIpOnLaunch": true,
                "State": "available",
                "SubnetId": "subnet-0b6e7a1e1840713a9",
                "VpcId": "vpc-05d932bbfd4bfe3c5",
                "OwnerId": "336282279309",
                "AssignIpv6AddressOnCreation": false,
                "Ipv6CidrBlockAssociationSet": [],
                "Tags": [
                    ...
                ],
                "SubnetArn": "arn:aws:ec2:ap-south-1:336282279309:subnet/subnet-0b6e7a1e1840713a9"
            },
            {
                "AvailabilityZone": "ap-south-1c",
                "AvailabilityZoneId": "aps1-az2",
                "AvailableIpAddressCount": 49,
                "CidrBlock": "192.170.160.0/26",
                "DefaultForAz": false,
                "MapPublicIpOnLaunch": true,
                "State": "available",
                "SubnetId": "subnet-0e45e8fc489794ea9",
                "VpcId": "vpc-05d932bbfd4bfe3c5",
                "OwnerId": "336282279309",
                "AssignIpv6AddressOnCreation": false,
                "Ipv6CidrBlockAssociationSet": [],
                "Tags": [
                    ...
                ],
                "SubnetArn": "arn:aws:ec2:ap-south-1:336282279309:subnet/subnet-0e45e8fc489794ea9"
            }
        ]
    }
</code>```

So basically 3 subnets are:

```<code>subnet-0   CIDR: 192.170.0.0/26    Zone: ap-south-1a
subnet-1   CIDR: 192.170.80.0/26   Zone: ap-south-1b
subnet-2   CISR: 192.170.160.0/26  Zone: ap-south-1c
</code>```

The route tables are as follows:

```<code> aws ec2 describe-route-tables --filters Name=vpc-id,Values=vpc-05d932bbfd4bfe3c5
{
    "RouteTables": [
        {
            "Associations": [
                {
                    "Main": true,
                    "RouteTableAssociationId": "rtbassoc-02f438a98c50824f2",
                    "RouteTableId": "rtb-04a14541aaf44b1d1",
                    "AssociationState": {
                        "State": "associated"
                    }
                }
            ],
            "PropagatingVgws": [],
            "RouteTableId": "rtb-04a14541aaf44b1d1",
            "Routes": [
                {
                    "DestinationCidrBlock": "192.170.0.0/16",
                    "GatewayId": "local",
                    "Origin": "CreateRouteTable",
                    "State": "active"
                }
            ],
            "Tags": [],
            "VpcId": "vpc-05d932bbfd4bfe3c5",
            "OwnerId": "336282279309"
        },
        {
            "Associations": [
                {
                    "Main": false,
                    "RouteTableAssociationId": "rtbassoc-047cce5bf22b50a76",
                    "RouteTableId": "rtb-08371ccc1f79ebfe6",
                    "SubnetId": "subnet-0e45e8fc489794ea9",
                    "AssociationState": {
                        "State": "associated"
                    }
                },
                {
                    "Main": false,
                    "RouteTableAssociationId": "rtbassoc-0fbf237d4b7af1b57",
                    "RouteTableId": "rtb-08371ccc1f79ebfe6",
                    "SubnetId": "subnet-0a4c7cc6faa094318",
                    "AssociationState": {
                        "State": "associated"
                    }
                },
                {
                    "Main": false,
                    "RouteTableAssociationId": "rtbassoc-066c66d94f1aa32a5",
                    "RouteTableId": "rtb-08371ccc1f79ebfe6",
                    "SubnetId": "subnet-0b6e7a1e1840713a9",
                    "AssociationState": {
                        "State": "associated"
                    }
                }
            ],
            "PropagatingVgws": [],
            "RouteTableId": "rtb-08371ccc1f79ebfe6",
            "Routes": [
                {
                    "DestinationCidrBlock": "192.168.0.0/24",
                    "TransitGatewayId": "tgw-065d7ae5e846681b0",
                    "Origin": "CreateRoute",
                    "State": "active"
                },
                {
                    "DestinationCidrBlock": "192.170.0.0/16",
                    "GatewayId": "local",
                    "Origin": "CreateRouteTable",
                    "State": "active"
                },
                {
                    "DestinationCidrBlock": "0.0.0.0/0",
                    "GatewayId": "igw-0d37c7db290bf696c",
                    "Origin": "CreateRoute",
                    "State": "active"
                }
            ],
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "wqw"
                }
            ],
            "VpcId": "vpc-05d932bbfd4bfe3c5",
            "OwnerId": "336282279309"
        }
    ]
}
</code>```

I have 2 ec2 instances :

```<code>instance-1  Subnet: subnet-0 ,  IP :  192.170.0.57
instance-2  Subnet: subnet-1 ,  IP :  192.170.80.6
</code>```

I am unable to do ssh from instance-1 to instance-2 or vice-varsa. However I am able to ssh to both of them from another instance in another vpc with cidr 192.168.0.0/16 using transit gateway, which you may find in the routing information above.

Do I need to add additional routing info between the subnets subnet-0 & subnet-1 ? If so what would be the "target" of such route ? I tried enabling flow-log on the vpc but nothing came in cloud-watch logs.

Appreciate some help here.

答:
The local VPC route will always be allowed so this is not a routing issue.

Check the following:

Security Groups

NACLs.

Also take a look at VPC Flow Logs and enable on both subnets. Look for REJECTs.

Title: AWS inter-subnet routing issue

Body:
I have a VPC ( say vpc-a ) with CIDR range 192.170.0.0/16 .

I have created 3 subnets in the VPC which are as follows:

   > aws ec2 describe-subnets --filters Name=vpc-id,Values=vpc-05d932bbfd4bfe3c5
    {
        "Subnets": [
            {
                "AvailabilityZone": "ap-south-1b",
                "AvailabilityZoneId": "aps1-az3",
                "AvailableIpAddressCount": 57,
                "CidrBlock": "192.170.80.0/26",
                "DefaultForAz": false,
                "MapPublicIpOnLaunch": true,
                "State": "available",
                "SubnetId": "subnet-0a4c7cc6faa094318",
                "VpcId": "vpc-05d932bbfd4bfe3c5",
                "OwnerId": "336282279309",
                "AssignIpv6AddressOnCreation": false,
                "Ipv6CidrBlockAssociationSet": [],
                "Tags": [
                    ...
                ],
                "SubnetArn": "arn:aws:ec2:ap-south-1:336282279309:subnet/subnet-0a4c7cc6faa094318"
            },
            {
                "AvailabilityZone": "ap-south-1a",
                "AvailabilityZoneId": "aps1-az1",
                "AvailableIpAddressCount": 48,
                "CidrBlock": "192.170.0.0/26",
                "DefaultForAz": false,
                "MapPublicIpOnLaunch": true,
                "State": "available",
                "SubnetId": "subnet-0b6e7a1e1840713a9",
                "VpcId": "vpc-05d932bbfd4bfe3c5",
                "OwnerId": "336282279309",
                "AssignIpv6AddressOnCreation": false,
                "Ipv6CidrBlockAssociationSet": [],
                "Tags": [
                    ...
                ],
                "SubnetArn": "arn:aws:ec2:ap-south-1:336282279309:subnet/subnet-0b6e7a1e1840713a9"
            },
            {
                "AvailabilityZone": "ap-south-1c",
                "AvailabilityZoneId": "aps1-az2",
                "AvailableIpAddressCount": 49,
                "CidrBlock": "192.170.160.0/26",
                "DefaultForAz": false,
                "MapPublicIpOnLaunch": true,
                "State": "available",
                "SubnetId": "subnet-0e45e8fc489794ea9",
                "VpcId": "vpc-05d932bbfd4bfe3c5",
                "OwnerId": "336282279309",
                "AssignIpv6AddressOnCreation": false,
                "Ipv6CidrBlockAssociationSet": [],
                "Tags": [
                    ...
                ],
                "SubnetArn": "arn:aws:ec2:ap-south-1:336282279309:subnet/subnet-0e45e8fc489794ea9"
            }
        ]
    }

So basically 3 subnets are:

subnet-0   CIDR: 192.170.0.0/26    Zone: ap-south-1a
subnet-1   CIDR: 192.170.80.0/26   Zone: ap-south-1b
subnet-2   CISR: 192.170.160.0/26  Zone: ap-south-1c

The route tables are as follows:

 aws ec2 describe-route-tables --filters Name=vpc-id,Values=vpc-05d932bbfd4bfe3c5
{
    "RouteTables": [
        {
            "Associations": [
                {
                    "Main": true,
                    "RouteTableAssociationId": "rtbassoc-02f438a98c50824f2",
                    "RouteTableId": "rtb-04a14541aaf44b1d1",
                    "AssociationState": {
                        "State": "associated"
                    }
                }
            ],
            "PropagatingVgws": [],
            "RouteTableId": "rtb-04a14541aaf44b1d1",
            "Routes": [
                {
                    "DestinationCidrBlock": "192.170.0.0/16",
                    "GatewayId": "local",
                    "Origin": "CreateRouteTable",
                    "State": "active"
                }
            ],
            "Tags": [],
            "VpcId": "vpc-05d932bbfd4bfe3c5",
            "OwnerId": "336282279309"
        },
        {
            "Associations": [
                {
                    "Main": false,
                    "RouteTableAssociationId": "rtbassoc-047cce5bf22b50a76",
                    "RouteTableId": "rtb-08371ccc1f79ebfe6",
                    "SubnetId": "subnet-0e45e8fc489794ea9",
                    "AssociationState": {
                        "State": "associated"
                    }
                },
                {
                    "Main": false,
                    "RouteTableAssociationId": "rtbassoc-0fbf237d4b7af1b57",
                    "RouteTableId": "rtb-08371ccc1f79ebfe6",
                    "SubnetId": "subnet-0a4c7cc6faa094318",
                    "AssociationState": {
                        "State": "associated"
                    }
                },
                {
                    "Main": false,
                    "RouteTableAssociationId": "rtbassoc-066c66d94f1aa32a5",
                    "RouteTableId": "rtb-08371ccc1f79ebfe6",
                    "SubnetId": "subnet-0b6e7a1e1840713a9",
                    "AssociationState": {
                        "State": "associated"
                    }
                }
            ],
            "PropagatingVgws": [],
            "RouteTableId": "rtb-08371ccc1f79ebfe6",
            "Routes": [
                {
                    "DestinationCidrBlock": "192.168.0.0/24",
                    "TransitGatewayId": "tgw-065d7ae5e846681b0",
                    "Origin": "CreateRoute",
                    "State": "active"
                },
                {
                    "DestinationCidrBlock": "192.170.0.0/16",
                    "GatewayId": "local",
                    "Origin": "CreateRouteTable",
                    "State": "active"
                },
                {
                    "DestinationCidrBlock": "0.0.0.0/0",
                    "GatewayId": "igw-0d37c7db290bf696c",
                    "Origin": "CreateRoute",
                    "State": "active"
                }
            ],
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "wqw"
                }
            ],
            "VpcId": "vpc-05d932bbfd4bfe3c5",
            "OwnerId": "336282279309"
        }
    ]
}

I have 2 ec2 instances :

instance-1  Subnet: subnet-0 ,  IP :  192.170.0.57
instance-2  Subnet: subnet-1 ,  IP :  192.170.80.6

I am unable to do ssh from instance-1 to instance-2 or vice-varsa. However I am able to ssh to both of them from another instance in another vpc with cidr 192.168.0.0/16 using transit gateway, which you may find in the routing information above.

Do I need to add additional routing info between the subnets subnet-0 & subnet-1 ? If so what would be the "target" of such route ? I tried enabling flow-log on the vpc but nothing came in cloud-watch logs.

Appreciate some help here.


来源: stackexchange

问:
How I Use My Redeemed Free Credits from AWS?
Yesterday, I received an email from Amazon like this:

Subject: "AWS Summit Online - Feedback Ninja USD$25 AWS Credits"

"Thank you for participating and providing feedback at AWS Summit Online. We are pleased to inform you that as a Feedback Ninja, you have been allocated the USD$25 AWS credit code."

When I log in to my AWS account, I had redeemed it and now my account have credit like this:

How I use my redeemed credits? Because I want to learn AWS with it.

答:
Now, start using your AWS server, but always keep informed yourself by using bill forecast. It will show you the upcoming bill value.
Most important part is your credit will automatically consume from your bill value. </p>

ContentLicense: CC BY-SA 4.0


问:
Parse small string for name and email?
I have a string:

John Smith <jsmith@gmail.com>

I would like to get two variables:

name (John Smith) and email (jsmith@gmail.com)

How might I do that?

Thanks for the help!

答:
There are more forms of valid Internet Email address than you probably realize.  I would suggest using somebody else's code to parse them, like email.utils.parseaddr.

For example, the following is a valid address:

```<code>"Rocky J. Squirrel" <rocky.squirrel@gmail.com>
</code>```

Here, the name is Rocky J. Squirrel, not "Rocky J. Squirrel".

The following is also legal syntax and shows up regularly in mail headers (note lack of <> delimiters):

```<code>rocky.squirrel@gmail.com (Rocky J. Squirrel)
</code>```

Although the part in parens is technically just a "comment", most mail clients interpret it as the user's name.  (And so does Python's email.utils.parseaddr.)

To actually do the parsing (saving you reading the docs):

```<code>>>> import email.utils
>>> email.utils.parseaddr("John Smith <jsmith@gmail.com>")
('John Smith', 'jsmith@gmail.com')
</code>```

ContentLicense: CC BY-SA 3.0

Title: Parse small string for name and email?

Body:
There are more forms of valid Internet Email address than you probably realize.  I would suggest using somebody else's code to parse them, like email.utils.parseaddr.

For example, the following is a valid address:

"Rocky J. Squirrel" <rocky.squirrel@gmail.com>

Here, the name is Rocky J. Squirrel, not "Rocky J. Squirrel".

The following is also legal syntax and shows up regularly in mail headers (note lack of <> delimiters):

rocky.squirrel@gmail.com (Rocky J. Squirrel)

Although the part in parens is technically just a "comment", most mail clients interpret it as the user's name.  (And so does Python's email.utils.parseaddr.)

To actually do the parsing (saving you reading the docs):

>>> import email.utils
>>> email.utils.parseaddr("John Smith <jsmith@gmail.com>")
('John Smith', 'jsmith@gmail.com')


问:
How can i configurate the emqtt`s max packet size
I send the large data (about 50MB),And i add the mqtt.max_packet_size value as 6400KB ,But still report below error info .from https://docs.emqx.io/docs/broker/v3/cn/config.html#mqtt  it shows that this value as mqtt.max_packet_size = 1MB, I am not sure this value can be add more because i need to send large data .
Please advice.thanks

current config:

```<code>//Max Packet Size Allowed, 64K by default.

mqtt.max_packet_size = 6400KB
</code>```

emqtt version info as below:

```<code>[root@proxy bin]# ./emqttd_ctl status
Node 'emqttd@127.0.0.1' is started
emqttd 2.2 is running
</code>```

error log

```<code>2020-05-21 11:30:55.859 [error] <0.17448.21>@emqttd_client:received:328 Client(127.0.0.1:59748): Framing error - invalid_mqtt_frame_len
</code>```

Body:
I send the large data (about 50MB),And i add the mqtt.max_packet_size value as 6400KB ,But still report below error info .from https://docs.emqx.io/docs/broker/v3/cn/config.html#mqtt  it shows that this value as mqtt.max_packet_size = 1MB, I am not sure this value can be add more because i need to send large data .
Please advice.thanks

current config:

//Max Packet Size Allowed, 64K by default.

mqtt.max_packet_size = 6400KB

emqtt version info as below:

[root@proxy bin]# ./emqttd_ctl status
Node 'emqttd@127.0.0.1' is started
emqttd 2.2 is running

error log

2020-05-21 11:30:55.859 [error] <0.17448.21>@emqttd_client:received:328 Client(127.0.0.1:59748): Framing error - invalid_mqtt_frame_len

Body:
6400KB？ 6400KB == 5MB

Try 64000 KB or 128MB


问:
is there a button function to completely remove background?
I'm having trouble with a button function. I have an HTML document with a background set for all pages (in order to keep a common theme). I created a button on one of my pages with the intent of removing the background on that one specific page. I used a script function to change the background color to white. When I press the button, the background changes to white, except for the parts that have text (see images linked below). How can I get the button to essentially remove the entire background?

before button is pressed

after button is pressed

Here is the code I have so far:

```<code> <body>
<style>
  body {
    background-image: url(IMG_7305.JPG);
    background-size: cover;
    background-attachment: fixed;
</style>

<button id="button" type="button" onclick="myFunction()"> Press here to remove the background image </button>

<script>
  function myFunction() {
    document.getElementById("about").style.backgroundColor = "white"
  }
</script>
<p>
  I want the background to be cleared... even here!!
</p>
</code>```

答:
Instead of having your background image on the body tag in the css, you can give it to a class and remove the class when clicked.

```<code> <body class='background'>
<style>
  .background {
    background-image: url(IMG_7305.JPG);
    background-size: cover;
    background-attachment: fixed;
</style>

<button id="button" type="button" onclick="myFunction()"> Press here to remove the background image </button>

<script>
  function myFunction() {
    document.body.classList.remove('background')
  }
</script>
<p>
  I want the background to be cleared... even here!!
</p>
</code>```

I would also recommend adding a container and style that rather than the body tag itself.

Body:
I'm having trouble with a button function. I have an HTML document with a background set for all pages (in order to keep a common theme). I created a button on one of my pages with the intent of removing the background on that one specific page. I used a script function to change the background color to white. When I press the button, the background changes to white, except for the parts that have text (see images linked below). How can I get the button to essentially remove the entire background?

before button is pressed

after button is pressed

Here is the code I have so far:

<button id="button" type="button" onclick="myFunction()"> Press here to remove the background image </button>

  I want the background to be cleared... even here!!

Body:
Instead of having your background image on the body tag in the css, you can give it to a class and remove the class when clicked.

 <body class='background'>
<style>
  .background {
    background-image: url(IMG_7305.JPG);
    background-size: cover;
    background-attachment: fixed;
</style>

<button id="button" type="button" onclick="myFunction()"> Press here to remove the background image </button>

<script>
  function myFunction() {
    document.body.classList.remove('background')
  }
</script>
<p>
  I want the background to be cleared... even here!!
</p>

I would also recommend adding a container and style that rather than the body tag itself.


问:
How to use id3 plugging in Flutter
Only getting the first letter for every tag, or may be I am wrong somewhere

```<code>void info() {
MP3Instance mp3instance = new MP3Instance("/storage/emulated/0/Download/Army_320-(Mr-Jat.in).mp3");
    if(mp3instance.parseTagsSync()){
      print(mp3instance.getMetaTags());
      print(mp3instance.metaTags['Title']);
      print(mp3instance.metaTags['Artist']);
      print(mp3instance.metaTags['Album']);
      print(mp3instance.metaTags['Year']);
      print(mp3instance.metaTags['Genre']);
    }
}
</code>```

and here is the output

```<code>I/flutter ( 6995): {Version: v2.3.0, Title: A
I/flutter ( 6995): A
I/flutter ( 6995): S
I/flutter ( 6995): H
I/flutter ( 6995): 2
I/flutter ( 6995): M
</code>```

Only the first alphabet of text appears and the stops.

答:
I printed out the ASCII equivalent of mp3instance.getMetaTags() and realized that the string has some ASCII control characters in it which terminates the print() statement.

After some research I used this method to remove the control characters:

```<code>String normalizeString(String s) {
    var encoded = ascii.encode(s.toString());
    List<int> normalized = new List.from(encoded.map((e) => (e < 32) ? 32 : e));
    return ascii.decode(normalized);
}
</code>```

I printed the normalized string as follows:

```<code> print( "Before normalizing: " + mp3instance.getMetaTags().toString() );
 String normalString = normalizeString( mp3instance.getMetaTags().toString() );
 print( "After normalizing: " + normalString);
 print( "Normalized title: " + mp3instance.metaTags['Title'].toString() );
</code>```

More resources:

Replace non ASCII character from string

Another id3 tagging flutter library

Title: How to use id3 plugging in Flutter

Body:
Only getting the first letter for every tag, or may be I am wrong somewhere

void info() {
MP3Instance mp3instance = new MP3Instance("/storage/emulated/0/Download/Army_320-(Mr-Jat.in).mp3");
    if(mp3instance.parseTagsSync()){
      print(mp3instance.getMetaTags());
      print(mp3instance.metaTags['Title']);
      print(mp3instance.metaTags['Artist']);
      print(mp3instance.metaTags['Album']);
      print(mp3instance.metaTags['Year']);
      print(mp3instance.metaTags['Genre']);
    }
}

and here is the output

I/flutter ( 6995): {Version: v2.3.0, Title: A
I/flutter ( 6995): A
I/flutter ( 6995): S
I/flutter ( 6995): H
I/flutter ( 6995): 2
I/flutter ( 6995): M

Only the first alphabet of text appears and the stops.

Body:
I printed out the ASCII equivalent of mp3instance.getMetaTags() and realized that the string has some ASCII control characters in it which terminates the print() statement.

After some research I used this method to remove the control characters:

String normalizeString(String s) {
    var encoded = ascii.encode(s.toString());
    List<int> normalized = new List.from(encoded.map((e) => (e < 32) ? 32 : e));
    return ascii.decode(normalized);
}

I printed the normalized string as follows:

 print( "Before normalizing: " + mp3instance.getMetaTags().toString() );
 String normalString = normalizeString( mp3instance.getMetaTags().toString() );
 print( "After normalizing: " + normalString);
 print( "Normalized title: " + mp3instance.metaTags['Title'].toString() );

More resources:

Replace non ASCII character from string

Another id3 tagging flutter library


答:
You need to target the body where the image is, not just the "about" element.

function myFunction() {
  document.querySelector("body").style.backgroundImage = "none";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    background-image: url('https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/beach-quotes-1559667853.jpg');
    background-size: cover;
    background-attachment: fixed;
 }</code>```

<button id="button" type="button" onclick="myFunction()"> Press here to remove the background image </button>

  I want the background to be cleared... even here!!

```

Title: is there a button function to completely remove background?

Body:
You need to target the body where the image is, not just the "about" element.

function myFunction() {
  document.querySelector("body").style.backgroundImage = "none";
}

body {
    background-image: url('https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/beach-quotes-1559667853.jpg');
    background-size: cover;
    background-attachment: fixed;
 }

<button id="button" type="button" onclick="myFunction()"> Press here to remove the background image </button>

<p>
  I want the background to be cleared... even here!!
</p>


问:
is there a way to read multiple excel tab/sheets from single xlsx to multiple dataframes with each dataframe named with sheet name?
I am not good in python please forgive me for this question but I need to create a function which does the following thing:

Create multiple data frames from multiple excel tab/sheet present in a single xlsx file and be named on the sheet name.

The columns' values should be concatenated and checked if there is no duplicate value.

if the concat value has a duplicate then it should be told as yes/No in another column.

all the dataframes then should be written into a single workbook as different worksheets inside.
values inside () are columns for better understanding

example:

sheet1

```<code>(a) (b) (c) (d)
a1  b1  c1  d1
a2  b2  c2  d2
</code>```

result:

```<code>(c) (d) (concate) (is duplicate)
c1  d1  c1_d1     no
c2  d2  c2_d2     no
</code>```

sheet2

```<code>(a) (b) (e) (f)
a3  b3  e1  f1
a4  b4  e1  f1
a5  b5  e2  f2
a6  b6  e4  f4
a7  a8  e4  f5
</code>```

result:

```<code>(e) (f) (concat) (has duplicate)
e1 f1 e1_f1 yes
e2 f2 e2_f2 no
e4 f4 e4_f4 no
e4 f5 e4_f5 no
</code>```

答:
First of all, to read an excel file with multiple sheets, use pandas ExcelFile function.

e.g. df = pd.ExcelFile(filepath)

And, after reading the excel from the step above, you can read each sheet in a seperate dataframe using the read_excel function, e.g.

```<code>df1 = pd.read_excel(df, 'sheet_name_1')
df2 = pd.read_excel(df, 'sheet_name_2')
</code>```

insert different sheet names and read the sheets in different dataframes.

I didn't understand the latter part of your question please elaborate a bit more.

Body:
I am not good in python please forgive me for this question but I need to create a function which does the following thing:

Create multiple data frames from multiple excel tab/sheet present in a single xlsx file and be named on the sheet name.

The columns' values should be concatenated and checked if there is no duplicate value.

if the concat value has a duplicate then it should be told as yes/No in another column.

all the dataframes then should be written into a single workbook as different worksheets inside.
values inside () are columns for better understanding

example:

sheet1

(a) (b) (c) (d)
a1  b1  c1  d1
a2  b2  c2  d2

result:

(c) (d) (concate) (is duplicate)
c1  d1  c1_d1     no
c2  d2  c2_d2     no

sheet2

(a) (b) (e) (f)
a3  b3  e1  f1
a4  b4  e1  f1
a5  b5  e2  f2
a6  b6  e4  f4
a7  a8  e4  f5

result:

(e) (f) (concat) (has duplicate)
e1 f1 e1_f1 yes
e2 f2 e2_f2 no
e4 f4 e4_f4 no
e4 f5 e4_f5 no

Body:
First of all, to read an excel file with multiple sheets, use pandas ExcelFile function.

e.g. df = pd.ExcelFile(filepath)

And, after reading the excel from the step above, you can read each sheet in a seperate dataframe using the read_excel function, e.g.

df1 = pd.read_excel(df, 'sheet_name_1')
df2 = pd.read_excel(df, 'sheet_name_2')

insert different sheet names and read the sheets in different dataframes.

I didn't understand the latter part of your question please elaborate a bit more.


问:
When to use an object in `setState` instead of using functional `setState`?
I read a lot of articles about using functional setState like that:

```<code>this.setState((state, props) => ({   counter: state.counter + props.increment }));
</code>```

but when do we actually need to use it as an object like that:

```<code>this.setState({quantity: 2})
</code>```

Is there a significant reason why we should use an object in setState in normal cases vs using it as a function?

答:
In Javascript, a function is an object.

Therefore, technically, there is no difference between

a function being passed as the argument to setState and

an object being passed as the argument for the setState method.

However, a function may be used instead of an object for the purpose of formatting or for performing temporary calculations before updating the state attributes.

Example use cases for function in place of an object:

Rounding-off decimal places

Conversion of units (Celcius --> fahrenheit, KG to lb, etc)

Compute derived information (max, min, average, etc)

Body:
I read a lot of articles about using functional setState like that:

this.setState((state, props) => ({   counter: state.counter + props.increment }));

but when do we actually need to use it as an object like that:

this.setState({quantity: 2})

Is there a significant reason why we should use an object in setState in normal cases vs using it as a function?


问:
ActiveRecord not releasing memory
I have an export job that exports a big amount of data from our MySQL DB. As the data grew I noticed that the sidekiq job for this takes far too much memory. The server has 32GB and after the export is done, it takes 28GB. When I stop the sidekiq process, memory use drops to 8GB.

I already followed the guide here https://github.com/mperham/sidekiq/wiki/Problems-and-Troubleshooting

prevent memory fragmentation by using MALLOC_ARENA_MAX=2

clear query cache ActiveRecord::Base.connection.clear_query_cache

I'm on Ruby 2.6.5p114 and tried to isolate the problem by creating a new rails app in production, and using my DB as a backend:

```<code>gem install rails --version 5.2.4.3
rails new debug -d mysql
</code>```

I created an empty model to avoid custom methods in my code that maybe cause the problem:

```<code>class Variant < ApplicationRecord
end
</code>```

This script simply loads 1 Mio objects from the DB and prints the memory usage:

```<code># memory.rb

def memory
  (`ps -o rss= -p #{Process.pid}`.to_i.to_f / 1024).to_s + " MB"
end

def load_variants
  puts "load_variants..."
  Variant.uncached do
    variants = Variant.limit(1_000_000).to_a
    puts "variant.count: #{variants.count}"
  end
end

puts memory
load_variants
puts memory

puts "GC.start..."
GC.start
puts memory

# second run
load_variants
puts memory

puts "GC.start..."
GC.start
puts memory
</code>```

This is the output:

```<code>root@6e79d7a97d9c:/usr/src/debug# rails r memory.rb
76.93359375 MB
load_variants...
variant.count: 1000000
2436.3125 MB
GC.start...
2421.046875 MB
load_variants...
variant.count: 1000000
2436.3828125 MB
GC.start...
2436.3984375 MB
</code>```

it starts with 76.93359375 MB

after loading 1 Mio objects, memory increases to 2436.3125 MB

garbage collection reduces memory to 2421.046875 MB, but I would expect a significantly higher drop!

interestingly, a second run, only increases memory to 2436.3828125 MB

the last GC.start somehow increases the memory a little bit to 2436.3984375 MB

So I'd like to know how this could be? There must be something in ActiveRecord that I'm unaware, and I'd like to understand how this all works, and why the memory isn't freed.

Following this logic, the memory should increase on every request that reads data, but I assume there is something different when using within a request-response cycle.

答: Loading large object that are spread all around the memory (instead of objects like String that are in consecutive memory) in Ruby's tend to have such effect since the Mark & Sweep algorithm cannot return the whole blocks of memory back to the OS. You'll get similar effect if you start parsing large JSON files (like 10+MB) since the resulting Hash, consisting of tons of other objects, is going to be placed in multiple memory blocks along side other objects that still have an active reference and hence Ruby cannot release that block.

Title: ActiveRecord not releasing memory

Body:
I have an export job that exports a big amount of data from our MySQL DB. As the data grew I noticed that the sidekiq job for this takes far too much memory. The server has 32GB and after the export is done, it takes 28GB. When I stop the sidekiq process, memory use drops to 8GB.

I already followed the guide here https://github.com/mperham/sidekiq/wiki/Problems-and-Troubleshooting

prevent memory fragmentation by using MALLOC_ARENA_MAX=2

clear query cache ActiveRecord::Base.connection.clear_query_cache

I'm on Ruby 2.6.5p114 and tried to isolate the problem by creating a new rails app in production, and using my DB as a backend:

gem install rails --version 5.2.4.3
rails new debug -d mysql

I created an empty model to avoid custom methods in my code that maybe cause the problem:

class Variant < ApplicationRecord
end

This script simply loads 1 Mio objects from the DB and prints the memory usage:

# memory.rb

def memory
  (`ps -o rss= -p #{Process.pid}`.to_i.to_f / 1024).to_s + " MB"
end

def load_variants
  puts "load_variants..."
  Variant.uncached do
    variants = Variant.limit(1_000_000).to_a
    puts "variant.count: #{variants.count}"
  end
end

puts memory
load_variants
puts memory

puts "GC.start..."
GC.start
puts memory

# second run
load_variants
puts memory

puts "GC.start..."
GC.start
puts memory

This is the output:

root@6e79d7a97d9c:/usr/src/debug# rails r memory.rb
76.93359375 MB
load_variants...
variant.count: 1000000
2436.3125 MB
GC.start...
2421.046875 MB
load_variants...
variant.count: 1000000
2436.3828125 MB
GC.start...
2436.3984375 MB

it starts with 76.93359375 MB

after loading 1 Mio objects, memory increases to 2436.3125 MB

garbage collection reduces memory to 2421.046875 MB, but I would expect a significantly higher drop!

interestingly, a second run, only increases memory to 2436.3828125 MB

the last GC.start somehow increases the memory a little bit to 2436.3984375 MB

So I'd like to know how this could be? There must be something in ActiveRecord that I'm unaware, and I'd like to understand how this all works, and why the memory isn't freed.

Following this logic, the memory should increase on every request that reads data, but I assume there is something different when using within a request-response cycle.


问:
Error while trying to login with react native google sign-in
I'm using React-native-google-sigin package. I have followed the instructions and registered the app in Firebase.io, created SHA256 key using keytools and added to the firebase and enabled the google login.
Added google-services.json to android/app directory.

Everytime i try to login, it is throwing this error, please help:

```<code>Error: A non-recoverable sign in failure occurred
at createErrorFromErrorData (NativeModules.js:146)
at NativeModules.js:95
at MessageQueue.__invokeCallback (MessageQueue.js:397)
at MessageQueue.js:127
at MessageQueue.__guard (MessageQueue.js:297)
at MessageQueue.invokeCallbackAndReturnFlushedQueue (MessageQueue.js:126)
at debuggerWorker.js:72
</code>```

答:
The SHA-1 key in the firebase console must be incorrect or not present.

To add this key navigate to android folder using following command

cd android

Run the 2 following command and copy the 2 SHA-1 keys.

keytool -list -v -keystore .\app\debug.keystore
  add your .keystore file path insted of .\app\debug.keystore and copy generated SHA-1 key and paste it as per step 3

and

./gradlew signingReport again copy generated SHA-1 key and paste it as per step 3.

Paste these SHA-1 keys on Firebase Console->Project Setting->your Apps->add fingureprint and paste the SHA-1 keys here

Body:
I'm using React-native-google-sigin package. I have followed the instructions and registered the app in Firebase.io, created SHA256 key using keytools and added to the firebase and enabled the google login.
Added google-services.json to android/app directory.

Everytime i try to login, it is throwing this error, please help:

Error: A non-recoverable sign in failure occurred
at createErrorFromErrorData (NativeModules.js:146)
at NativeModules.js:95
at MessageQueue.__invokeCallback (MessageQueue.js:397)
at MessageQueue.js:127
at MessageQueue.__guard (MessageQueue.js:297)
at MessageQueue.invokeCallbackAndReturnFlushedQueue (MessageQueue.js:126)
at debuggerWorker.js:72


问:
How to set fixed pods names in kubernetes
I want to maintain different configuration for each pod, so planning to fetch properties from spring cloud config based on pod name.

Ex:
Properties in cloud

PodName1.property1  = "xxx"
PodName2.property1   ="yyy";

Property value will be different for each pod. Planning to fetch properties from cloud ,based on container name  Environment.get("current pod name"+ " propertyName").

So I want to set fixed hostname/pod name

If the above is not possible, is there any alternative ?

答:
You can use statefulsets if you want fixed pod names for your application.
e.g.

```<code>apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: web # this will be used as prefix in pod name
spec:
  serviceName: "nginx"
  replicas: 2 # specify number of pods that should be running
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: k8s.gcr.io/nginx-slim:0.8
        ports:
        - containerPort: 80
          name: web
</code>```

This template will create 2 pods of nginx in default namespace with names as following:

```<code>kubectl get pods -l app=nginx
NAME      READY     STATUS    RESTARTS   AGE
web-0     1/1       Running   0          1m
web-1     1/1       Running   0          1m
</code>```

A basic example can be found here.

Body:
You can use statefulsets if you want fixed pod names for your application.
e.g.

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: web # this will be used as prefix in pod name
spec:
  serviceName: "nginx"
  replicas: 2 # specify number of pods that should be running
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: k8s.gcr.io/nginx-slim:0.8
        ports:
        - containerPort: 80
          name: web

This template will create 2 pods of nginx in default namespace with names as following:

kubectl get pods -l app=nginx
NAME      READY     STATUS    RESTARTS   AGE
web-0     1/1       Running   0          1m
web-1     1/1       Running   0          1m

A basic example can be found here.


问:
CSS not working with a div under form why is it happening?
```<code><form class="modal-content" id="bookingForm">

    <div class="formContainer">
      <div class="send" id="alert">
        Your Trip Has been Booked Sucessfully.
      </div>
      <h1>Booking Form</h1>
      <p>Please fill in this form to Book The Trip.</p>
</code>```

I am trying to add css to the "send" class to make it appear with green background when the form is submitted.
The Css id given below:

```<code>.send{
  text-align: center;
  padding: 10px;
  background: green;
  color: white;
  margin-bottom: 10px;
  display: none;
}
</code>```

But The CSS is not working. What Is The Cause Of It??

答:
You need to write JavaScript to change the display property value from 'none' to 'block' once the button inside form is clicked.
Here's the full code :

<!DOCTYPE html>

   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
   <link rel="stylesheet" href="style.css">

   <form class="modal-content" id="bookingForm">

               Your Trip Has been Booked Sucessfully.

Booking Form

Please fill in this form to Book The Trip.

       <button>Submit</button>
   </form>

```

Body:
<form class="modal-content" id="bookingForm">

        Your Trip Has been Booked Sucessfully.

Booking Form

Please fill in this form to Book The Trip.

I am trying to add css to the "send" class to make it appear with green background when the form is submitted.
The Css id given below:

.send{
  text-align: center;
  padding: 10px;
  background: green;
  color: white;
  margin-bottom: 10px;
  display: none;
}

But The CSS is not working. What Is The Cause Of It??

Body:
You need to write JavaScript to change the display property value from 'none' to 'block' once the button inside form is clicked.
Here's the full code :

<!DOCTYPE html>
<html lang="en">

<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
   <link rel="stylesheet" href="style.css">
</head>

<body>
   <form class="modal-content" id="bookingForm">

       <div class="formContainer">
           <div class="send" id="alert">
               Your Trip Has been Booked Sucessfully.
           </div>
           <h1>Booking Form</h1>
           <p>Please fill in this form to Book The Trip.</p>
       </div>
       <button>Submit</button>
   </form>
   <!-- <script src='./app.js'></script> -->
   <script>
       document.querySelector('button').addEventListener('click', (e) => showDiv(e));
       function showDiv(e) {
           e.preventDefault();
           document.querySelector('.send').style.display = 'block';
       }
   </script>
</body>


问:
How do I turn an observable set of two different types to a different third type observable in Typescript with rxjs?
So I have a problem of basically I am getting two different services of types Observable and Observable let's say.  They are returned by services and fine on initial load doing something like this (in a constructor of a component in Angular)

```<code>combineLatest([this.service.A(), this.service.B()])
  ).subscribe(([A, B]) => {
    this.C = A.map(x => {
        return {
           id: x.id,
           name: x.specificA
        };  //Different type of C
    }).concat(B.map(x => {
         return {
            id: x.id,
            name: x.specificB
       };
   });
</code>```

So this works when it is done on constructor and the view loads with my 'C' in this example and the world is right.  However I would like to call an update on the rows at times and go full circle back to my collection and then update.  I was thinking of doing a combineLatest but without a subscribe to get an observable on the component of something like C$: Observable.  Then make that object do all the work in subscriptions and further updates.  Then doing the

```<code>  this.C$ = ([this.service.A(), this.service.B()]).pipe(map( //this is wrong))
</code>```

Basically I don't want to subscribe to the observable but set it up from other observables, THEN subscribe to that.  Potentially do a combo with rxjs to take two observable types and make a third type.  Then when the event of an update happens kick off the subscribe of the 'C$' observable.  I know it is probably a simple operation I am just not getting that someone that is good at rxjs could tell me how to combine.

答:
Your first combineLatest seems almost as the solution.

Since the mapping operation for both types is different, first I would create an observable fore each type that maps them to the third type, and then merge them to single observable of the third type.

Let's go over it, assume I have these 3 types:

interface ModelA { aSpecific: string; }
interface ModelB { bSpecific: string; }
interface ModelC { id: string; }
```

<p>with these two <code>Observable</code>s of them:  </p>

<pre class="lang-js prettyprint-override"><code>const a$: Observable<ModelA[]> = of([{ aSpecific: "a-1" }, { aSpecific: "a-2" }]);
const b$: Observable<ModelB[]> = of([{ bSpecific: "b-1" }, { bSpecific: "b-2" }]);
</code>```

Now, create 2 Observables that maps to ModelC:

const mappedA$: Observable<ModelC[]> = a$.pipe(map(a => a.map(({ aSpecific: id }) => ({ id }))));

const mappedB$: Observable<ModelC[]> = b$.pipe(map(b => b.map(({ bSpecific: id }) => ({ id }))));
```

<p>Lastly, merge them with <code>combineLAtest</code> and <code>mergeAll</code> to unfold the first "array of arrays"</p>

<pre class="lang-js prettyprint-override"><code>const c$: Observable<ModelC[]> = combineLatest(mappedA$, mappedB$).pipe(
  mergeAll()
);
</code>```

You can find the full source code in this stackblitz

Body:
So I have a problem of basically I am getting two different services of types Observable and Observable let's say.  They are returned by services and fine on initial load doing something like this (in a constructor of a component in Angular)

combineLatest([this.service.A(), this.service.B()])
  ).subscribe(([A, B]) => {
    this.C = A.map(x => {
        return {
           id: x.id,
           name: x.specificA
        };  //Different type of C
    }).concat(B.map(x => {
         return {
            id: x.id,
            name: x.specificB
       };
   });

So this works when it is done on constructor and the view loads with my 'C' in this example and the world is right.  However I would like to call an update on the rows at times and go full circle back to my collection and then update.  I was thinking of doing a combineLatest but without a subscribe to get an observable on the component of something like C$: Observable.  Then make that object do all the work in subscriptions and further updates.  Then doing the

  this.C$ = ([this.service.A(), this.service.B()]).pipe(map( //this is wrong))

Basically I don't want to subscribe to the observable but set it up from other observables, THEN subscribe to that.  Potentially do a combo with rxjs to take two observable types and make a third type.  Then when the event of an update happens kick off the subscribe of the 'C$' observable.  I know it is probably a simple operation I am just not getting that someone that is good at rxjs could tell me how to combine.

Body:
Your first combineLatest seems almost as the solution.

Since the mapping operation for both types is different, first I would create an observable fore each type that maps them to the third type, and then merge them to single observable of the third type.

Let's go over it, assume I have these 3 types:

interface ModelA { aSpecific: string; }
interface ModelB { bSpecific: string; }
interface ModelC { id: string; }

with these two Observables of them:

const a$: Observable<ModelA[]> = of([{ aSpecific: "a-1" }, { aSpecific: "a-2" }]);
const b$: Observable<ModelB[]> = of([{ bSpecific: "b-1" }, { bSpecific: "b-2" }]);

Now, create 2 Observables that maps to ModelC:

const mappedA$: Observable<ModelC[]> = a$.pipe(map(a => a.map(({ aSpecific: id }) => ({ id }))));

const mappedB$: Observable<ModelC[]> = b$.pipe(map(b => b.map(({ bSpecific: id }) => ({ id }))));

Lastly, merge them with combineLAtest and mergeAll to unfold the first "array of arrays"

const c$: Observable<ModelC[]> = combineLatest(mappedA$, mappedB$).pipe(
  mergeAll()
);

You can find the full source code in this stackblitz


问:
Openstack nova mount volumes
I have one volume mounted as /vda, I created a new volume which is /vdb . Now when I mount this new volume I guess I can mount it to an existing directory on vda?? Hence growing the overall size of the existing directory ?? </p>

答:
@larsks is correct.  This is mostly an operating systems question, and it would be better to ask on another site like ServerFault or Unix or AskUbuntu.

But since you are here, and since you asked in the context of Openstack, I'll answer here.

Now when I mount this new volume I guess I can mount it to an existing directory on vda? Hence growing the overall size of the existing directory?

The short answer is No.  That's not how UNIX / Linux filesystems work.

When an Openstack Volume is attached to an Instance, it is viewed by the guest OS as a virtual disk device.  You then (typically) format it to contain a file system and mount the file system on top of a directory in the root file system.

(For a real physical disk, you normally partition the disk as well, and put the file systems into some of the partitions.  It is not normal practice to do that with an Volume.)

What you want here is a single file system that spans multiple Volumes; i.e. multiple virtual disks.  This is possible if you use Linux LVM (see https://opensource.com/business/16/9/linux-users-guide-lvm).  However, it is not possible to do an in-place conversion of an existing ordinary device into an LVM; see https://serverfault.com/questions/241987/convert-full-hard-drive-to-lvm-without-external-storage.

You probably need to do something like this:

Read all about LVM ... and decide if you can deal with the extra complexity.

Back up all your data!!

Attach your new Volume to the Instance.

Format it with LVM, and create a LVM volume on it and format the volume.

Mount the volume.

Copy the file system from your existing Volume into the new file system

Unmount file systems for the old volume and the new volume

Add the old volume into LVM and make it part of the existing LVM volume

Resize the file system so that it can use all of the space in the combined LVM volume.

Mount the file system.

If you have a file system split over two Volumes, your data integrity will depend on both of them.  I think you are better off either using the two Volumes as separate filesystems or creating a single large Volume.  Did you know that you can resize a Volume in some circumstances?

Title: Openstack nova mount volumes


问:
Configure SQS Dead letter Queue to raise a cloud watch alarm on receiving a message
I was working with Dead letter Queue in Amazon SQS. I want that whenever a new message is received by the queue it should raise a CloudWatch alarm. The problem is I configured an alarm on the metric: number_of_messages_sent of the queue but this metric don't work as expected in case of Dead letter Queues as mentioned in the Amazon SQS Dead-Letter Queues - Amazon Simple Queue Service documentation.

Now some suggestions on this were use number_of_messages_visible but I am not sure how to configure this in an alarm. So if i set that the value of this metric>0 then this is not same as getting a new message in the queue. If an old message is there then the metric value will always be >0. I can do some kind of mathematical expression to get the delta in this metric for some defined period (let's say a minute) but I am looking for some better solution.

答:
It is difficult to achieve what is being asked in the question. If the endpoint of cloudwatch alarm is to send Email or notify users about the DLQ message arrival you can do a similar thing with the help of SQS, SNS and Lambda. And from cloudwatch you can see how the DLQ messages grows on time whenever you receive any Email.

Create a SQS DLQ for an existing queue.

Create an SNS topic and subscribe the SNS topic to send Email.

Create a small lambda function which listens the SQS queue for an incoming messages, if there is any new incoming messages, send it to SNS. Since SNS is subscribed to Email you will get the Email whenever any new messages comes to SQS queue. Obviously the trigger for the lambda function is SQS and batch size is 1.

```<code>#!/usr/bin/python3
import json
import boto3
import os

def lambda_handler(event, context):
    batch_processes=[]
    for record in event['Records']:
        send_request(record["body"])

def send_request(body):
    # Create SNS client
    sns = boto3.client('sns')

    # Publish messages to the specified SNS topic
    response = sns.publish(
        TopicArn=#YOUR_TOPIC_ARN
        Message=body,
    )

    # Print out the response
    print(response)
</code>```

Body:
It is difficult to achieve what is being asked in the question. If the endpoint of cloudwatch alarm is to send Email or notify users about the DLQ message arrival you can do a similar thing with the help of SQS, SNS and Lambda. And from cloudwatch you can see how the DLQ messages grows on time whenever you receive any Email.

Create a SQS DLQ for an existing queue.

Create an SNS topic and subscribe the SNS topic to send Email.

Create a small lambda function which listens the SQS queue for an incoming messages, if there is any new incoming messages, send it to SNS. Since SNS is subscribed to Email you will get the Email whenever any new messages comes to SQS queue. Obviously the trigger for the lambda function is SQS and batch size is 1.

#!/usr/bin/python3
import json
import boto3
import os

def lambda_handler(event, context):
    batch_processes=[]
    for record in event['Records']:
        send_request(record["body"])

def send_request(body):
    # Create SNS client
    sns = boto3.client('sns')

    # Publish messages to the specified SNS topic
    response = sns.publish(
        TopicArn=#YOUR_TOPIC_ARN
        Message=body,
    )

    # Print out the response
    print(response)


问:
Debugging multithreaded applications
I have an application written in C++ and MFC which is multithreaded running on windows. Occasionally I do get some complaints such as deadlocks or an unhandled exception which is caused because of these threads. Normally I use visual studio (if the problem is reproducible) or else use the WinDbg to analyse the dump files generated. Is there any better way of doing this? Can  I use some other tools to do this?</p>

答:
I would recommend the Intel Thread Checker if you have enough budget for it. It does a great job of analysing running programs and alerting you to possible race conditions.

Check out the demonstration video for more info.

OwnerDisplayName: Naveen

ContentLicense: CC BY-SA 2.5

Title: Debugging multithreaded applications

LastEditorDisplayName: Jason S

OwnerDisplayName: Casey


问:
Finding Sub-Classes and Implementations
My favorite way to find subclasses of class 'X' or implementations of interface 'Y' has been to use Red Gate's Reflector.  But I'd like to know if there is a (free) way to do the same thing from VS 2010.  Does 2010 already have this ability?  Is there a plugin I can add?

The object browser, the place I might expect this feature to be found, does not seem to have this capability.  It can tell you about a parent type, but it does not tell you about derived types.

答:
While I've not found a RedGate Reflector level of functionality for this need, I have started using a partial solution.  Using the regex search capability in VS, I enter the following:

\:.@<place base class or interface here>

Example:

\:.@MyBase

Any derivative interface or class made from "MyBase," defined in the solution, will be returned.

Title: Finding Sub-Classes and Implementations


问:
Having ffmpeg add a repeating text overlay on a video
I'm looking to create an overlay that cycles through the characters in a string over and over. I've succeeded in using a sendcmd file to put A, B, C, D, E on the first 5 seconds of a video

```<code>0  drawtext reinit 'text=A';
1  drawtext reinit 'text=B';
2  drawtext reinit 'text=C';
3  drawtext reinit 'text=D';
4  drawtext reinit 'text=E';
</code>```

But it doesn't cycle and I haven't been able to find a way to make it, because sendcmd looks like it just takes a simple timecode. I could make a command file 3600 lines long for my hour video, with those commands in over and over (the command file would be generated programmatically so not onerous)

After some considerable experimenting I was able to do it with 5 separate drawtext:

```<code>drawtext=fontfile=/Windows/Fonts/bauhs93.ttf:fontsize=1024:fontcolor=white@0.1:bordercolor=black@0.1:borderw=10:r=250:text='A':x=if(trunc(mod(t\,5))\,-2000\,(w-tw)/2),
drawtext=fontfile=/Windows/Fonts/bauhs93.ttf:fontsize=1024:fontcolor=white@0.1:bordercolor=black@0.1:borderw=10:r=250:text='B':x=if(trunc(mod(t\,5))-1\,-2000\,(w-tw)/2),
drawtext=fontfile=/Windows/Fonts/bauhs93.ttf:fontsize=1024:fontcolor=white@0.1:bordercolor=black@0.1:borderw=10:r=250:text='C':x=if(trunc(mod(t\,5))-2\,-2000\,(w-tw)/2),
drawtext=fontfile=/Windows/Fonts/bauhs93.ttf:fontsize=1024:fontcolor=white@0.1:bordercolor=black@0.1:borderw=10:r=250:text='D':x=if(trunc(mod(t\,5))-3\,-2000\,(w-tw)/2),
drawtext=fontfile=/Windows/Fonts/bauhs93.ttf:fontsize=1024:fontcolor=white@0.1:bordercolor=black@0.1:borderw=10:r=250:text='E':x=if(trunc(mod(t\,5))-4\,-2000\,(w-tw)/2)
</code>```

But as can be seen, I have to repeat a lot of stuff here. Is there any slicker way? It does seem to have a noticeable effect on encoding speed the more chars are added

I was hoping that text expressions would help but it seems I can only return numerics from the values, so this expression didn't work out:

```<code>%{e:if(trunc(mod(t,5)),'A', '')%{e:if(trunc(mod(t,5))-1,'B', '') ...
</code>```

答: In the end I just created a text file containing thousands of sendcmd commands</p>

Body:
I'm looking to create an overlay that cycles through the characters in a string over and over. I've succeeded in using a sendcmd file to put A, B, C, D, E on the first 5 seconds of a video

0  drawtext reinit 'text=A';
1  drawtext reinit 'text=B';
2  drawtext reinit 'text=C';
3  drawtext reinit 'text=D';
4  drawtext reinit 'text=E';

But it doesn't cycle and I haven't been able to find a way to make it, because sendcmd looks like it just takes a simple timecode. I could make a command file 3600 lines long for my hour video, with those commands in over and over (the command file would be generated programmatically so not onerous)

After some considerable experimenting I was able to do it with 5 separate drawtext:

drawtext=fontfile=/Windows/Fonts/bauhs93.ttf:fontsize=1024:fontcolor=white@0.1:bordercolor=black@0.1:borderw=10:r=250:text='A':x=if(trunc(mod(t\,5))\,-2000\,(w-tw)/2),
drawtext=fontfile=/Windows/Fonts/bauhs93.ttf:fontsize=1024:fontcolor=white@0.1:bordercolor=black@0.1:borderw=10:r=250:text='B':x=if(trunc(mod(t\,5))-1\,-2000\,(w-tw)/2),
drawtext=fontfile=/Windows/Fonts/bauhs93.ttf:fontsize=1024:fontcolor=white@0.1:bordercolor=black@0.1:borderw=10:r=250:text='C':x=if(trunc(mod(t\,5))-2\,-2000\,(w-tw)/2),
drawtext=fontfile=/Windows/Fonts/bauhs93.ttf:fontsize=1024:fontcolor=white@0.1:bordercolor=black@0.1:borderw=10:r=250:text='D':x=if(trunc(mod(t\,5))-3\,-2000\,(w-tw)/2),
drawtext=fontfile=/Windows/Fonts/bauhs93.ttf:fontsize=1024:fontcolor=white@0.1:bordercolor=black@0.1:borderw=10:r=250:text='E':x=if(trunc(mod(t\,5))-4\,-2000\,(w-tw)/2)

But as can be seen, I have to repeat a lot of stuff here. Is there any slicker way? It does seem to have a noticeable effect on encoding speed the more chars are added

I was hoping that text expressions would help but it seems I can only return numerics from the values, so this expression didn't work out:

%{e:if(trunc(mod(t,5)),'A', '')%{e:if(trunc(mod(t,5))-1,'B', '') ...


问:
React: cant get output inside a functional component
I am having an Array of objects where I am trying to use reduce function to filter based on the keys of the object.
Here is the code for the whole project: CODE

If you check the index.js file inside the Exercises Folder:

```<code>{exercices_.map(([category, array]) => {
          <Typography>{category}</Typography>;
})}
</code>```

The exercices_ is a nested array that inside each array I have the category and another array.
For now I am just trying to output the category but it's not working. The same code works in the App.js file when I use console. But when I am passing the array to the child Componenet It doesnt work anymore. You are free to change the code through the website but notice that you are the only one who sees these changes.

The expected output is just a string Like Shoulders. Make sure to check the console of the webpage since it has all the output there.

答:
The problem is that you're not returning this  component on every iteration so it loops through it but the output array is empty.

A way to fix that:

```<code>{exercices_.map(([category, array]) => {
          return <Typography>{category}</Typography>;
})}
</code>```

Check out how .map function works here https://www.w3schools.com/jsref/jsref_map.asp

Body:
I am having an Array of objects where I am trying to use reduce function to filter based on the keys of the object.
Here is the code for the whole project: CODE

If you check the index.js file inside the Exercises Folder:

{exercices_.map(([category, array]) => {
          <Typography>{category}</Typography>;
})}

The exercices_ is a nested array that inside each array I have the category and another array.
For now I am just trying to output the category but it's not working. The same code works in the App.js file when I use console. But when I am passing the array to the child Componenet It doesnt work anymore. You are free to change the code through the website but notice that you are the only one who sees these changes.

The expected output is just a string Like Shoulders. Make sure to check the console of the webpage since it has all the output there.

Body:
The problem is that you're not returning this  component on every iteration so it loops through it but the output array is empty.

A way to fix that:

{exercices_.map(([category, array]) => {
          return <Typography>{category}</Typography>;
})}

Check out how .map function works here https://www.w3schools.com/jsref/jsref_map.asp


问:
Creating Custom URL Scheme in iOS using Objective C
I am working on custom URL scheme basically i am new with us functionality.

What i done before?

I implemented this successfully,i create simple url "myApp" now when i hit this url on safari like (myApp://) its launch my application.

My code

i used:

```<code>- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
</code>```

What i want?

Basically i want to implement two things that is:

when an user hit a link on safari if an application is installed on device,through that link application should launch.That point i already done successfully.

The second point which i can't done yet,after trying a lot but i couldn't found any solution yet,that is:

If an application is not installed on device that link should redirect to app store where user can installed application.

If it is possible,then please tell me how to do that,please refer me any link,example or your answer also help me.Thanks in advance

答:
In AppDelegate.m call this:

```<code>-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options;{
    NSLog(@"url recieved: %@", url);
    NSLog(@"query string: %@", [url query]);
    NSLog(@"host: %@", [url host]);
    NSLog(@"url path: %@", [url path]);
    NSDictionary *dict = [self parseQueryString:[url query]];
    NSLog(@"query dict: %@", dict);
    if ([[url host] isEqualToString:@"login"]) {
        [self setupHomeScreen:NO type:@"" entityId:@""];
        [self _endSession];
        return YES;
    } else if ([[url host] isEqualToString:@"smartoffice"]) {

        NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
        NSRange needle = [url.absoluteString rangeOfString:@"?" options:NSCaseInsensitiveSearch];
        NSString *data = nil;

        if(needle.location != NSNotFound) {
            NSUInteger start = needle.location + 1;
            NSUInteger end = [url.absoluteString length] - start;
            data = [url.absoluteString substringWithRange:NSMakeRange(start, end)];
        }

        for (NSString *param in [data componentsSeparatedByString:@"&"]) {
            NSArray *keyvalue = [param componentsSeparatedByString:@"="];
            if([keyvalue count] == 2){
                [result setObject:[keyvalue objectAtIndex:1] forKey:[keyvalue objectAtIndex:0]];
            }
        }
        NSString *entityID = ([result objectForKey:@"secondparameter"]);
        NSString *type = [result objectForKey:@"parameter"];
        [self setupHomeScreen:YES type:type entityId:entityID];
        //[self setupHomeScreen:YES type:@"TASK" entityId:@"160315"];
        return result;
    } else {
        NSLog(@"myApp is not installed");
        [self setupHomeScreen:NO type:@"0" entityId:@"0"];
    }
    return NO;
}
</code>```

Open Xcode, got to Project Settings -> Info, and add inside ‘The URL Types” section a new URL scheme.

That is the scheme ://resource. So we go ahead and type com.myApp://

Fo me its backofficeapp://

Now use this link on Safari

backofficeapp://smartoffice/1?parameter=TASK&secondparameter=157536

Where

parameter = “TASK”

secondparameter = “taskID”  // #iOS Mobile 2020 = 157536

This parameter is for landing on a specific screen.

Remember this URL won’t work if the app is not installed.

Body:
I am working on custom URL scheme basically i am new with us functionality.

What i done before?

I implemented this successfully,i create simple url "myApp" now when i hit this url on safari like (myApp://) its launch my application.

My code

i used:

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation

What i want?

Basically i want to implement two things that is:

when an user hit a link on safari if an application is installed on device,through that link application should launch.That point i already done successfully.

The second point which i can't done yet,after trying a lot but i couldn't found any solution yet,that is:

If an application is not installed on device that link should redirect to app store where user can installed application.

If it is possible,then please tell me how to do that,please refer me any link,example or your answer also help me.Thanks in advance

Body:
In AppDelegate.m call this:

-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options;{
    NSLog(@"url recieved: %@", url);
    NSLog(@"query string: %@", [url query]);
    NSLog(@"host: %@", [url host]);
    NSLog(@"url path: %@", [url path]);
    NSDictionary *dict = [self parseQueryString:[url query]];
    NSLog(@"query dict: %@", dict);
    if ([[url host] isEqualToString:@"login"]) {
        [self setupHomeScreen:NO type:@"" entityId:@""];
        [self _endSession];
        return YES;
    } else if ([[url host] isEqualToString:@"smartoffice"]) {

        NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
        NSRange needle = [url.absoluteString rangeOfString:@"?" options:NSCaseInsensitiveSearch];
        NSString *data = nil;

        if(needle.location != NSNotFound) {
            NSUInteger start = needle.location + 1;
            NSUInteger end = [url.absoluteString length] - start;
            data = [url.absoluteString substringWithRange:NSMakeRange(start, end)];
        }

        for (NSString *param in [data componentsSeparatedByString:@"&"]) {
            NSArray *keyvalue = [param componentsSeparatedByString:@"="];
            if([keyvalue count] == 2){
                [result setObject:[keyvalue objectAtIndex:1] forKey:[keyvalue objectAtIndex:0]];
            }
        }
        NSString *entityID = ([result objectForKey:@"secondparameter"]);
        NSString *type = [result objectForKey:@"parameter"];
        [self setupHomeScreen:YES type:type entityId:entityID];
        //[self setupHomeScreen:YES type:@"TASK" entityId:@"160315"];
        return result;
    } else {
        NSLog(@"myApp is not installed");
        [self setupHomeScreen:NO type:@"0" entityId:@"0"];
    }
    return NO;
}

Open Xcode, got to Project Settings -> Info, and add inside ‘The URL Types” section a new URL scheme.

That is the scheme ://resource. So we go ahead and type com.myApp://

Fo me its backofficeapp://

Now use this link on Safari

backofficeapp://smartoffice/1?parameter=TASK&secondparameter=157536

Where

parameter = “TASK”

secondparameter = “taskID”  // #iOS Mobile 2020 = 157536

This parameter is for landing on a specific screen.

Remember this URL won’t work if the app is not installed.


问:
How to plot two case1.hdf5 and case2.hdf5 files in matplotlib. Seeking help to correct the script
I have below script which only plots case1.hdf5 file.

I want to plot another case2.hdf5 file in  same script such that  I
get two overlapping plots.

Additionally, I want to use

Times New Roman fonts for labels and titles.

Insert Legends for both the plots.

Multiply Y-axis data with some constant number.

This script gives bottom three lines in a same colour but I want all
three in different solid colours  for case1.hdf5 and with same
colour and dashed for another case2.hdf5 file.

My script is here

```<code>import h5py
import matplotlib.pyplot as plt
import warnings
import matplotlib

warnings.filterwarnings("ignore") # Ignore all warnings

ticklabels=[r'$\Gamma$','F','Q','Z',r'$\Gamma$']

params = {
'mathtext.default': 'regular',
'axes.linewidth': 1.2,
'axes.edgecolor': 'Black',
}

plt.rcParams.update(params)
fig, ax = plt.subplots()

f = h5py.File('band.hdf5',  'r')
#print ('datasets are:')
print(list(f.keys()))

dist=f[u'distance']
freq=f[u'frequency']
kpt=f[u'path']

# Iterate over each segment
for i in range(len(dist)):
# Iteraton over each band
    for nbnd in range(len(freq[i][0])):
        x=[]
        y=[]

        for j in range(len(dist[i])):
            x.append(dist[i][j])
            y.append(freq[i][j][nbnd])
# First 3 bands are red
        if (nbnd<3):
            color='red'
        else:
            color='black'

        ax.plot(x, y, c=color, lw=2.0, alpha=0.8)

# Labels and axis limit and ticks
ax.set_ylabel(r'Frequency (THz)', fontsize=12)
ax.set_xlabel(r'Wave Vector (q)', fontsize=12)
ax.set_xlim([dist[0][0],dist[len(dist)-1][-1]])
xticks=[dist[i][0] for i in range(len(dist))]
xticks.append(dist[len(dist)-1][-1])
ax.set_xticks(xticks)
ax.set_xticklabels(ticklabels)
# Plot grid
ax.grid(which='major', axis='x', c='green', lw=2.5, linestyle='--', alpha=0.8)
# Save to pdf
plt.savefig('plots.pdf', bbox_inches='tight')
</code>```

You see, there is

First 3 bands are red

```<code>    if (nbnd<3):
        color='red'
</code>```

and instead of red I want all of these three in solid different colours and for case2.hdf5 in dashed lines with same colours.

答:
1. Colours

It sounds like in the first instance you want to map different colours to the first there bands of your data.

One way you might do this is to setup a colourmap and then apply it to those first three bands. Here I have just picked the default matplotlib colormap, but there are loads to choose from, so if the default doesn't work for you I would suggest checking out the post about choosing a colormap. In most use cases you should try to stick to a perceptually constant map.

2. Legend

This should just be a matter of calling ax.legend(). Although be wary when setting the position of the legend to be outside the bounds of the plot as you need to do some extra finicking when saving to pdf, as detailed here..

However you first need to add some labels to your plot, which in your case you would do inside your ax.plot() calls. I'm not sure what you are plotting, so can't tell you what labels would be sensible, but you may want something like: ax.plot(... label=f'band {nbnd}' if nbnd < 4 else None).

Notice the inline if. You are likely going to have a whole bunch of black bands that you don't want to label individually, so you likely want to only label the first and let the rest have label = None which means no bloated legend.

3. Scale Y

If you change the way you iterate through your data you should be able to capture the h5 dataset as something that behaves much like a numpy array. What I mean by that is you really only need two loops to index the data you want. freq[i, :, nbnd] should be a 1-d array that you want to set to y. You can multiply that 1-d array by some scale value

4.

import h5py
import matplotlib.pyplot as plt
import warnings
import matplotlib

warnings.filterwarnings("ignore") # Ignore all warnings

cmap = matplotlib.cm.get_cmap('jet', 4)

ticklabels=['A','B','C','D','E']

params = {
'mathtext.default': 'regular',
'axes.linewidth': 1.2,
'axes.edgecolor': 'Black',
'font.family' : 'serif'
}

#get the viridis cmap with a resolution of 3

#apply a scale to the y axis. I'm just picking an arbritrary number here
scale = 10
offset = 0 #set this to a non-zero value if you want to have your lines offset in a waterfall style effect

plt.rcParams.update(params)
fig, ax = plt.subplots()

f = h5py.File('band.hdf5',  'r')
#print ('datasets are:')
print(list(f.keys()))

dist=f[u'distance']
freq=f[u'frequency']
kpt=f[u'path']

lbl = {0:'AB', 1:'BC', 2:'CD', 3:'fourth'}

for i, section in enumerate(dist):
    for nbnd, _ in enumerate(freq[i][0]):
        x = section # to_list() you may need to convert sample to list.
        y = (freq[i, :, nbnd] + offset*nbnd) * scale

        if (nbnd<3):
            color=f'C{nbnd}'
        else:
            color='black'

        ax.plot(x, y, c=color, lw=2.0, alpha=0.8, label = lbl[nbnd] if nbnd < 3 and i == 0 else None)

ax.legend()

# Labels and axis limit and ticks
ax.set_ylabel(r'Frequency (THz)', fontsize=12)
ax.set_xlabel(r'Wave Vector (q)', fontsize=12)
ax.set_xlim([dist[0][0],dist[len(dist)-1][-1]])
xticks=[dist[i][0] for i in range(len(dist))]
xticks.append(dist[len(dist)-1][-1])
ax.set_xticks(xticks)
ax.set_xticklabels(ticklabels)
# Plot grid
ax.grid(which='major', axis='x', c='green', lw=2.5, linestyle='--', alpha=0.8)
# Save to pdf
plt.savefig('plots.pdf', bbox_inches='tight')
```

This script gives me the following image with the data you supplied

Body:
I have below script which only plots case1.hdf5 file.

I want to plot another case2.hdf5 file in  same script such that  I
get two overlapping plots.

Additionally, I want to use

Times New Roman fonts for labels and titles.

Insert Legends for both the plots.

Multiply Y-axis data with some constant number.

This script gives bottom three lines in a same colour but I want all
three in different solid colours  for case1.hdf5 and with same
colour and dashed for another case2.hdf5 file.

My script is here

import h5py
import matplotlib.pyplot as plt
import warnings
import matplotlib

warnings.filterwarnings("ignore") # Ignore all warnings

ticklabels=[r'$\Gamma$','F','Q','Z',r'$\Gamma$']

params = {
'mathtext.default': 'regular',
'axes.linewidth': 1.2,
'axes.edgecolor': 'Black',
}

plt.rcParams.update(params)
fig, ax = plt.subplots()

f = h5py.File('band.hdf5',  'r')
#print ('datasets are:')
print(list(f.keys()))

dist=f[u'distance']
freq=f[u'frequency']
kpt=f[u'path']

# Iterate over each segment
for i in range(len(dist)):
# Iteraton over each band
    for nbnd in range(len(freq[i][0])):
        x=[]
        y=[]

        for j in range(len(dist[i])):
            x.append(dist[i][j])
            y.append(freq[i][j][nbnd])
# First 3 bands are red
        if (nbnd<3):
            color='red'
        else:
            color='black'

        ax.plot(x, y, c=color, lw=2.0, alpha=0.8)

# Labels and axis limit and ticks
ax.set_ylabel(r'Frequency (THz)', fontsize=12)
ax.set_xlabel(r'Wave Vector (q)', fontsize=12)
ax.set_xlim([dist[0][0],dist[len(dist)-1][-1]])
xticks=[dist[i][0] for i in range(len(dist))]
xticks.append(dist[len(dist)-1][-1])
ax.set_xticks(xticks)
ax.set_xticklabels(ticklabels)
# Plot grid
ax.grid(which='major', axis='x', c='green', lw=2.5, linestyle='--', alpha=0.8)
# Save to pdf
plt.savefig('plots.pdf', bbox_inches='tight')

You see, there is

First 3 bands are red

    if (nbnd<3):
        color='red'

and instead of red I want all of these three in solid different colours and for case2.hdf5 in dashed lines with same colours.

Body:
1. Colours

It sounds like in the first instance you want to map different colours to the first there bands of your data.

One way you might do this is to setup a colourmap and then apply it to those first three bands. Here I have just picked the default matplotlib colormap, but there are loads to choose from, so if the default doesn't work for you I would suggest checking out the post about choosing a colormap. In most use cases you should try to stick to a perceptually constant map.

2. Legend

This should just be a matter of calling ax.legend(). Although be wary when setting the position of the legend to be outside the bounds of the plot as you need to do some extra finicking when saving to pdf, as detailed here..

However you first need to add some labels to your plot, which in your case you would do inside your ax.plot() calls. I'm not sure what you are plotting, so can't tell you what labels would be sensible, but you may want something like: ax.plot(... label=f'band {nbnd}' if nbnd < 4 else None).

Notice the inline if. You are likely going to have a whole bunch of black bands that you don't want to label individually, so you likely want to only label the first and let the rest have label = None which means no bloated legend.

3. Scale Y

If you change the way you iterate through your data you should be able to capture the h5 dataset as something that behaves much like a numpy array. What I mean by that is you really only need two loops to index the data you want. freq[i, :, nbnd] should be a 1-d array that you want to set to y. You can multiply that 1-d array by some scale value

4.

import h5py
import matplotlib.pyplot as plt
import warnings
import matplotlib

warnings.filterwarnings("ignore") # Ignore all warnings

cmap = matplotlib.cm.get_cmap('jet', 4)

ticklabels=['A','B','C','D','E']

params = {
'mathtext.default': 'regular',
'axes.linewidth': 1.2,
'axes.edgecolor': 'Black',
'font.family' : 'serif'
}

#get the viridis cmap with a resolution of 3

#apply a scale to the y axis. I'm just picking an arbritrary number here
scale = 10
offset = 0 #set this to a non-zero value if you want to have your lines offset in a waterfall style effect

plt.rcParams.update(params)
fig, ax = plt.subplots()

f = h5py.File('band.hdf5',  'r')
#print ('datasets are:')
print(list(f.keys()))

dist=f[u'distance']
freq=f[u'frequency']
kpt=f[u'path']

lbl = {0:'AB', 1:'BC', 2:'CD', 3:'fourth'}

for i, section in enumerate(dist):
    for nbnd, _ in enumerate(freq[i][0]):
        x = section # to_list() you may need to convert sample to list.
        y = (freq[i, :, nbnd] + offset*nbnd) * scale

        if (nbnd<3):
            color=f'C{nbnd}'
        else:
            color='black'

        ax.plot(x, y, c=color, lw=2.0, alpha=0.8, label = lbl[nbnd] if nbnd < 3 and i == 0 else None)

ax.legend()

# Labels and axis limit and ticks
ax.set_ylabel(r'Frequency (THz)', fontsize=12)
ax.set_xlabel(r'Wave Vector (q)', fontsize=12)
ax.set_xlim([dist[0][0],dist[len(dist)-1][-1]])
xticks=[dist[i][0] for i in range(len(dist))]
xticks.append(dist[len(dist)-1][-1])
ax.set_xticks(xticks)
ax.set_xticklabels(ticklabels)
# Plot grid
ax.grid(which='major', axis='x', c='green', lw=2.5, linestyle='--', alpha=0.8)
# Save to pdf
plt.savefig('plots.pdf', bbox_inches='tight')

This script gives me the following image with the data you supplied


问:
I am unable to request data from two table on typegraphql type-orm
I am making a graphQl API using TypeGraphQl with Postgress Database and TypeORM.

I am these two tables (shortened)

User

```<code>@ObjectType()
@Entity()
export class User extends BaseEntity {

  @Field()
  @PrimaryGeneratedColumn('uuid')
  id!: string;

  @OneToMany(() => Article, (article: Article) => article.author)
  public articles: Article[];
</code>```

And Articles written by user

```<code>@ObjectType()
@Entity()
export class Article extends BaseEntity{
  @Field()
  @PrimaryGeneratedColumn('uuid')
  articleId!: string;

  @ManyToOne(() => User, (author: User) => author.articles)
  author: User;
</code>```

Problem
I am unable to make a query that would typically return the related info, in other words, one query that returns both an article and the user who wrote the article.

Resolvers
Article

```<code>Resolver(() => Article);
export class ArticleResolver {
  @Query(() => [Article])
  public async getArticles() {
    const articles = await Article.find();
    return articles;
  }
</code>```

User

```<code>Resolver(() => User);
export class RegisterResolver {
  @Query(() => [User])
  public async getUsers() {
    const users = await User.find();
    return users;
  }
</code>```

This query gets the articles successfully

```<code>{

  getArticles{
    articleId
    title
    cells

  }
}
</code>```

I want to make a query that also gets the author, and vice-versa for the Users I get the articles he had written.

From what I searched, this should be the query, but it is not recognized in the playground

```<code>{

  getArticles{
    articleId
    title
    cells
    author{
      lastName
    }
  }
}
</code>```

I know that I should use Field() decorator to make those requests. But I am getting this error if I add it Error: You need to provide explicit type for Article#author ! because of the ORM
Is there a way to configure Field() decorator to make it work? Or am writing the query wrongly?

答:
You need to write field resolvers that resolve the relation between article and author by using TypeORM repository.

You can see some examples in the repo:
https://github.com/MichalLytek/type-graphql/blob/master/examples/typeorm-basic-usage/resolvers/recipe-resolver.ts#L65-L76

Body:
I am making a graphQl API using TypeGraphQl with Postgress Database and TypeORM.

I am these two tables (shortened)

User

@ObjectType()
@Entity()
export class User extends BaseEntity {

  @Field()
  @PrimaryGeneratedColumn('uuid')
  id!: string;

  @OneToMany(() => Article, (article: Article) => article.author)
  public articles: Article[];

And Articles written by user

@ObjectType()
@Entity()
export class Article extends BaseEntity{
  @Field()
  @PrimaryGeneratedColumn('uuid')
  articleId!: string;

  @ManyToOne(() => User, (author: User) => author.articles)
  author: User;

Problem
I am unable to make a query that would typically return the related info, in other words, one query that returns both an article and the user who wrote the article.

Resolvers
Article

Resolver(() => Article);
export class ArticleResolver {
  @Query(() => [Article])
  public async getArticles() {
    const articles = await Article.find();
    return articles;
  }

User

Resolver(() => User);
export class RegisterResolver {
  @Query(() => [User])
  public async getUsers() {
    const users = await User.find();
    return users;
  }

This query gets the articles successfully

{

  getArticles{
    articleId
    title
    cells

  }
}

I want to make a query that also gets the author, and vice-versa for the Users I get the articles he had written.

From what I searched, this should be the query, but it is not recognized in the playground

{

  getArticles{
    articleId
    title
    cells
    author{
      lastName
    }
  }
}

I know that I should use Field() decorator to make those requests. But I am getting this error if I add it Error: You need to provide explicit type for Article#author ! because of the ORM
Is there a way to configure Field() decorator to make it work? Or am writing the query wrongly?


问:
HTML5 + Javascript: Networking for a game
I noticed I'm getting tired of trying to make games with high level programming languages like C#, using OpenTK. C or C++ stills looks a little out of range for my humble self. I just got the sudden urge to get back to some web development and try to make a browser game - in pure HTML5+JS of course!

And while I think I can figure out the canvas myself sooner or later, with the help of ze internetz, I just don't quite know how I should handle networking.

WebSockets seem interesting, but are they the right way to go, seeing as they're still pretty undeveloped? AJAX sounds a little slow and bulky. I don't plan to make a game that requires very low latency, but I do want to keep it low enough to play smoothly.

What would you suggest?

答:
for the networking code you might want to try working with an existing framework like union platform. here's a multiuser drawing app written in pure js/html5 without websockets:

http://www.unionplatform.com/?page_id=2762

it's also worth looking at www.socket.io. socket.io provides a raw websocket wrapper with xhr failover, but no higher-level apis (e.g., no rooms, no users, no accounts, no data sharing/management for things like scores, etc).

colin


问:
Django filter by two parameters
I want to filter by two parameters. I have this:

```<code>    def get_queryset(self):
        queryset = Product.objects.filter(
             Q(category__in=self.request.GET.getlist("category")) &
             Q(brand__in=self.request.GET.getlist("brand")))
        return queryset
</code>```

But this works only if two filters are chosen(otherwise it returns nothing). I want my program to filter by one filter if only one is chosen and filter by two parameters if two are chosen. How can I do that?

答:
```<code>def get_queryset(self):
    queryset = Product.objects.all()
    if "category" in self.request.GET:
        queryset = queryset.filter(category__in=self.request.GET.getlist("category"))
    if "brand" in self.request.GET:
        queryset = queryset.filter(brand__in=self.request.GET.getlist("brand"))
    return queryset
</code>```

Most methods applied to a queryset will return a new queryset. This allows you to add more parameters as required. As the queryset is lazy, it doesn't actually query the database until you start consuming data so there's no performance overhead to the above either.

Title: Django filter by two parameters

Body:
I want to filter by two parameters. I have this:

    def get_queryset(self):
        queryset = Product.objects.filter(
             Q(category__in=self.request.GET.getlist("category")) &
             Q(brand__in=self.request.GET.getlist("brand")))
        return queryset

But this works only if two filters are chosen(otherwise it returns nothing). I want my program to filter by one filter if only one is chosen and filter by two parameters if two are chosen. How can I do that?

Body:
def get_queryset(self):
    queryset = Product.objects.all()
    if "category" in self.request.GET:
        queryset = queryset.filter(category__in=self.request.GET.getlist("category"))
    if "brand" in self.request.GET:
        queryset = queryset.filter(brand__in=self.request.GET.getlist("brand"))
    return queryset

Most methods applied to a queryset will return a new queryset. This allows you to add more parameters as required. As the queryset is lazy, it doesn't actually query the database until you start consuming data so there's no performance overhead to the above either.


问:
Why Quartz scheduler's unscheduleJob is deleting both trigger and job detail?
Im trying to execute the following quartz scheduler code in the a cluster environment.

```<code>scheduler.unscheduleJob("genericJobTrigger", "DEFAULT");
</code>```

where as

```<code>Scheduler scheduler = (Scheduler) context.getBean("scheduler");
JobDetail genericJob = (JobDetail) context.getBean("genericJob");
CronTrigger genericJobTrigger = (CronTrigger) context.getBean("genericJobTrigger");
</code>```

Above piece of code is deleting entries from trigger and job detail. It supposed to remove only trigger right?

Why Quartz scheduler's unscheduleJob is deleting both trigger and job detail?

答:
Whenever you are creating an object of JobDetail then set storeDurably(), refer the below example:

```<code>return JobBuilder.newJob(ScheduledJob.class)
                .setJobData(jobDataMap)
                .withDescription("job executes at specified frequency")
                .withIdentity(UUID.randomUUID().toString(), "email-jobs")
                .storeDurably() //This will not allow to delete automatially
                .build();
</code>```

Also you can verify it by checking the value of IS_DURABLE column in jobDetails table.

Body:
Im trying to execute the following quartz scheduler code in the a cluster environment.

scheduler.unscheduleJob("genericJobTrigger", "DEFAULT");

where as

Scheduler scheduler = (Scheduler) context.getBean("scheduler");
JobDetail genericJob = (JobDetail) context.getBean("genericJob");
CronTrigger genericJobTrigger = (CronTrigger) context.getBean("genericJobTrigger");

Above piece of code is deleting entries from trigger and job detail. It supposed to remove only trigger right?

Why Quartz scheduler's unscheduleJob is deleting both trigger and job detail?

Body:
Whenever you are creating an object of JobDetail then set storeDurably(), refer the below example:

return JobBuilder.newJob(ScheduledJob.class)
                .setJobData(jobDataMap)
                .withDescription("job executes at specified frequency")
                .withIdentity(UUID.randomUUID().toString(), "email-jobs")
                .storeDurably() //This will not allow to delete automatially
                .build();

Also you can verify it by checking the value of IS_DURABLE column in jobDetails table.


答:
You forgot to return, you also need to add a key when using an array of React elements</p>

```<code>{exercices_.map(([category, array], index) => {
          return <Typography key={index}>{category}</Typography>;
})}
</code>```

Title: React: cant get output inside a functional component

Body:
You forgot to return, you also need to add a key when using an array of React elements

{exercices_.map(([category, array], index) => {
          return <Typography key={index}>{category}</Typography>;
})}


问:
Read from firebase database and store the data, return values to be used in other pages
I first try to get the data from firebase, then call a function to update the outer variable (setdata). The function however creates a local variable and doesnt update the outer one.

I was wondering how I can update the outer variable?

```<code>import * as firebase from 'firebase';

function userData() {
  var userInfo

  firebase.auth().onAuthStateChanged(user => {
    if (user) {
      getUserData(user.uid)
    }
  })

  function getUserData(uid) {
    firebase
     .database()
     .ref('users/' + uid)
     .once("value")
     .then(function (snapshot){
        setData(snapshot.val())
      })
  }

  function setData(data){
    userInfo.name = data.name;
    userInfo.username = data.username;
  }

  return({ nameOf: userInfo.name, usernameOf: userInfo.username});
}

export default userInformation = {
  name: userData().nameOf,
  username: userData.usernameOf,
}
</code>```

答:
I think the problem is in the way you handled it. Please try this way and let me know if it worked. It should work...

userData.js

```<code>export default function userData() {
  return firebase.auth().onAuthStateChanged((user) => {
    if (user) {
      return getUserData(user.uid);
    }
  });

  function getUserData(uid) {
    return firebase
      .database()
      .ref('users/' + uid)
      .once('value')
      .then(function (snapshot) {
        const data = snapshot.val();
        return { name: data.name, username: data.username };
      });
  }
}
</code>```

When you want to use the above function,

```<code>import userData from 'path/to/userData/js';

const userInformation = userData();
</code>```

Body:
I first try to get the data from firebase, then call a function to update the outer variable (setdata). The function however creates a local variable and doesnt update the outer one.

I was wondering how I can update the outer variable?

import * as firebase from 'firebase';

function userData() {
  var userInfo

  firebase.auth().onAuthStateChanged(user => {
    if (user) {
      getUserData(user.uid)
    }
  })

  function getUserData(uid) {
    firebase
     .database()
     .ref('users/' + uid)
     .once("value")
     .then(function (snapshot){
        setData(snapshot.val())
      })
  }

  function setData(data){
    userInfo.name = data.name;
    userInfo.username = data.username;
  }

  return({ nameOf: userInfo.name, usernameOf: userInfo.username});
}

export default userInformation = {
  name: userData().nameOf,
  username: userData.usernameOf,
}

Body:
I think the problem is in the way you handled it. Please try this way and let me know if it worked. It should work...

userData.js

export default function userData() {
  return firebase.auth().onAuthStateChanged((user) => {
    if (user) {
      return getUserData(user.uid);
    }
  });

  function getUserData(uid) {
    return firebase
      .database()
      .ref('users/' + uid)
      .once('value')
      .then(function (snapshot) {
        const data = snapshot.val();
        return { name: data.name, username: data.username };
      });
  }
}

When you want to use the above function,

import userData from 'path/to/userData/js';

const userInformation = userData();


问:
GA-100% pageviews are not being sent for page load sample
We have updated Google Analytics sampling rate to 100% for many partners.

```<code>ga('create', 'UA-xxxxxxxxx-x', {'siteSpeedSampleRate': 100});
</code>```

However, for some partners, we observed that all pageviews are not set for page load sampling. In some cases, it is around 80%.

Is there any exact reason for this? Doesn't {'siteSpeedSampleRate': 100} means all pageviews should be sent for page load sampling?

Thanks!

答:
Even if you put the sampling rate to 100 you can still hit quota limits here (Site Speed processing quota limit).

https://developers.google.com/analytics/devguides/collection/analyticsjs/user-timings#sampling_considerations

To measure all the site speed hits you can extract the values (different load times) via GTM and some custom javascript and send the values as dimensions or events.

Body:
We have updated Google Analytics sampling rate to 100% for many partners.

ga('create', 'UA-xxxxxxxxx-x', {'siteSpeedSampleRate': 100});

However, for some partners, we observed that all pageviews are not set for page load sampling. In some cases, it is around 80%.

Is there any exact reason for this? Doesn't {'siteSpeedSampleRate': 100} means all pageviews should be sent for page load sampling?

Thanks!