问:
Passing the interface of a class throws errors but passing just the class works fine
I have two classes:

DefectsController

```<code>public abstract class DefectsController<TDefect, TDefectService> :
    ApplicationController<DefectsController<TDefect, TDefectService>, TDefect>
    where TDefectService : IEntityService<TDefect>
    where TDefect : Defect
{
    private readonly TDefectService defectService;

    public DefectsController(TDefectService defectService)
        : base(defectService)
    {
        this.defectService = defectService;
    }
}
</code>```

and JobDefectsController (there are other parts as well, these are just examples)

```<code>public class JobDefectsController : DefectsController<JobDefect, IEntityService<JobDefect>>
{
    public JobDefectsController(EntityService<JobDefect> service)
        : base(service)
    {
    }
}
</code>```

For some reason if I change JobDefectsController's constructor to using IEntityService instead then if I try to access defectService in the DefectsController it throws unknown errors.

Edit: This error: The number of generic arguments provided doesn't equal the arity of the generic type definition.

Parameter name: instantiation

There used to be a class called JobDefectsService which inherited from IEntityService<JobDefect> and the interface of that (IJobDefectService) could be used in place of both IEntityService<JobDefect> and EntityService<JobDefect> without problems.

Anyone have any clue to what the problem could be?

Thanks,

Harold

答:
Your constructor parameter and your second class parameter need to be the same type. I.e. TDefectService .

If you want to use the interface then your concrete class should be defined as follows...

```<code>public class JobDefectsController : DefectsController<JobDefect, IEntityService<JobDefect>>
{
    public JobDefectsController(IEntityService<JobDefect> service)
        : base(service)
    {
    }
}
</code>```

To use the concrete class then you need to do this...

```<code>public class JobDefectsController : DefectsController<JobDefect, EntityService<JobDefect>>
{
    public JobDefectsController(EntityService<JobDefect> service)
        : base(service)
    {
    }
}
</code>```

Body:
I have two classes:

DefectsController

public abstract class DefectsController<TDefect, TDefectService> :
    ApplicationController<DefectsController<TDefect, TDefectService>, TDefect>
    where TDefectService : IEntityService<TDefect>
    where TDefect : Defect
{
    private readonly TDefectService defectService;

    public DefectsController(TDefectService defectService)
        : base(defectService)
    {
        this.defectService = defectService;
    }
}

and JobDefectsController (there are other parts as well, these are just examples)

public class JobDefectsController : DefectsController<JobDefect, IEntityService<JobDefect>>
{
    public JobDefectsController(EntityService<JobDefect> service)
        : base(service)
    {
    }
}

For some reason if I change JobDefectsController's constructor to using IEntityService instead then if I try to access defectService in the DefectsController it throws unknown errors.

Edit: This error: The number of generic arguments provided doesn't equal the arity of the generic type definition.

Parameter name: instantiation

There used to be a class called JobDefectsService which inherited from IEntityService<JobDefect> and the interface of that (IJobDefectService) could be used in place of both IEntityService<JobDefect> and EntityService<JobDefect> without problems.

Anyone have any clue to what the problem could be?

Thanks,

Harold

Body:
Your constructor parameter and your second class parameter need to be the same type. I.e. TDefectService .

If you want to use the interface then your concrete class should be defined as follows...

public class JobDefectsController : DefectsController<JobDefect, IEntityService<JobDefect>>
{
    public JobDefectsController(IEntityService<JobDefect> service)
        : base(service)
    {
    }
}

To use the concrete class then you need to do this...

public class JobDefectsController : DefectsController<JobDefect, EntityService<JobDefect>>
{
    public JobDefectsController(EntityService<JobDefect> service)
        : base(service)
    {
    }
}


来源: stackexchange

问:
Sticky element to top on scroll
I am trying to make my div appear at the top when the user scrolls down the page, and once the user scrolls to the top, the element should not overlap the nav bar.

I am struggling to implement this, so help would be appreciated. This is what I have tried:

```<code> <div id="floating-sidebar-sticky-wrapper" class="floating-sidebar-wrap" style="height: 696px;">
 <div id="floating-sidebar"></div>
</div>

 <script>
    $(window).on('load',function(){
      $("#floating-sidebar").sticky({ topSpacing: 0, wrapperClassName: "floating-sidebar-wrap" });
    });
  </script>
</code>```

答:
You don't need any javascript or even jquery to do that.

Try the Sticky CSS position

.top-nav {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  background:black;
  color: white;
  line-height: 2em;
}
div.sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 2em;
  background-color: #ccc;
  padding: 5px;
  font-size: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="top-nav">Top nav</div>
<div class="">
<h2>Sticky Element: Scroll Down to See the Effect</h2>
<p>Scroll down this page to see how  sticky positioning works.</p>
<div class="sticky">I will stick to the screen when you reach my scroll position</div>

<p>Some example text..</p>
<h2>Scroll back up again to "remove" the sticky position.</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis.</p>
<div class="sticky" style="background:red">I will stick to the screen when you reach my scroll position</div>
<h2>Scroll back up again to "remove" the sticky position.</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis.</p>
<h2>Scroll back up again to "remove" the sticky position.</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis.</p>
</div></code>```

ContentLicense: CC BY-SA 4.0

Title: Sticky element to top on scroll

Body:
You don't need any javascript or even jquery to do that.

Try the Sticky CSS position

.top-nav {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  background:black;
  color: white;
  line-height: 2em;
}
div.sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 2em;
  background-color: #ccc;
  padding: 5px;
  font-size: 20px;
}

<div class="top-nav">Top nav</div>
<div class="">
<h2>Sticky Element: Scroll Down to See the Effect</h2>
<p>Scroll down this page to see how  sticky positioning works.</p>
<div class="sticky">I will stick to the screen when you reach my scroll position</div>

<p>Some example text..</p>
<h2>Scroll back up again to "remove" the sticky position.</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis.</p>
<div class="sticky" style="background:red">I will stick to the screen when you reach my scroll position</div>
<h2>Scroll back up again to "remove" the sticky position.</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis.</p>
<h2>Scroll back up again to "remove" the sticky position.</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis.</p>
</div>


问:
Conditionally insert a line in JSON array like file with awk
I want to push items with awk to a myArray.json file like so

```<code>[
 item1,
 item2
]
</code>```

To add item1 I tried

```<code>echo -e "[\n]" > myArray.json # Create an empty JSON array with "\n"
awk -v var="item1" '/\]/ {print var} 1' myArray.json >> myArray-tmp.json
mv myArray-tmp.json myArray.json
</code>```

If I now comment out echo -e "[\n]" > myArray.json line (or conditionally skip it), set var="item2" and run the script, item2 is added to the array. I want to add a comma after first line, but not second.

答:
jq is a great tool so I upvoted and accepted answer. Here's my ugly way.

```<code>[
 item1
 ,item2
]
</code>```

I needed to do conditional to skip first two lines after first item has been added. Run this line instead.

```<code>awk -v var="item2" '/\]/ {print ","var} 1' myArray.json >> myArray-tmp.json
</code>```

Body:
I want to push items with awk to a myArray.json file like so

[
 item1,
 item2
]

To add item1 I tried

echo -e "[\n]" > myArray.json # Create an empty JSON array with "\n"
awk -v var="item1" '/\]/ {print var} 1' myArray.json >> myArray-tmp.json
mv myArray-tmp.json myArray.json

If I now comment out echo -e "[\n]" > myArray.json line (or conditionally skip it), set var="item2" and run the script, item2 is added to the array. I want to add a comma after first line, but not second.

Body:
jq is a great tool so I upvoted and accepted answer. Here's my ugly way.

[
 item1
 ,item2
]

I needed to do conditional to skip first two lines after first item has been added. Run this line instead.

awk -v var="item2" '/\]/ {print ","var} 1' myArray.json >> myArray-tmp.json


问:
Java Spark application logs through logger is not showing in EMR log
I have a Spark java application running on an EMR. When I am trying to run the spark job locally logging into the EMR EC2 instance i am getting my Logger info from the java application on the console.

/usr/lib/spark/bin/spark-submit --class com.myproject.MyMainSparkClass --conf 'spark.driver.extraJavaOptions=-Dcong.parameters=somepropertiesparameter' --conf 'spark.executor.extraJavaOptions=-Dcong.parameters=somepropertiesparameter' --master local s3://myJarS3Location/myjar.jar

on console my logger info: 19/05/29 01:50:11 INFO DataTransforFileProcessUtility: ############ Job started at :2019-05-29 01:50:11.391 ############

Where as when i use the cluster mode :

/usr/lib/spark/bin/spark-submit --deploy-mode cluster --master yarn --class com.myproject.MyMainSparkClass --conf 'spark.driver.extraJavaOptions=-Dcong.parameters=somepropertiesparameter' --conf 'spark.executor.extraJavaOptions=-Dcong.parameters=somepropertiesparameter' s3://myJarS3Location/myjar.jar

I am not able to get the logger info from my application on my console. If i execute the cluster mode command as a step on EMR still i m not finding the application logger info in any of the log files. Does the application logger info gets logged anywhere if we run on cluster mode with Yarn?

答:
When you use cluster mode, you should go to Yarn Resourcemanager  or Spark History Server to get your application log;

In my case(cloudera CDH):
 - Yarn RM:  http:${your_yarn_resourcemanager_host}:8088/cluster
 - Spark History Server:  http:${your_spark_history_server_host}:18088


问:
HTTPS redirect issue
I need to force all request to HTTPS rather than HTTP.

For that I have added the following code in to my .htaccess as can be seen below:

```<code>RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

This URL is forced to HTTPS: http://localhost/test

but this URL is not forced to HTTPS: http://localhost/test/public/assets/css/custom.css

答:
This is straight from the Apache documentation:

```<code>RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
</code>```

It doesn't look much different than yours but perhaps the minor changes will make a difference with your specific issue.

ContentLicense: CC BY-SA 3.0

Title: HTTPS redirect issue

Body:
I need to force all request to HTTPS rather than HTTP.

For that I have added the following code in to my .htaccess as can be seen below:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

This URL is forced to HTTPS: http://localhost/test

but this URL is not forced to HTTPS: http://localhost/test/public/assets/css/custom.css

Body:
This is straight from the Apache documentation:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

It doesn't look much different than yours but perhaps the minor changes will make a difference with your specific issue.


问:
Using GPS to measure area
Hey guys, I'm researching something for a friend of mine who's involved in road construction. He needs some sort of a device that he can use to measure distance or area between points. I have done some GPS programming in the past but for mobile devices and i wasn't too impressed with accuracy. That was quite a few years ago and i think the technology has improved, however i am not sure what device i should as the receiver. Since a mobile device would probably be out of the question because i'd need to be able to run my custom application on it, something that hooks up through a USB port would maybe work? I found u-blox PCI hard that works with laptops and PCs. Has anyone on here had any experience with it? Perhaps there are other devices i'd need to look into?

I appreciate any help i can get on this. Thank you.

答: You could use a mobile device that has GPS and the ability to run your custom software like the iphone, google phones, and probably a lot of other smart phones.</p>

OwnerDisplayName: Sergey

LastEditorDisplayName: nzpcmad

ContentLicense: CC BY-SA 2.5

Title: Using GPS to measure area

OwnerDisplayName: DasBoot


问:
I am not able to remove elements from the list
The task that I have to do is showing all other elements rather than (Americano). I tried to use 'Record.remove("Americano") but it shows the error

```<code>Record.remove("Americano")
ValueError: list.remove(x): x not in list
</code>```

What should I Do......

=========================this is the result of=======================     Record.append(record[1]) print(Record) ->

```<code>['Menu_name', 'Cafe_latte', 'Americano', 'Americano', 'Smoothie_queen', 'Americano', 'Americano', 'Cafe_mocha', 'Cafe_latte', 'Americano', 'Amorparty', 'Plain_yogurt', 'Americano', 'Americano', 'Cafe_mocha', 'Berry_smoothie', 'Cafe_mocha', 'Cafe_latte', 'Americano', 'Cafe_latte', 'Berry_smoothie', 'Berry_smoothie', 'Plain_yogurt', 'Berry_smoothie', 'Plane_yougurt', 'Berry_smoothie', 'Cafe_latte', 'Americano', 'Americano', 'Cafe_mocha', 'Plain_yogurt', 'Americano', 'Plain_yogurt', 'Cafe_mocha', 'Plain_yogurt', 'Americano', 'Cofe_latte', 'Plain_yogurt', 'Cafe_mocha', 'Americano', 'Berry_smoothie', 'Cafe_latte', 'Cafe_latte', 'Cafe_mocha', 'Cafe_latte', 'Cafe_latte', 'Cafe_mocha', 'Americano', 'Plain_yogurt', 'Americano', 'Americano', 'Cofe_latte', 'Berry_smoothie', 'Berry_smudie', 'American_air', 'Plain_yogurt', 'Berry_smoothie', 'Berry_smoothie', 'Berry_smoothie', 'Cafe_latte', 'Americano', 'Plain_yogurt', 'Cafe_latte', 'Cafe_mocha', 'Cafe_mocha', 'Plain_yogurt', 'Berry_smoothie', 'Berry_smoothie', 'Cafe_mocha', 'Cafe_mocha', 'Berry_smoothie', 'Cafe_mocha', 'Plain_yogurt']
</code>```

```<code>def load_menu():
    Menu = []
    #========= STEP 1 ==========
    menufile = open("menu.txt", "r")

    for line in menufile:
        menu = line.split()
        Menu.append(menu)

    menufile.close()

    for menu in Menu:
        print(menu[0]," : ",menu[1])
    #========= STEP 1 ==========
    return Menu

def error_check(date):
    #========= STEP 3 ==========
    Record = []
    recordfile = open("ledger_"+date+".txt","r")

    for line in recordfile:
        record = line.split()
        Record.append(record[1])
        Record.remove("Americano")
    print(Record)

    recordfile.close()
    #========= STEP 3 ==========
</code>```

答:
You should check if "Americano" in list before remove the element:</p>

```<code>def error_check(date):
    #========= STEP 3 ==========
    Record = []
    recordfile = open("ledger_"+date+".txt","r")

for line in recordfile:
    record = line.split()
    Record.append(record[1])
    if "Americano" in Record:
        Record.remove("Americano")
print(Record)

recordfile.close()
#========= STEP 3 ==========
</code>```

Body:
The task that I have to do is showing all other elements rather than (Americano). I tried to use 'Record.remove("Americano") but it shows the error

Record.remove("Americano")
ValueError: list.remove(x): x not in list

What should I Do......

=========================this is the result of=======================     Record.append(record[1]) print(Record) ->

['Menu_name', 'Cafe_latte', 'Americano', 'Americano', 'Smoothie_queen', 'Americano', 'Americano', 'Cafe_mocha', 'Cafe_latte', 'Americano', 'Amorparty', 'Plain_yogurt', 'Americano', 'Americano', 'Cafe_mocha', 'Berry_smoothie', 'Cafe_mocha', 'Cafe_latte', 'Americano', 'Cafe_latte', 'Berry_smoothie', 'Berry_smoothie', 'Plain_yogurt', 'Berry_smoothie', 'Plane_yougurt', 'Berry_smoothie', 'Cafe_latte', 'Americano', 'Americano', 'Cafe_mocha', 'Plain_yogurt', 'Americano', 'Plain_yogurt', 'Cafe_mocha', 'Plain_yogurt', 'Americano', 'Cofe_latte', 'Plain_yogurt', 'Cafe_mocha', 'Americano', 'Berry_smoothie', 'Cafe_latte', 'Cafe_latte', 'Cafe_mocha', 'Cafe_latte', 'Cafe_latte', 'Cafe_mocha', 'Americano', 'Plain_yogurt', 'Americano', 'Americano', 'Cofe_latte', 'Berry_smoothie', 'Berry_smudie', 'American_air', 'Plain_yogurt', 'Berry_smoothie', 'Berry_smoothie', 'Berry_smoothie', 'Cafe_latte', 'Americano', 'Plain_yogurt', 'Cafe_latte', 'Cafe_mocha', 'Cafe_mocha', 'Plain_yogurt', 'Berry_smoothie', 'Berry_smoothie', 'Cafe_mocha', 'Cafe_mocha', 'Berry_smoothie', 'Cafe_mocha', 'Plain_yogurt']

def load_menu():
    Menu = []
    #========= STEP 1 ==========
    menufile = open("menu.txt", "r")

    for line in menufile:
        menu = line.split()
        Menu.append(menu)

    menufile.close()

    for menu in Menu:
        print(menu[0]," : ",menu[1])
    #========= STEP 1 ==========
    return Menu

def error_check(date):
    #========= STEP 3 ==========
    Record = []
    recordfile = open("ledger_"+date+".txt","r")

    for line in recordfile:
        record = line.split()
        Record.append(record[1])
        Record.remove("Americano")
    print(Record)

    recordfile.close()
    #========= STEP 3 ==========

Body:
You should check if "Americano" in list before remove the element:

def error_check(date):
    #========= STEP 3 ==========
    Record = []
    recordfile = open("ledger_"+date+".txt","r")

for line in recordfile:
    record = line.split()
    Record.append(record[1])
    if "Americano" in Record:
        Record.remove("Americano")
print(Record)

recordfile.close()
#========= STEP 3 ==========


问:
Delete snapshots except those with specific description
I'm trying to delete old AWS snapshots but I need to exclude any with a description value that starts with "Created by CreateImage".

I've tried variations of boto3.resource and boto3.client.

```<code>from datetime import datetime, timedelta, timezone

import boto3
client = boto3.client('ec2')
snapshots = client.snapshots.filter(Description!='Created by CreateImage')

def lambda_handler(event, context):
    for snapshot in snapshots:
        start_time = snapshot.start_time
        delete_time = datetime.now(tz=timezone.utc) - timedelta(days=790)
        if delete_time > start_time:
            snapshot.delete()
            print('Snapshot with Id = {} is deleted '.format(snapshot.snapshot_id))
</code>```

Right now I have about 10 snapshots older than 790 days, 5 with a description that starts with "Created by CreateImage" and 5 that don't. In testing this out I want to delete those snapshots without that description.

the error I get is:

module initialization error: 'EC2' object has no attribute 'snapshots'

答:
Here's a version that works.

Note the use of OwnerIds=['self'] which limits results to only snapshots created by your AWS account. Without this, it will return all publicly-available snapshots created by any AWS account.

```<code>from datetime import datetime, timedelta, timezone

import boto3

def lambda_handler(event, context):

    delete_time = datetime.now(tz=timezone.utc) - timedelta(days=790)

    ec2_resource = boto3.resource('ec2', region_name='ap-southeast-2')
    snapshots = ec2_resource.snapshots.filter(OwnerIds=['self'])

    for snapshot in snapshots:
        if not snapshot.description.startswith('Created by CreateImage') and delete_time > snapshot.start_time:
            snapshot.delete()
            print('Snapshot with Id = {} is deleted '.format(snapshot.snapshot_id))
</code>```

Body:
I'm trying to delete old AWS snapshots but I need to exclude any with a description value that starts with "Created by CreateImage".

I've tried variations of boto3.resource and boto3.client.

from datetime import datetime, timedelta, timezone

import boto3
client = boto3.client('ec2')
snapshots = client.snapshots.filter(Description!='Created by CreateImage')

def lambda_handler(event, context):
    for snapshot in snapshots:
        start_time = snapshot.start_time
        delete_time = datetime.now(tz=timezone.utc) - timedelta(days=790)
        if delete_time > start_time:
            snapshot.delete()
            print('Snapshot with Id = {} is deleted '.format(snapshot.snapshot_id))

Right now I have about 10 snapshots older than 790 days, 5 with a description that starts with "Created by CreateImage" and 5 that don't. In testing this out I want to delete those snapshots without that description.

the error I get is:

module initialization error: 'EC2' object has no attribute 'snapshots'

Body:
Here's a version that works.

Note the use of OwnerIds=['self'] which limits results to only snapshots created by your AWS account. Without this, it will return all publicly-available snapshots created by any AWS account.

from datetime import datetime, timedelta, timezone

import boto3

def lambda_handler(event, context):

    delete_time = datetime.now(tz=timezone.utc) - timedelta(days=790)

    ec2_resource = boto3.resource('ec2', region_name='ap-southeast-2')
    snapshots = ec2_resource.snapshots.filter(OwnerIds=['self'])

    for snapshot in snapshots:
        if not snapshot.description.startswith('Created by CreateImage') and delete_time > snapshot.start_time:
            snapshot.delete()
            print('Snapshot with Id = {} is deleted '.format(snapshot.snapshot_id))


问:
Reflecting Return Date & Extension Date in Excel
I am setting up a Excel for Rental of Vehicle to Keep track of Vehicle Return Date & Extension Date. I can get the table to show vehicle return but couldnt get it to show the extension date.

Tried to use Multiple If And statement.

```<code>=IF(AND($B10<>"",$C10<>""),1-SUMPRODUCT(('[Rental Current Fleet.xlsm]Rental Vehicle'!$G$7:$G$1000<=H$7)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$H$7:$H$1000>=H$7)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$C$7:$C$1000=$B10)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$D$7:$D$1000=$C10)),"")
</code>```

**Above code is working

```<code>=IF(AND($B10<>"",$C10<>""),1-SUMPRODUCT(('[Rental Current Fleet.xlsm]Rental Vehicle'!$H$7:$H$1000<=H$7)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$J$7:$J$1000>=H$7)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$C$7:$C$1000=$B10)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$D$7:$D$1000=$C10)),"")
</code>```

Cell Shows #Value!

答:
Vehicle Rental Availability

I am actually trying to create an excel to indicate

Yellow - Vehicle Available

Grey - Vehicle Date out to Expected In Date

Blue - Vehicle Extended Date

Input Fields

Body:
I am setting up a Excel for Rental of Vehicle to Keep track of Vehicle Return Date & Extension Date. I can get the table to show vehicle return but couldnt get it to show the extension date.

Tried to use Multiple If And statement.

=IF(AND($B10<>"",$C10<>""),1-SUMPRODUCT(('[Rental Current Fleet.xlsm]Rental Vehicle'!$G$7:$G$1000<=H$7)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$H$7:$H$1000>=H$7)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$C$7:$C$1000=$B10)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$D$7:$D$1000=$C10)),"")

**Above code is working

=IF(AND($B10<>"",$C10<>""),1-SUMPRODUCT(('[Rental Current Fleet.xlsm]Rental Vehicle'!$H$7:$H$1000<=H$7)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$J$7:$J$1000>=H$7)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$C$7:$C$1000=$B10)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$D$7:$D$1000=$C10)),"")

Cell Shows #Value!


问:
Func<HttpRequestMessage> related Mocking Questions for Unit Tests
I am using Moq in my XUnit test. In the dependency methods, it contains a Func<HttpResponseMessage> parameter. Here's the unit test that I wrote:

```<code>      [Fact]
    public async Task Test()
    {
        //Arrange
        var content = new StringContent(TestData.GetResponse().ToString(), Encoding.UTF8, "application/json");
        var httpResponse = new HttpResponseMessage()
        {
            StatusCode = HttpStatusCode.OK,
            Content = content
        };
        _mockRetryHttpRequest.Setup(x => x.ExecuteAsync(It.IsAny<Func<HttpRequestMessage>>(), It.IsAny<HttpClient>(), It.IsAny<int>()))
                           .ReturnsAsync(httpResponse);
        var libraryService = new LibraryService(_mockRetryHttpRequest.Object);

        //Act
        var response = await libraryService.GetResponseForSearch(new SearchRequest(), null);

        //Assert
        response.Should().NotBeNull();
    }
</code>```

And here's the actual method that I need to test on

```<code>public class LibraryService : ILibraryService
{
    private IRetryHttpRequest _retryHttpRequest;
    public LibraryService(IRetryHttpRequest retryHttpRequest)
    {
        _retryHttpRequest = retryHttpRequest;
    }

    public async Task<ResponseModel> GetResponseForSearch(SearchRequest searchRequest, HttpClient client)
    {
        //send request and retry if failed
        ResponseModel result = new ResponseModel();
        HttpResponseMessage httpResponseMessage = await _retryHttpRequest.ExecuteAsync(() => new HttpRequestMessage(), client, 3);

        //process response
        if (httpResponseMessage != null)
        {
            string response = await httpResponseMessage.Content.ReadAsStringAsync();
            result = JsonConvert.DeserializeObject<ResponseModel>(response);
        }
        return result;
    }
}

public class RetryHttpRequest : IRetryHttpRequest
{
    public async Task<HttpResponseMessage> ExecuteAsync(Func<HttpRequestMessage> requestMessage, HttpClient client, int maxTryValue)
    {
        var content = new StringContent("From Execute Async", Encoding.UTF8, "application/json");
        var httpResponse = new HttpResponseMessage()
        {
            StatusCode = HttpStatusCode.OK,
            Content = content
        };
        return httpResponse;
    }
}
</code>```

When I stepped through the code, for this below line of code, the httpResponseMessage variable is returning null despite the fact that I already mocked it with 200 response in the unit test.

```<code>HttpResponseMessage httpResponseMessage = await _retryHttpRequest.ExecuteAsync(() => new HttpRequestMessage(), client, 3);
</code>```

答:
While the question appears to be lacking a complete explanation, the follow is being used for demonstrative purposes to show how to test the target method with moq.

Assuming the following

```<code>public interface IRetryHttpRequest {
    Task<HttpResponseMessage> ExecuteAsync(Func<HttpRequestMessage> requestMessage, HttpClient client, int maxTryValue);
}

public class LibraryService : ILibraryService {
    private IRetryHttpRequest _retryHttpRequest;
    public LibraryService(IRetryHttpRequest retryHttpRequest) {
        _retryHttpRequest = retryHttpRequest;
    }

    public async Task<ResponseModel> GetResponseForSearch(SearchRequest searchRequest, HttpClient client) {
        //send request and retry if failed
        ResponseModel result = new ResponseModel();
        HttpResponseMessage httpResponseMessage = await _retryHttpRequest.ExecuteAsync(() => new HttpRequestMessage(), client, 3);

        //process response
        if (httpResponseMessage != null) {
            string response = await httpResponseMessage.Content.ReadAsStringAsync();
            result = JsonConvert.DeserializeObject<ResponseModel>(response);
        }
        return result;
    }
}

public interface ILibraryService {

}
</code>```

Note the syntax changes that would have shown errors with the original code shown in the question.

The following test demonstrates how to test the LibraryService.GetResponse method and assert the expected behavior

```<code>public async Task SampleTest() {
    //Arrange
    var content = new StringContent("{}", Encoding.UTF8, "application/json");
    var httpResponse = new HttpResponseMessage() {
        StatusCode = HttpStatusCode.OK,
        Content = content
    };

    var _mockRetryHttpRequest = new Mock<IRetryHttpRequest>();
    _mockRetryHttpRequest
        .Setup(_ => _.ExecuteAsync(It.IsAny<Func<HttpRequestMessage>>(), It.IsAny<HttpClient>(), It.IsAny<int>()))
        .ReturnsAsync(httpResponse);

    var lgService = new LibraryService(_mockRetryHttpRequest.Object);

    //Act
    var response = await lgService.GetResponseForSearch(new SearchRequest(), null);

    //Assert
    response.Should().NotBeNull();
}
</code>```

FluentAssertions was used to assert the expected behavior.

Some points to take note of

Only the dependencies actually necessary for the test to be exercised to completion were provided to the subject under test. Which means no HttpClient is actually needed by the mock

The method under test also needs to be awaited in order to get the response for assertion.

Because I dont have access to your test data, I used an empty JSON object "{}" to represent the content of the response to allow the JsonConvert to work

I would suggest then that you review your test data that is being deserialized. That may be the point of failure as that is the only place that the result can be set to null since it is being initialized at the top of the function.

Body:
I am using Moq in my XUnit test. In the dependency methods, it contains a Func<HttpResponseMessage> parameter. Here's the unit test that I wrote:

      [Fact]
    public async Task Test()
    {
        //Arrange
        var content = new StringContent(TestData.GetResponse().ToString(), Encoding.UTF8, "application/json");
        var httpResponse = new HttpResponseMessage()
        {
            StatusCode = HttpStatusCode.OK,
            Content = content
        };
        _mockRetryHttpRequest.Setup(x => x.ExecuteAsync(It.IsAny<Func<HttpRequestMessage>>(), It.IsAny<HttpClient>(), It.IsAny<int>()))
                           .ReturnsAsync(httpResponse);
        var libraryService = new LibraryService(_mockRetryHttpRequest.Object);

        //Act
        var response = await libraryService.GetResponseForSearch(new SearchRequest(), null);

        //Assert
        response.Should().NotBeNull();
    }

And here's the actual method that I need to test on

public class LibraryService : ILibraryService
{
    private IRetryHttpRequest _retryHttpRequest;
    public LibraryService(IRetryHttpRequest retryHttpRequest)
    {
        _retryHttpRequest = retryHttpRequest;
    }

    public async Task<ResponseModel> GetResponseForSearch(SearchRequest searchRequest, HttpClient client)
    {
        //send request and retry if failed
        ResponseModel result = new ResponseModel();
        HttpResponseMessage httpResponseMessage = await _retryHttpRequest.ExecuteAsync(() => new HttpRequestMessage(), client, 3);

        //process response
        if (httpResponseMessage != null)
        {
            string response = await httpResponseMessage.Content.ReadAsStringAsync();
            result = JsonConvert.DeserializeObject<ResponseModel>(response);
        }
        return result;
    }
}

public class RetryHttpRequest : IRetryHttpRequest
{
    public async Task<HttpResponseMessage> ExecuteAsync(Func<HttpRequestMessage> requestMessage, HttpClient client, int maxTryValue)
    {
        var content = new StringContent("From Execute Async", Encoding.UTF8, "application/json");
        var httpResponse = new HttpResponseMessage()
        {
            StatusCode = HttpStatusCode.OK,
            Content = content
        };
        return httpResponse;
    }
}

When I stepped through the code, for this below line of code, the httpResponseMessage variable is returning null despite the fact that I already mocked it with 200 response in the unit test.

HttpResponseMessage httpResponseMessage = await _retryHttpRequest.ExecuteAsync(() => new HttpRequestMessage(), client, 3);

Body:
While the question appears to be lacking a complete explanation, the follow is being used for demonstrative purposes to show how to test the target method with moq.

Assuming the following

public interface IRetryHttpRequest {
    Task<HttpResponseMessage> ExecuteAsync(Func<HttpRequestMessage> requestMessage, HttpClient client, int maxTryValue);
}

public class LibraryService : ILibraryService {
    private IRetryHttpRequest _retryHttpRequest;
    public LibraryService(IRetryHttpRequest retryHttpRequest) {
        _retryHttpRequest = retryHttpRequest;
    }

    public async Task<ResponseModel> GetResponseForSearch(SearchRequest searchRequest, HttpClient client) {
        //send request and retry if failed
        ResponseModel result = new ResponseModel();
        HttpResponseMessage httpResponseMessage = await _retryHttpRequest.ExecuteAsync(() => new HttpRequestMessage(), client, 3);

        //process response
        if (httpResponseMessage != null) {
            string response = await httpResponseMessage.Content.ReadAsStringAsync();
            result = JsonConvert.DeserializeObject<ResponseModel>(response);
        }
        return result;
    }
}

public interface ILibraryService {

}

Note the syntax changes that would have shown errors with the original code shown in the question.

The following test demonstrates how to test the LibraryService.GetResponse method and assert the expected behavior

public async Task SampleTest() {
    //Arrange
    var content = new StringContent("{}", Encoding.UTF8, "application/json");
    var httpResponse = new HttpResponseMessage() {
        StatusCode = HttpStatusCode.OK,
        Content = content
    };

    var _mockRetryHttpRequest = new Mock<IRetryHttpRequest>();
    _mockRetryHttpRequest
        .Setup(_ => _.ExecuteAsync(It.IsAny<Func<HttpRequestMessage>>(), It.IsAny<HttpClient>(), It.IsAny<int>()))
        .ReturnsAsync(httpResponse);

    var lgService = new LibraryService(_mockRetryHttpRequest.Object);

    //Act
    var response = await lgService.GetResponseForSearch(new SearchRequest(), null);

    //Assert
    response.Should().NotBeNull();
}

FluentAssertions was used to assert the expected behavior.

Some points to take note of

Only the dependencies actually necessary for the test to be exercised to completion were provided to the subject under test. Which means no HttpClient is actually needed by the mock

The method under test also needs to be awaited in order to get the response for assertion.

Because I dont have access to your test data, I used an empty JSON object "{}" to represent the content of the response to allow the JsonConvert to work

I would suggest then that you review your test data that is being deserialized. That may be the point of failure as that is the only place that the result can be set to null since it is being initialized at the top of the function.


问:
git repository gives 403 error while connecting from jenkins in linux
Hi I just want to configure my project from github to jenkins to generate build.
I'm getting following error

```<code>Failed to connect to repository : Command "/usr/bin/git ls-remote -h
https://github.com/xxxxx/yyyyy.git HEAD"
returned status code 128:
stdout:
stderr: error: The requested URL returned error: 403 Forbidden while
accessing https://github.com/xxxxx/yyyyy.git/info/refs

fatal: HTTP request failed
</code>```

I have added git path at Global Tool Configuration also.  I've setup jenkins in linux centos server.

I have found few similar questions in stackoverflow but that doesn't give a solution

Can anyone please tell me what may be wrong in that ?
Thanks in advance

答: I also faced similar issue when configuring GIT in jenkins. After some investigation I found out that jenkins using default git installation which is 1.7.1 version. Then I installed the latest version and configured jenkins to use the latest version. Click on Maange Jenkins -> Global Tool Configuration -> Git to find the configuration section.

Body:
Hi I just want to configure my project from github to jenkins to generate build.
I'm getting following error

Failed to connect to repository : Command "/usr/bin/git ls-remote -h
https://github.com/xxxxx/yyyyy.git HEAD"
returned status code 128:
stdout:
stderr: error: The requested URL returned error: 403 Forbidden while
accessing https://github.com/xxxxx/yyyyy.git/info/refs

fatal: HTTP request failed

I have added git path at Global Tool Configuration also.  I've setup jenkins in linux centos server.

I have found few similar questions in stackoverflow but that doesn't give a solution

Can anyone please tell me what may be wrong in that ?
Thanks in advance


问:
Java basics: a static function without a name, or return type
```<code>public class Main {
    public static final Logger LOGGER = Logger.getLogger(Main.class.getName());

    static {
        try {
             LOGGER.addHandler(new FileHandler("errors.log",true));
        }
        catch(IOException ex) {
             LOGGER.log(Level.WARNING,ex.toString(),ex);
        }
    }
...
</code>```

I'm wondering what is this nameless static function about.

I never saw anything like this in java (which I'm currently learning).

What is it for ?

When is it typically used ?

When is this gonna be executed in the program ?

答: It's a static initializer, which will be executed during class initialization. As you can see, it allows you to run complex logic during that stage, including exception handling.</p>

Body:
public class Main {
    public static final Logger LOGGER = Logger.getLogger(Main.class.getName());

    static {
        try {
             LOGGER.addHandler(new FileHandler("errors.log",true));
        }
        catch(IOException ex) {
             LOGGER.log(Level.WARNING,ex.toString(),ex);
        }
    }
...

I'm wondering what is this nameless static function about.

I never saw anything like this in java (which I'm currently learning).

What is it for ?

When is it typically used ?

When is this gonna be executed in the program ?


问:
Redirect All Traffic to https://
I am currently using this:

```<code>RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

Which appears to be working but I don't know if it is correct way, and no idea if it is the most efficient.

I also found this:

```<code>RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
</code>```

Which seems to be much cleaner, but it does not redirect https://www to https://

I want to redirect all possible entry points (http:// || http://www. || www. || https://www.) to https://.

Any other recommended ways to handle?

答:
I redirect all formats to https://example.com without the www.

This is what I use:

```<code>#Redirect www and http
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
</code>```

I have never had a problem with it.

Title: Redirect All Traffic to https://

Body:
I am currently using this:

RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Which appears to be working but I don't know if it is correct way, and no idea if it is the most efficient.

I also found this:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]

Which seems to be much cleaner, but it does not redirect https://www to https://

I want to redirect all possible entry points (http:// || http://www. || www. || https://www.) to https://.

Any other recommended ways to handle?

Body:
I redirect all formats to https://example.com without the www.

This is what I use:

#Redirect www and http
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

I have never had a problem with it.


问:
How to Schedule Selenium Web Drivers Tests in C#
In my development project, We implemented regression test cases using selenium webdriver using c#. I would like to schedule of Regression tests once in a day.
Tools used shows below.

Selenium Webdriver on C#

Visual Studio 2017

NUnit test framework

Please suggest any other solution.

Thanks in advance.

答:
Use task scheduler;

Create a batch file with the command to execute the tests (e.g ..\nunit.exe ..\seleniumTests.cs)

Open 'Task Scheduler'

Create a task with the time/frequency as the 'Trigger' and the set the batch file as the 'Action' to execute.


问:
How to optimize code - it works, but I know I'm missing much learning
The exercise I'm working on asks "Write a method, coprime?(num_1, num_2), that accepts two numbers as args. The method should return true if the only common divisor between the two numbers is 1."

I've written a method to complete the task, first by finding all the factors then sorting them and looking for duplicates. But I'm looking for suggestions on areas I should consider to optimize it.

The code works, but it is just not clean.

def factors(num)
 return (1..num).select { |n| num % n == 0}
end

def coprime?(num_1, num_2)
  num_1_factors = factors(num_1)
  num_2_factors = factors(num_2)
  all_factors = num_1_factors + num_2_factors
  new = all_factors.sort
  dups = 0
  new.each_index do |i|
    dups += 1 if new[i] == new[i+1]
  end
  if dups > 1
    false
  else
    true
  end
end

p coprime?(25, 12)    # => true
p coprime?(7, 11)     # => true
p coprime?(30, 9)     # => false
p coprime?(6, 24)     # => false

```

答:
You can just use Integer#gcd:</p>

```<code>def coprime?(num_1, num_2)
  num_1.gcd(num_2) == 1
end
</code>```

Body:
You can just use Integer#gcd:

def coprime?(num_1, num_2)
  num_1.gcd(num_2) == 1
end


问:
How do I create multiple data frames using a for loop in python
I'm trying to make multiple dataframes that are subsets of existing dataframes.

I have df_list which is actually a list of datasets:

df_list = [df1B, df2B, df3B, df4B, df5B, df6B, df7B, df8B, df9B, df10B, df11B, df12B, df13B, df14B, df15B, df16B, df17B, df18B, df19B, df20B, df21B, df22B, df23B, df24B, df25B, df26B, df27B, df28B, df30B, df31B, df32B, df33B, df34B, df35B]
```

<p>If I want to make a subset of a single data set I do this and it works:</p>

<pre class="lang-py prettyprint-override"><code>df2B = df2B.groupby(['Location']).get_group(36)
</code>```

It takes all locations with number 36, but when I try to do it for all the data sets in a for loop it doesn't work

for df in df_list:
    df = df.groupby(['Location']).get_group(36)
```

But this is not making it for each dataset. It doesn't show any error message but it doesn't do anything else either :(

Should I just write the same line 35 times ??? I hope I have a better option.

答:
If I understand correctly, you can use a list comprehension for this:

```<code>subset_df_list = [df.groupby('Location').get_group(36) for df in df_list]
</code>```

As an aside, your for loop doesn't work because you just keep assigning back to df. You probably want this, which is also the equivalent of the above comprehension:

```<code>subset_df_list = []

for df in df_list:
    subset_df = df.groupby('Location').get_group(36)
    subset_df_list.append(subset_df)
</code>```

Body:
I'm trying to make multiple dataframes that are subsets of existing dataframes.

I have df_list which is actually a list of datasets:

df_list = [df1B, df2B, df3B, df4B, df5B, df6B, df7B, df8B, df9B, df10B, df11B, df12B, df13B, df14B, df15B, df16B, df17B, df18B, df19B, df20B, df21B, df22B, df23B, df24B, df25B, df26B, df27B, df28B, df30B, df31B, df32B, df33B, df34B, df35B]

If I want to make a subset of a single data set I do this and it works:

df2B = df2B.groupby(['Location']).get_group(36)

It takes all locations with number 36, but when I try to do it for all the data sets in a for loop it doesn't work

for df in df_list:
    df = df.groupby(['Location']).get_group(36)

But this is not making it for each dataset. It doesn't show any error message but it doesn't do anything else either :(

Should I just write the same line 35 times ??? I hope I have a better option.

Body:
If I understand correctly, you can use a list comprehension for this:

subset_df_list = [df.groupby('Location').get_group(36) for df in df_list]

As an aside, your for loop doesn't work because you just keep assigning back to df. You probably want this, which is also the equivalent of the above comprehension:

subset_df_list = []

for df in df_list:
    subset_df = df.groupby('Location').get_group(36)
    subset_df_list.append(subset_df)


问:
Java: need to see if each char in input string, matches any char in "alphabet"
I am implementing a DFA.  The given alphabet is {a, b}.

I've got it telling me if the input string is accepted or not.  (it's got an easy "accept" rule -- the first & last character of the input string must be the same)

What I am trying to do, though, is to check if each character in the input string, is allowed per the prescribed "alphabet".

So, as a boolean, it would return false if the input string is "abcdefg" (for instance)... and it would return true if the input string is "abbaabbbbba" (for instance)

I need to check if a is in the alphabet... then if b is in the alphabet... then if c is in the alphabet... and so forth for each character in the input string.

I've tried variations of loops of different kinds, (I don't remember every single variation!) comparing inputString.charAt(i) with each character in the alphabet... but so far nothing is working like i need/want it to.

for instance, right now I'm trying:

```<code>  public boolean isInAlphabet(String inputString) {
    if(inputString == " ") {
      System.out.println("   -> empty string is not in our alphabet");
      return false;
    }

    for(int i = 0; i < inputString.length(); i++) {
      Character check = inputString.charAt(i);
      System.out.print(check);  // just to see what it's doing

      if(check.equals(alphabet.charAt(0)) || check.equals(alphabet.charAt(1))) {
        System.out.println("   -> your input string is in our alphabet");

        return true;
      }
      else{
        System.out.println("   -> your input string is *not* in our alphapet");
        return false;
      }
    }
    return false;
  }
</code>```

the alphabet is represented as:

```<code>String alphabet = "ab";
</code>```

and the input string is like:

```<code>String inputString = "abcdefg";
</code>```

Thing is, it stops checking after it finds that the first character in the input string, is in the alphabet.

Like:

```<code>test input string: abcdefg
is test input string in our alphabet?
a   -> your input string is in our alphabet
</code>```

... and that's all the further checking it does.

How do I get it to check the whole input string -- each character of the input string, against the alphabet?

Like i said, I can't even remember all the things I've tried so far, but it's been at least a dozen.  The more I try the more confused I get.  This feels so easy, but yet I'm not sure how to get it to work.

答:
This is only a schema of how to proceed and it's more like a general pattern,
in this case is adapted for your purpose.

 (accept only if first char is the same as last char)

This a DFA for your problem.

Basically there are states inside(circles) and transitions(arrows)

States:

S1->start state (always start from here)

S2,S3 -> intermediary (when input is finish and this state then not accepted)

S4,S5 -> final state (input finish and this state then accepted)`

Transitions[movements array]

(StateA, StateB, char) : going from SA to SB with char

(S1,S3,a) : T1

(S1,S2,b) : T2

(S3,S3,b) : T3

(S3,S4,a) : T4

(S4,S4,a) : T5

(S2,S2,a) : T6

(S4,S3,b) : T7

(S2,S5,b) : T8

(S5,S2,a) : T9

(S5,S5,b) : T10

Eg:

1:abb

(S1,a)->S3 by T1

(S3,b)->S3 by T3

(S3,b)->S3 by T3

End on S3 and input is not accepted

2:babb

(S1,b)->S2 by T2

(S2,a)->S2 by T6

(S2,b)->S5 by T9 (accepted if input is finish:bab, here not)

(S5,b)->S5 by T10

End on S5 and input is accepted

For any other char encounter that is not in alphabet just return immediately with not accepted.

For coding, need to add states and transitions.When checking the input char by char on
each step then update the current state properly.

Hope to be useful for you.

Body:
I am implementing a DFA.  The given alphabet is {a, b}.

I've got it telling me if the input string is accepted or not.  (it's got an easy "accept" rule -- the first & last character of the input string must be the same)

What I am trying to do, though, is to check if each character in the input string, is allowed per the prescribed "alphabet".

So, as a boolean, it would return false if the input string is "abcdefg" (for instance)... and it would return true if the input string is "abbaabbbbba" (for instance)

I need to check if a is in the alphabet... then if b is in the alphabet... then if c is in the alphabet... and so forth for each character in the input string.

I've tried variations of loops of different kinds, (I don't remember every single variation!) comparing inputString.charAt(i) with each character in the alphabet... but so far nothing is working like i need/want it to.

for instance, right now I'm trying:

  public boolean isInAlphabet(String inputString) {
    if(inputString == " ") {
      System.out.println("   -> empty string is not in our alphabet");
      return false;
    }

    for(int i = 0; i < inputString.length(); i++) {
      Character check = inputString.charAt(i);
      System.out.print(check);  // just to see what it's doing

      if(check.equals(alphabet.charAt(0)) || check.equals(alphabet.charAt(1))) {
        System.out.println("   -> your input string is in our alphabet");

        return true;
      }
      else{
        System.out.println("   -> your input string is *not* in our alphapet");
        return false;
      }
    }
    return false;
  }

the alphabet is represented as:

String alphabet = "ab";

and the input string is like:

String inputString = "abcdefg";

Thing is, it stops checking after it finds that the first character in the input string, is in the alphabet.

Like:

test input string: abcdefg
is test input string in our alphabet?
a   -> your input string is in our alphabet

... and that's all the further checking it does.

How do I get it to check the whole input string -- each character of the input string, against the alphabet?

Like i said, I can't even remember all the things I've tried so far, but it's been at least a dozen.  The more I try the more confused I get.  This feels so easy, but yet I'm not sure how to get it to work.


问:
How do I add a column to a JPA entity, and still keep my data?
During the development of a JPA application, I added a field "type" to an entity. This caused the application to fail to start with

```<code>Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: Column 'T1.TYPE' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join specification or appears in a HAVING clause and is not in the GROUP BY list. If this is a CREATE or ALTER TABLE  statement then 'T1.TYPE' is not a column in the target table.
Error Code: -1
</code>```

during a selection.

Is there a way to get it to ALTER TABLE on startup, to match the current entity definitions?
I notice that when the app starts up it calls CREATE TABLE for each table, fails and carries on.

In the past when I've added fields to entities I just delete the database and start again. This is ok for me now but what if I want to add a field to an entry when developing the next release of the software, how do I upgrade my clients without losing all there data?

Thanks in advance - Phil.

答:
You can replace the tables in EclipseLink using,

"eclipselink.ddl-generation" = "drop-and-create-tables"

EclipseLink does not support altering existing tables, please log an enhancement request for this and vote for it.

In general it is normally better to have a DBA define a script to define the production schema and handle migration.

Body:
During the development of a JPA application, I added a field "type" to an entity. This caused the application to fail to start with

Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: Column 'T1.TYPE' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join specification or appears in a HAVING clause and is not in the GROUP BY list. If this is a CREATE or ALTER TABLE  statement then 'T1.TYPE' is not a column in the target table.
Error Code: -1

during a selection.

Is there a way to get it to ALTER TABLE on startup, to match the current entity definitions?
I notice that when the app starts up it calls CREATE TABLE for each table, fails and carries on.

In the past when I've added fields to entities I just delete the database and start again. This is ok for me now but what if I want to add a field to an entry when developing the next release of the software, how do I upgrade my clients without losing all there data?

Thanks in advance - Phil.


问:
Redirect to a certain page then perform an event or action
I have a button with an onlick event that when triggered, has to redirect to a certain page, and add a class to a certain element.

Using the code:

window.location.href = "http://localhost:8000/dashboard";

$('p').addClass('active');,

I've successfully managed to redirect it but the event was not performed.  Is this even possible because it refreshes the DOM after redirecting. Thanks.

答: You will not be able to manipulate DOM elements on other pages during navigation as code after the redirect will not be executed. Instead listen to events on the page you are redirecting to and determine from there on how to apply your active class.


答:
```<code>df = [pd.DataFrame({'Location': np.random.randint(0,5,size=(100))}) for i in range(10)]
df = list(map(lambda x: x.groupby('Location').get_group(1), df))
</code>```

Title: How do I create multiple data frames using a for loop in python


问:
UPDATE to remove duplicates from comma-separated list
In my Postgres db, I have a table with some columns where one column B has values as follows:

```<code>A      B
a1     b0, b1, b1
a2     b2, b3
a3     b4, b4, b5, b5
</code>```

My expected output should be like this:

```<code>A      B
a1     b0, b1
a2     b2, b3
a3     b4, b5
</code>```

Is there a simple UPDATE in Postgres to do this?

答:
The specific update statement depends on the type of column b, but there are really only 3 different ways this data could be stored, in a delimited string, an text array or a json

The update statement for the comma separated text field would be:

```<code>update mytable
set b = array_to_string(array(select distinct unnest(string_to_array(b, ', '))), ', ');
</code>```

If b is an text array then:

```<code>update mytable
set b = array(select distinct unnest(b));
</code>```

If b is a json array then:

```<code>update mytable
set b = array_to_json(array(select distinct value from json_array_elements_text(b)));
</code>```

As you can see, the cleanest statement in is case results from the data being stored as a text array. If you must store an array of values in 1 column, do it using an array type.

However, I would also recommend normalizing your data.

These statements above will update all rows in the table, thus incurring a higher execution cost. I'll illustrate a way to reduce updates using the text array variant (as that requires the shortest sql query):

```<code>update mytable
set b = array(select distinct unnest(b))
where array_length(b_array, 1) != (select count(distinct c) from unnest(b) c);
</code>```

Body:
In my Postgres db, I have a table with some columns where one column B has values as follows:

A      B
a1     b0, b1, b1
a2     b2, b3
a3     b4, b4, b5, b5

My expected output should be like this:

A      B
a1     b0, b1
a2     b2, b3
a3     b4, b5

Is there a simple UPDATE in Postgres to do this?

Body:
The specific update statement depends on the type of column b, but there are really only 3 different ways this data could be stored, in a delimited string, an text array or a json

The update statement for the comma separated text field would be:

update mytable
set b = array_to_string(array(select distinct unnest(string_to_array(b, ', '))), ', ');

If b is an text array then:

update mytable
set b = array(select distinct unnest(b));

If b is a json array then:

update mytable
set b = array_to_json(array(select distinct value from json_array_elements_text(b)));

As you can see, the cleanest statement in is case results from the data being stored as a text array. If you must store an array of values in 1 column, do it using an array type.

However, I would also recommend normalizing your data.

These statements above will update all rows in the table, thus incurring a higher execution cost. I'll illustrate a way to reduce updates using the text array variant (as that requires the shortest sql query):

update mytable
set b = array(select distinct unnest(b))
where array_length(b_array, 1) != (select count(distinct c) from unnest(b) c);


答:
You could use Euclid's algorithm to find the GCD, then check whether it's 1.

def gcd a, b
  while a % b != 0
    a, b = b, a % b
  end
  return b
end

def coprime? a, b
  gcd(a, b) == 1
end

p coprime?(25, 12)    # => true
p coprime?(7, 11)     # => true
p coprime?(30, 9)     # => false
p coprime?(6, 24)     # => false```
</code>```

Title: How to optimize code - it works, but I know I'm missing much learning

Body:
The exercise I'm working on asks "Write a method, coprime?(num_1, num_2), that accepts two numbers as args. The method should return true if the only common divisor between the two numbers is 1."

I've written a method to complete the task, first by finding all the factors then sorting them and looking for duplicates. But I'm looking for suggestions on areas I should consider to optimize it.

The code works, but it is just not clean.

def factors(num)
 return (1..num).select { |n| num % n == 0}
end

def coprime?(num_1, num_2)
  num_1_factors = factors(num_1)
  num_2_factors = factors(num_2)
  all_factors = num_1_factors + num_2_factors
  new = all_factors.sort
  dups = 0
  new.each_index do |i|
    dups += 1 if new[i] == new[i+1]
  end
  if dups > 1
    false
  else
    true
  end
end

p coprime?(25, 12)    # => true
p coprime?(7, 11)     # => true
p coprime?(30, 9)     # => false
p coprime?(6, 24)     # => false


问:
Unable to display Bitmap and text on a CMfcButton : Only picture displayed
I would like to be able to display a bitmap and a text on a CMFC Button.

I succeed to display the bitmap, but, if i tried to display the text, the text don't display .

Here is my code ( in my OnInitDialog) :

```<code>    CPngImage image_;
    image_.Load(IDB_PNG2, AfxGetInstanceHandle());
    CBitmap bitmap_;
    bitmap_.Attach(image_.Detach());
    m_pButtonExport->SetBitmap(bitmap_);
    m_pButtonExport->SetWindowTextW(L"Text");
    m_pButtonExport->Invalidate();
</code>```

Anyone have some ideas please ?

Thanks a lot :)

答:
Just try to use as below. Hope it will work.</p>

```<code>demoBtn->m_bTopImage = TRUE;
</code>```

Body:
I would like to be able to display a bitmap and a text on a CMFC Button.

I succeed to display the bitmap, but, if i tried to display the text, the text don't display .

Here is my code ( in my OnInitDialog) :

    CPngImage image_;
    image_.Load(IDB_PNG2, AfxGetInstanceHandle());
    CBitmap bitmap_;
    bitmap_.Attach(image_.Detach());
    m_pButtonExport->SetBitmap(bitmap_);
    m_pButtonExport->SetWindowTextW(L"Text");
    m_pButtonExport->Invalidate();

Anyone have some ideas please ?

Thanks a lot :)

Body:
Just try to use as below. Hope it will work.

demoBtn->m_bTopImage = TRUE;


问:
What guarantees that different unrelated objects in two unrelated threads don't have an (unavoidable) race condition?
When different threads only use unrelated objects and literally do not share anything they cannot have a race condition, right? Obviously.

Actually all threads share something: the address space. There is no guarantee that a memory location that was used by one thread isn't going to be allocated at some other time to another thread. This can be true of memory for dynamically allocated objects or even for automatic objects: there is no prescription that the memory space for the "stacks" (the local objects of functions) of multiple threads is pre-allocated (even lazily), disjoint and represented as the usual linear "stack"; it could be anything with stack (FILO) behavior. So the memory location used to store an automatic object can be reused later by another automatic object in another thread.

That in itself seems pretty innocuous and uninteresting as how room is made for automatic objects is only important when room is missing (very large automatic arrays or deep recursion).

What about synchronisation? Unrelated disjoint threads obviously cannot use any C++ synchronisation primitive to ensure correct synchronisation as by definition there is nothing (to) synchronize (on), so no happens before relation is going to be created between threads.

What if the implementation reuses the memory range of the stack of foo() (including the location of i) after destruction of local variables and exit of foo() in thread 1 to store variables for bar() in thread 2?

```<code>void foo() { // in thread 1
   int i;
   i = 1;
}

void bar() { // in thread 2
   int i;
   i = 2;
}
</code>```

There is no happens before between i = 1 and i = 2.

Would that cause a data race and undefined behavior?

In other words, do all multithread programs have a potential for having undefined behavior based on implementation choices the user has no control over, that are unforeseeable and with races he can't do anything about?

答:
The physical machine's "same address" is irrelivant to the C++ memory model.  The C++ memory model talks about the behaviour of the abstract machine.  Addresses in the abstract machine can be incomparable in fundamenral way, even if they have the same machine address at different times.

Race conditions in the C++ abstract machine talk about operations in it, not on the physical machine.  It is the job of the compiler to ensure that the physical machine implementation of the abstract machine behaviour of the C++ code is conformant.

If it does strange things like reuse stack address space between threads, then it does whatever it has to in order to maintain the lack of race conditions that accessing unrelated variables in the abstract machine.  None of this happens at the C++ code level; there is no C++ code (other than possibly in namespace std) involved.

Body:
When different threads only use unrelated objects and literally do not share anything they cannot have a race condition, right? Obviously.

Actually all threads share something: the address space. There is no guarantee that a memory location that was used by one thread isn't going to be allocated at some other time to another thread. This can be true of memory for dynamically allocated objects or even for automatic objects: there is no prescription that the memory space for the "stacks" (the local objects of functions) of multiple threads is pre-allocated (even lazily), disjoint and represented as the usual linear "stack"; it could be anything with stack (FILO) behavior. So the memory location used to store an automatic object can be reused later by another automatic object in another thread.

That in itself seems pretty innocuous and uninteresting as how room is made for automatic objects is only important when room is missing (very large automatic arrays or deep recursion).

What about synchronisation? Unrelated disjoint threads obviously cannot use any C++ synchronisation primitive to ensure correct synchronisation as by definition there is nothing (to) synchronize (on), so no happens before relation is going to be created between threads.

What if the implementation reuses the memory range of the stack of foo() (including the location of i) after destruction of local variables and exit of foo() in thread 1 to store variables for bar() in thread 2?

void foo() { // in thread 1
   int i;
   i = 1;
}

void bar() { // in thread 2
   int i;
   i = 2;
}

There is no happens before between i = 1 and i = 2.

Would that cause a data race and undefined behavior?

In other words, do all multithread programs have a potential for having undefined behavior based on implementation choices the user has no control over, that are unforeseeable and with races he can't do anything about?


问:
JWT + SignalR on ASP Core 3 resulting in 401 Unauthorized
If I use http calls outside of signalr, such as with postman or httpclient, I am able to have my token validated successfully on the server. It's when I try to connect through my signalr hub that the token is not passing authorization.

Bearer was not authenticated. Failure message: No SecurityTokenValidator available for token: Bearer MyTokenFooBar

My service setup is:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddRouting();
    services.AddControllers();
    services.AddHealthChecks();
    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder => { builder.ConnectionString = _configuration.GetConnectionString("DefaultConnection"); }));
    services.AddIdentity<ApplicationUser, IdentityRole>(setup =>
    {
        // foo
    }).AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();

    services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            options.RequireHttpsMetadata = false;
            options.SaveToken = true;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidIssuer = _configuration["Jwt:Issuer"],
                ValidAudience = _configuration["Jwt:Audience"],
                ValidateIssuer = false,
                ValidateAudience = false,
                ValidateIssuerSigningKey = false,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"])),
                ValidateLifetime = false
            };

            options.Events = new JwtBearerEvents
            {
                OnMessageReceived = context =>
                {
                    var path = context.HttpContext.Request.Path;
                    if (!path.StartsWithSegments("/chat")) return Task.CompletedTask;
                    var accessToken = context.Request.Headers[HeaderNames.Authorization];
                    if (!string.IsNullOrWhiteSpace(accessToken) && context.Scheme.Name == JwtBearerDefaults.AuthenticationScheme)
                    {
                        context.Token = accessToken;
                    }

                    return Task.CompletedTask;
                }
            };
        });

    services.AddAuthorization();

    services.AddSignalR(options => { options.EnableDetailedErrors = true; });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(options =>
    {
        options.MapHealthChecks("/health");
        options.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
    });
    app.UseSignalR(options => { options.MapHub<ChatHub>("/chat"); });
}
</code>```

I use a basic http auth header for the initial connection, which will sign the user into identity and generate a jwt token as a response for use in future calls.

```<code>[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login()
{
    var (headerUserName, headerPassword) = GetAuthLoginInformation(HttpContext);

    var signInResult = await _signInManager.PasswordSignInAsync(headerUserName, headerPassword, false, false);
    if (!signInResult.Succeeded)
    {
        return Unauthorized();
    }

    var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SuperTopSecretKeyThatYouDoNotGiveOutEver!"));
    var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
    var jwt = new JwtSecurityToken(signingCredentials: signingCredentials);
    var handler = new JwtSecurityTokenHandler();
    var token = handler.WriteToken(jwt);
    return new OkObjectResult(token);
}
</code>```

And my client (a console application) is setup to cache this token and use it in future signalr calls as such:

Get the token:

```<code>_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(encoding.GetBytes($"{userName}:{password}")));
var response = await _client.SendAsync(request); // this goes to the login action posted above
_token = await response.Content.ReadAsStringAsync();
</code>```

...

```<code>_hubConnection = new HubConnectionBuilder()
    .WithUrl(new Uri(_baseAddress, "chat"),
        options => { options.AccessTokenProvider = () => Task.FromResult(_token); }) // send the cached token back with every request
    .Build();

// here is where the error occurs. 401 unauthorized comes back from this call.
await _hubConnection.StartAsync();
</code>```

答:
Resolved.

The issue was that I was overriding the OnMessageReceived handler of the JwtBearerHandler and then having it read the incoming token myself... but the token I was passing it included the prefix Bearer, which when parsed by the above handler did not match the known token for the existing user.

Simply removing my override of OnMessageReceived and letting AspNetCore's deafult implementation of the JwtBearerHandler do its job allowed the token parsing to work correctly.

Body:
If I use http calls outside of signalr, such as with postman or httpclient, I am able to have my token validated successfully on the server. It's when I try to connect through my signalr hub that the token is not passing authorization.

Bearer was not authenticated. Failure message: No SecurityTokenValidator available for token: Bearer MyTokenFooBar

My service setup is:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRouting();
    services.AddControllers();
    services.AddHealthChecks();
    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder => { builder.ConnectionString = _configuration.GetConnectionString("DefaultConnection"); }));
    services.AddIdentity<ApplicationUser, IdentityRole>(setup =>
    {
        // foo
    }).AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();

    services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            options.RequireHttpsMetadata = false;
            options.SaveToken = true;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidIssuer = _configuration["Jwt:Issuer"],
                ValidAudience = _configuration["Jwt:Audience"],
                ValidateIssuer = false,
                ValidateAudience = false,
                ValidateIssuerSigningKey = false,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"])),
                ValidateLifetime = false
            };

            options.Events = new JwtBearerEvents
            {
                OnMessageReceived = context =>
                {
                    var path = context.HttpContext.Request.Path;
                    if (!path.StartsWithSegments("/chat")) return Task.CompletedTask;
                    var accessToken = context.Request.Headers[HeaderNames.Authorization];
                    if (!string.IsNullOrWhiteSpace(accessToken) && context.Scheme.Name == JwtBearerDefaults.AuthenticationScheme)
                    {
                        context.Token = accessToken;
                    }

                    return Task.CompletedTask;
                }
            };
        });

    services.AddAuthorization();

    services.AddSignalR(options => { options.EnableDetailedErrors = true; });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(options =>
    {
        options.MapHealthChecks("/health");
        options.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
    });
    app.UseSignalR(options => { options.MapHub<ChatHub>("/chat"); });
}

I use a basic http auth header for the initial connection, which will sign the user into identity and generate a jwt token as a response for use in future calls.

[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login()
{
    var (headerUserName, headerPassword) = GetAuthLoginInformation(HttpContext);

    var signInResult = await _signInManager.PasswordSignInAsync(headerUserName, headerPassword, false, false);
    if (!signInResult.Succeeded)
    {
        return Unauthorized();
    }

    var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SuperTopSecretKeyThatYouDoNotGiveOutEver!"));
    var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
    var jwt = new JwtSecurityToken(signingCredentials: signingCredentials);
    var handler = new JwtSecurityTokenHandler();
    var token = handler.WriteToken(jwt);
    return new OkObjectResult(token);
}

And my client (a console application) is setup to cache this token and use it in future signalr calls as such:

Get the token:

_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(encoding.GetBytes($"{userName}:{password}")));
var response = await _client.SendAsync(request); // this goes to the login action posted above
_token = await response.Content.ReadAsStringAsync();

...

_hubConnection = new HubConnectionBuilder()
    .WithUrl(new Uri(_baseAddress, "chat"),
        options => { options.AccessTokenProvider = () => Task.FromResult(_token); }) // send the cached token back with every request
    .Build();

// here is where the error occurs. 401 unauthorized comes back from this call.
await _hubConnection.StartAsync();


问:
How to run multiple child runbooks against storage account
I have a powershell azure runbook that iterates through a large storage account and enforces file age policies on the blobs within the account. This runs fine but runs up against the Fair Share policy of 3 hours. I can use hybrid workers but I would prefer to run multiple child runbooks in parallel each handling a different portion of the blob account using the first letter prefix.

Example:

First child runbook runs A-M
Second: N-Z
Third: a-m
Fourth: m-z

I'm thinking of using a prefix variable within a loop that will iterate between letters.

```<code>## Declaring the variables
$number_of_days_bak_threshold = 15
$number_of_days_trn_threshold = 2
$current_date = get-date
$date_before_blobs_to_be_deleted_bak = $current_date.AddDays(-$number_of_days_bak_threshold)
$date_before_blobs_to_be_deleted_trn = $current_date.AddDays(-$number_of_days_trn_threshold)

# Number of blobs deleted
$blob_count_deleted = 0

# Storage account details
$storage_account_name = <Account Name>
$storage_account_key = <Account Key>
$container = <Container>

## Creating Storage context for Source, destination and log storage accounts
$context = New-AzureStorageContext -StorageAccountName $storage_account_name -StorageAccountKey $storage_account_key
$blob_list = Get-AzureStorageBlob -Context $context -Container $container

## Creating log file
$log_file = "log-"+(get-date).ToString().Replace('/','-').Replace(' ','-').Replace(':','-') + ".txt"
$local_log_file_path = $env:temp + "\" + "log-"+(get-date).ToString().Replace('/','-').Replace(' ','-').Replace(':','-') + ".txt"

write-host "Log file saved as: " $local_log_file_path -ForegroundColor Green

## Iterate through each blob
foreach($blob_iterator in $blob_list){

    $blob_date = [datetime]$blob_iterator.LastModified.UtcDateTime

    # Check if the blob's last modified date is less than the threshold date for deletion for trn files:
    if($blob_iterator.Name -Match ".trn") {
        if($blob_date -le $date_before_blobs_to_be_deleted_trn) {

        Write-Output "-----------------------------------" | Out-File $local_log_file_path -Append
        write-output "Purging blob from Storage: " $blob_iterator.name | Out-File $local_log_file_path -Append
        write-output " " | Out-File $local_log_file_path -Append
        write-output "Last Modified Date of the Blob: " $blob_date | Out-File $local_log_file_path -Append
        Write-Output "-----------------------------------" | Out-File $local_log_file_path -Append

        # Cmdle to delete the blob
        Remove-AzureStorageBlob -Container $container -Blob $blob_iterator.Name -Context $context

        $blob_count_deleted += 1
        Write-Output "Deleted "$extn
        }
    }
    Elseif($blob_iterator.Name -Match ".bak") {
        if($blob_date -le $date_before_blobs_to_be_deleted_bak) {

        Write-Output "-----------------------------------" | Out-File $local_log_file_path -Append
        write-output "Purging blob from Storage: " $blob_iterator.name | Out-File $local_log_file_path -Append
        write-output " " | Out-File $local_log_file_path -Append
        write-output "Last Modified Date of the Blob: " $blob_date | Out-File $local_log_file_path -Append
        Write-Output "-----------------------------------" | Out-File $local_log_file_path -Append

        # Cmdle to delete the blob
        Remove-AzureStorageBlob -Container $container -Blob $blob_iterator.Name -Context $context

        $blob_count_deleted += 1
        Write-Output "Deleted "$extn
        }
    }
    Else{
        Write-Error "Unable to determine file type." $blob_iterator.Name
    }
}
Write-Output "Blobs deleted: " $blob_count_deleted | Out-File $local_log_file_path -Append
</code>```

I expect to be able to run through the account in parallel.

答:
So, I agree with @4c74356b41 that breaking the workload down is the best approach.  However, that is itself, not always as simple as it might sound.  Below I describe the various workarounds for fairshare and the potential issues I can think of off the top of my head.  It as quite a lot of information, so here are the highlights:

Create jobs that do part of the work and then start the next job in the sequence.

Create jobs that all run on part of the sequence in parallel.

Create a runbook that does the work in parallel but also in a single job.

Use PowerShell Workflow with checkpoints so that your job is not subjected to fairshare.

Migrate the workload to use Azure Functions, e.g. Azure PowerShell functions.

TL;DR

No matter what, there are ways to breakup a sequential workload into sequentially executed jobs, e.g. each job works on a segment and then starts the next job as it's last operation.  (Like a kind of recursion.)  However, managing a sequential approach to correctly handle intermittent failures can add a lot of complexity.

If the workload can be broken down into smaller jobs that do not use a lot of resources, then you could do the work in parallel.  In other words, if the amount of memory and socket resources required by each segment is low, and as long as there is no overlap or contention, this approach should run in parallel much faster.  I also suspect that in parallel, the combined job minutes will still be less than the minutes necessary for a sequential approach.

There is one gotcha with processing the segments in parallel...

When a bunch of AA jobs belonging to the same account are started together, the tendency that they will all run within the same sandbox instance increases significantly.  Sandboxes are never shared with un-related accounts, but because of improvements in job start performance, there is a preference to share sandboxes for jobs within the same account.  When these jobs all run at the same time, there is an increased likelihood that the overall sandbox resource quota will be hit and then the sandbox will perform a hard exit immediately.

Because of this gotcha, if your workload is memory or socket intensive, you may want to have a parent runbook that controls the lifecycle (i.e. start rate) of the child runbooks.  This has the twisted effect that the parent runbook could now hit the fairshare limit.

The next workaround is to implement runbooks that kick off the job for the next processing segment when they are completed.  The best approach for this is to store the next segment somewhere the job can retrieve it, e.g. variable or blob.  This way, if a job fails with its segment, as long as there is some way of making sure the jobs run until the entire workload finishes, everything will eventually finish.  You might want to use a watcher task to verify eventual completion and handle retries.  Once you get to this level of complexity, you can experiment to discover how much parallelism you can introduce without hitting resource limits.

There is no way for a job to monitor the available resource and throttle itself.

There is no way to force each job to run in its own sandbox.

Whether jobs run in the same sandbox is very non-deterministic, which can cause problems with hard to trace intermittent failures.

If you have no worry for hitting resource limits, you could consider using the ThreadJob module on the PowerShell Gallery.  With this approach, you would still have a single runbook, but know you would be able to parallelize the workload within that runbook and complete the workload before hitting the fairshare limit.  This can be very effective if the individual tasks are fast and lightweight.  Otherwise, this approach may work for a little while but begin to fail if the workload increases in either the time or resources required.

Do not use PowerShell Jobs within an AA Job to achieve parallelism.  This includes not using commands like Parallel-ForEach.  There are a lot of examples for VM-Start/Stop runbooks that use PowerShell Jobs; this is not a recommend approach.  PowerShell Jobs require a lot of resources to execute, so using PowerShell Jobs will significantly increase the resources used by you AA Job and the chance of hitting the memory quota.

You can get around the fairshare limitation by re-implementing you code as a Power Shell Workflow and performing frequent checkpoints.  When a workflow job hits the fairshare limit, if it has been performing checkpoints, it will be restarted on another sandbox, resuming from the last checkpoint.

My recollection is your jobs need to perform a checkpoint at least once every 30 minutes.  If they do this, that will resume from the fairshare without any penalty, forever.  (At the cost of a tremendous number of job minutes.)

Even without a checkpoint, a workflow will get re-tried 2 times after hitting the checkpoint.  Because of this, if your workflow code is idempotent, and quickly will skip previously completed work, by using a workflow, your job may complete (in 9 hours) even without checkpoints.

However, workflow are not just Power Shell script wrapped inside a workflow {} script block:

There are a lot of subtle differences in the way workflow function compared to scripts.  Mastering these subtleties is difficult at best.

Workflow will not checkpoint all state during job execution.  For example, the big one is that you need to write your workflow so that it will re-authenticate with Azure after each checkpoint, because credentials are not captured by the checkpoint.

I don't think anyone is going to claim debugging an AA job is an easy task.  For workflow this task is even harder.  Even with all the correct dependencies, how a workflow runs when executed locally is different from how it executes in the cloud.

Script run measurably faster than workflow.

Migrate the work into Azure Functions.  With the recent release of PowerShell function, this might be relatively easy.  Functions will have different limitations than those in Automation.  This difference might suit your workload well, or be worse.  I have not yet tried the Functions approach, so I can't really say.

The most obvious difference you will notice right away is that Functions is a lot more of a raw, DevOps oriented service than Automation.  This is partly because Automation is a more mature product.  (Automation was probably the first widely available serverless service, having launched roughly a year before Lambda.)  Automation was purpose built for automating the management of cloud resources, and automation is the driving factor in the feature selection.  Whereas Functions is a much more general purpose serverless operations approach.  Anyway, one obvious difference at the moment is Functions does not have any built-in support for things like the RunAs account or Variables.  I expect Functions will improve in this specific aspect over time, but right now it is pretty basic for automation tasks.

Body:
I have a powershell azure runbook that iterates through a large storage account and enforces file age policies on the blobs within the account. This runs fine but runs up against the Fair Share policy of 3 hours. I can use hybrid workers but I would prefer to run multiple child runbooks in parallel each handling a different portion of the blob account using the first letter prefix.

Example:

First child runbook runs A-M
Second: N-Z
Third: a-m
Fourth: m-z

I'm thinking of using a prefix variable within a loop that will iterate between letters.

## Declaring the variables
$number_of_days_bak_threshold = 15
$number_of_days_trn_threshold = 2
$current_date = get-date
$date_before_blobs_to_be_deleted_bak = $current_date.AddDays(-$number_of_days_bak_threshold)
$date_before_blobs_to_be_deleted_trn = $current_date.AddDays(-$number_of_days_trn_threshold)

# Number of blobs deleted
$blob_count_deleted = 0

# Storage account details
$storage_account_name = <Account Name>
$storage_account_key = <Account Key>
$container = <Container>

## Creating Storage context for Source, destination and log storage accounts
$context = New-AzureStorageContext -StorageAccountName $storage_account_name -StorageAccountKey $storage_account_key
$blob_list = Get-AzureStorageBlob -Context $context -Container $container

## Creating log file
$log_file = "log-"+(get-date).ToString().Replace('/','-').Replace(' ','-').Replace(':','-') + ".txt"
$local_log_file_path = $env:temp + "\" + "log-"+(get-date).ToString().Replace('/','-').Replace(' ','-').Replace(':','-') + ".txt"

write-host "Log file saved as: " $local_log_file_path -ForegroundColor Green

## Iterate through each blob
foreach($blob_iterator in $blob_list){

    $blob_date = [datetime]$blob_iterator.LastModified.UtcDateTime

    # Check if the blob's last modified date is less than the threshold date for deletion for trn files:
    if($blob_iterator.Name -Match ".trn") {
        if($blob_date -le $date_before_blobs_to_be_deleted_trn) {

        Write-Output "-----------------------------------" | Out-File $local_log_file_path -Append
        write-output "Purging blob from Storage: " $blob_iterator.name | Out-File $local_log_file_path -Append
        write-output " " | Out-File $local_log_file_path -Append
        write-output "Last Modified Date of the Blob: " $blob_date | Out-File $local_log_file_path -Append
        Write-Output "-----------------------------------" | Out-File $local_log_file_path -Append

        # Cmdle to delete the blob
        Remove-AzureStorageBlob -Container $container -Blob $blob_iterator.Name -Context $context

        $blob_count_deleted += 1
        Write-Output "Deleted "$extn
        }
    }
    Elseif($blob_iterator.Name -Match ".bak") {
        if($blob_date -le $date_before_blobs_to_be_deleted_bak) {

        Write-Output "-----------------------------------" | Out-File $local_log_file_path -Append
        write-output "Purging blob from Storage: " $blob_iterator.name | Out-File $local_log_file_path -Append
        write-output " " | Out-File $local_log_file_path -Append
        write-output "Last Modified Date of the Blob: " $blob_date | Out-File $local_log_file_path -Append
        Write-Output "-----------------------------------" | Out-File $local_log_file_path -Append

        # Cmdle to delete the blob
        Remove-AzureStorageBlob -Container $container -Blob $blob_iterator.Name -Context $context

        $blob_count_deleted += 1
        Write-Output "Deleted "$extn
        }
    }
    Else{
        Write-Error "Unable to determine file type." $blob_iterator.Name
    }
}
Write-Output "Blobs deleted: " $blob_count_deleted | Out-File $local_log_file_path -Append

I expect to be able to run through the account in parallel.


问:
Action leaves the mic open

Your Action either leaves the mic open for a user command without a prompt such as a greeting, or an implicit or explicit question.

how can you solve this problem?

答: One easy solution while you're getting started is to ask "anything else I can help you with?" after any interaction that doesn't have a question and create a 'no' intent which will exit the app</p>

Title: Action leaves the mic open