问:
Indy10 Google Securetoken always 403
I am struggling to get a response from Google Securetoken using Delphi 10.2.2 and Indy 10.

I've gotten my RefreshToken before from https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=XXX. This worked fine.

Now I try to refresh the token with https://securetoken.googleapis.com/v1/token, which doesn't work. I always get a 403 Forbidden error.

procedure TForm1.Button2Click(Sender: TObject);
var
    l_Response: string;
    l_PostData: TIdMultiPartFormDataStream;
    l_IRESAccessToken: TIRESAccessToken;
begin
    IdHTTP2.Request.ContentType := 'application/json';
    IdHTTP2.Request.CharSet := 'utf-8';

    l_PostData := TIdMultiPartFormDataStream.Create;
    try
        l_PostData.AddFormField('grant_type', 'refresh_token');
        l_PostData.AddFormField('refresh_token', m_IRESAuth.RefreshToken);
        l_PostData.AddFormField('key', 'XXX');

        try
            l_Response := IdHTTP2.Post('https://securetoken.googleapis.com/v1/token', l_PostData);
            l_IRESAccessToken := TJson.JsonToObject<TIRESAccessToken>(l_Response);
        except
            on E: Exception do
                ShowMessage('Error on request: '#13#10 + e.Message);
        end;
    finally
        l_PostData.Free;
    end;
end;
```

I tried an IOHandler that specifies TLS 1.2, and tried to send the post with a JSON object.  Also, I set the hoKeepOrigProtocol flag in the TIdHTTP.HTTPOptions.  Nothing worked so far, I always get 403 Forbidden.

I tried it with another program, no problems there.

Am I missing something?

答:
Per Google's documentation:

Token Service REST API Reference:

HTTP request

POST https://securetoken.googleapis.com/v1/token

Request body

The request body contains data with the following structure:

URL-encoded representation

grant_type=string&code=string&refresh_token=string

The TStrings overload of TIdHTTP.Post() sends data in that format.  That is the overload you need to use, not the TIdMultipartFormDataStream overload.

Also, as you can see above, this URL does not accept your key as input.  It only accepts grant_type, code (which is ignored when grant_type is not 'authorization_code') and refresh_token.

Try this instead:

procedure TForm1.Button2Click(Sender: TObject);
var
  l_Response: string;
  l_PostData: TStringList;
  l_IRESAccessToken: TIRESAccessToken;
begin
  IdHTTP2.Request.ContentType := 'application/x-www-webform-urlencoded';

  l_PostData := TStringList.Create;
  try
    l_PostData.Add('grant_type=refresh_token');
    l_PostData.Add('refresh_token=' + m_IRESAuth.RefreshToken);

    try
      l_Response := IdHTTP2.Post('https://securetoken.googleapis.com/v1/token', l_PostData);
      l_IRESAccessToken := TJson.JsonToObject<TIRESAccessToken>(l_Response);
    except
      on E: Exception do
        ShowMessage('Error on request: '#13#10 + e.Message);
    end;
  finally
    l_PostData.Free;
  end;
end;
```

That being said, after reading the above documentation, I don't believe you can send an idToken from https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword to https://securetoken.googleapis.com/v1/token as a refresh_token.  I think you need to send it as an authorization_code instead, which then gives you a refresh_token.  So try adding that extra step, if you have not already done so.

Title: Indy10 Google Securetoken always 403

Body:
I am struggling to get a response from Google Securetoken using Delphi 10.2.2 and Indy 10.

I've gotten my RefreshToken before from https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=XXX. This worked fine.

Now I try to refresh the token with https://securetoken.googleapis.com/v1/token, which doesn't work. I always get a 403 Forbidden error.

procedure TForm1.Button2Click(Sender: TObject);
var
    l_Response: string;
    l_PostData: TIdMultiPartFormDataStream;
    l_IRESAccessToken: TIRESAccessToken;
begin
    IdHTTP2.Request.ContentType := 'application/json';
    IdHTTP2.Request.CharSet := 'utf-8';

    l_PostData := TIdMultiPartFormDataStream.Create;
    try
        l_PostData.AddFormField('grant_type', 'refresh_token');
        l_PostData.AddFormField('refresh_token', m_IRESAuth.RefreshToken);
        l_PostData.AddFormField('key', 'XXX');

        try
            l_Response := IdHTTP2.Post('https://securetoken.googleapis.com/v1/token', l_PostData);
            l_IRESAccessToken := TJson.JsonToObject<TIRESAccessToken>(l_Response);
        except
            on E: Exception do
                ShowMessage('Error on request: '#13#10 + e.Message);
        end;
    finally
        l_PostData.Free;
    end;
end;

I tried an IOHandler that specifies TLS 1.2, and tried to send the post with a JSON object.  Also, I set the hoKeepOrigProtocol flag in the TIdHTTP.HTTPOptions.  Nothing worked so far, I always get 403 Forbidden.

I tried it with another program, no problems there.

Am I missing something?

Body:
Per Google's documentation:

Token Service REST API Reference:

HTTP request

POST https://securetoken.googleapis.com/v1/token

Request body

The request body contains data with the following structure:

URL-encoded representation

grant_type=string&code=string&refresh_token=string

The TStrings overload of TIdHTTP.Post() sends data in that format.  That is the overload you need to use, not the TIdMultipartFormDataStream overload.

Also, as you can see above, this URL does not accept your key as input.  It only accepts grant_type, code (which is ignored when grant_type is not 'authorization_code') and refresh_token.

Try this instead:

procedure TForm1.Button2Click(Sender: TObject);
var
  l_Response: string;
  l_PostData: TStringList;
  l_IRESAccessToken: TIRESAccessToken;
begin
  IdHTTP2.Request.ContentType := 'application/x-www-webform-urlencoded';

  l_PostData := TStringList.Create;
  try
    l_PostData.Add('grant_type=refresh_token');
    l_PostData.Add('refresh_token=' + m_IRESAuth.RefreshToken);

    try
      l_Response := IdHTTP2.Post('https://securetoken.googleapis.com/v1/token', l_PostData);
      l_IRESAccessToken := TJson.JsonToObject<TIRESAccessToken>(l_Response);
    except
      on E: Exception do
        ShowMessage('Error on request: '#13#10 + e.Message);
    end;
  finally
    l_PostData.Free;
  end;
end;

That being said, after reading the above documentation, I don't believe you can send an idToken from https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword to https://securetoken.googleapis.com/v1/token as a refresh_token.  I think you need to send it as an authorization_code instead, which then gives you a refresh_token.  So try adding that extra step, if you have not already done so.


来源: stackexchange

问:
TestBed.OverrideProvider() doesn't work if TestBed.inject() or TestBed.get() (deprecated) has run before
Given the example spec test below

```<code>beforeEach(function () {
        TestBed.configureTestingModule({
            providers: [
                { provide: TranslateService, useClass: TranslateServiceMock },
                { provide: StoreService, useClass: StoreServiceMock },
                {
                    provide: GLOBAL_CONFIG_TOKEN,
                    useValue: { default: true }
                }
            ],
        });
        let config = TestBed.inject(GLOBAL_CONFIG_TOKEN);
});

it('should override provider otherwise what is the point? :)', () => {
  let config = TestBed.overrideProvider(GLOBAL_CONFIG_TOKEN, { useValue: { default: false, random: 'damn' } });
expect(config).toEqual({default: false, random: 'damn'});
});
</code>```

the thing is that test failed because default is always true and random is not a property of config. This means that config still has the default value during the configure of Testing Module and the provider hasn't been overridden.

Any idea why? Is overrideProvider method just a helper that updates the moduleRef object initially passed at configureTestingModule?

答:
That's right because there're built-in functions that trigger compilation of the test module. If you want to update the value after you need to reset the testBed, it's doable only via accessing private properties and therefore not recommended, better would be to write a proper test when env is created first and then its data is fetched.

Nevertheless that's what you can do before TestBed.overrideProvider to make it work.

  (getTestBed() as any)._instantiated = false;
  (getTestBed() as any)._moduleFactory = undefined;
```

ContentLicense: CC BY-SA 4.0

Body:
Given the example spec test below

beforeEach(function () {
        TestBed.configureTestingModule({
            providers: [
                { provide: TranslateService, useClass: TranslateServiceMock },
                { provide: StoreService, useClass: StoreServiceMock },
                {
                    provide: GLOBAL_CONFIG_TOKEN,
                    useValue: { default: true }
                }
            ],
        });
        let config = TestBed.inject(GLOBAL_CONFIG_TOKEN);
});

it('should override provider otherwise what is the point? :)', () => {
  let config = TestBed.overrideProvider(GLOBAL_CONFIG_TOKEN, { useValue: { default: false, random: 'damn' } });
expect(config).toEqual({default: false, random: 'damn'});
});

the thing is that test failed because default is always true and random is not a property of config. This means that config still has the default value during the configure of Testing Module and the provider hasn't been overridden.

Any idea why? Is overrideProvider method just a helper that updates the moduleRef object initially passed at configureTestingModule?


问:
Select only 1 child from each parent
One Author can have many Book. Table Book have Author_Id on it.

I Want a LINQ query that returns a IQueryable<Book> (So I can navigate with Book.Author.Name and stuff), but Only 1 Book per Author.

How do I do that with a LINQ?

答:
```<code>var authorsWithFirstBook =
    from book in Books
    group book by book.Author into authorBooks
    select authorBooks.First();
</code>```

That should give you the first book in the group.

You should then be able to do

```<code>foreach (var book in authorsWithFirstBook) {

  Console.WriteLine(book.Author.FirstName);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Select only 1 child from each parent

Body:
var authorsWithFirstBook =
    from book in Books
    group book by book.Author into authorBooks
    select authorBooks.First();

That should give you the first book in the group.

You should then be able to do

foreach (var book in authorsWithFirstBook) {

  Console.WriteLine(book.Author.FirstName);
}


问:
Using Invoke-Command but get error 'One or more computer names are not valid'

Invoke-Command : One or more computer names are not valid

I'm getting the error when running this command:

```<code>Invoke-Command -ComputerName $Targets -ScriptBlock $ScriptBlock
</code>```

$Targets is an array, which is populated by this command:

```<code>Get-ADComputer -Filter "Name -like '$Filter'" -SearchBase $OU |
    Select-Object -ExpandProperty Name |
    Sort-Object
</code>```

The computer names usually have - in them, but I tested computers without any special characters and got the same result.

Here is my method:

```<code>function Get-FilteredADComputers
{
     [CmdletBinding()]
     [OutputType([System.String[]])]
   param
       (
    [Parameter(Position = 0, Mandatory)]
    [ValidateSet('Site 1', 'Site 2', 'Site 3')]
    [String]
    $Site,

    [Parameter(Position = 1, Mandatory)]
    [ValidateSet('Client', 'Server')]
    [String]
    $ComputerType,
    [Parameter(Position = 2, Mandatory)]
    [String]
    $Filter
    )

$siteSecondLevel
switch($Site){
    "site 1"{$siteSecondLevel = "LVL 1"}
    "site 2"{$siteSecondLevel = "LVL 2"}
    "site 3"{$siteSecondLevel = "LVL 3"}
}
$OU = "OU=$ComputerType,OU=Devices,OU=$siteSecondLevel,OU=$Site,OU=MyOU,DC=mydomain,DC=com"
Get-ADComputer -Filter {Name -like $Filter} -SearchBase $OU | Select-Object -ExpandProperty Name | Sort-Object
}
</code>```

How I declare my list in a test environment:

```<code> $temp = Get-FilteredADComputers -Site Site1 -ComputerType Client -Filter
"myfilter"
$target = @()

foreach($t in $temp){
    if($t -ne $null -or $t -ne ""){
       $target += $t
       }
}
</code>```

I also get the same result by just declaring my array as $Targets = Get-FilteredADComputers

答:
Posting this for google search purposes.  My issue was that I was trying to pass a DevOps variable to a powershell script. I had to change my DevOps WebServers variable

From:

```<code>server1,server2,server3
</code>```

to:

```<code>@("server1","server2","server3")
</code>```

and in my powershell I used:

```<code>$p = "$(password)";
$sv = $(WebServers);  // --> I had to change this line and remove the quotes
$u = "$(username)";
</code>```

Body:
Invoke-Command : One or more computer names are not valid

I'm getting the error when running this command:

Invoke-Command -ComputerName $Targets -ScriptBlock $ScriptBlock

$Targets is an array, which is populated by this command:

Get-ADComputer -Filter "Name -like '$Filter'" -SearchBase $OU |
    Select-Object -ExpandProperty Name |
    Sort-Object

The computer names usually have - in them, but I tested computers without any special characters and got the same result.

Here is my method:

function Get-FilteredADComputers
{
     [CmdletBinding()]
     [OutputType([System.String[]])]
   param
       (
    [Parameter(Position = 0, Mandatory)]
    [ValidateSet('Site 1', 'Site 2', 'Site 3')]
    [String]
    $Site,

    [Parameter(Position = 1, Mandatory)]
    [ValidateSet('Client', 'Server')]
    [String]
    $ComputerType,
    [Parameter(Position = 2, Mandatory)]
    [String]
    $Filter
    )

$siteSecondLevel
switch($Site){
    "site 1"{$siteSecondLevel = "LVL 1"}
    "site 2"{$siteSecondLevel = "LVL 2"}
    "site 3"{$siteSecondLevel = "LVL 3"}
}
$OU = "OU=$ComputerType,OU=Devices,OU=$siteSecondLevel,OU=$Site,OU=MyOU,DC=mydomain,DC=com"
Get-ADComputer -Filter {Name -like $Filter} -SearchBase $OU | Select-Object -ExpandProperty Name | Sort-Object
}

How I declare my list in a test environment:

 $temp = Get-FilteredADComputers -Site Site1 -ComputerType Client -Filter
"myfilter"
$target = @()

foreach($t in $temp){
    if($t -ne $null -or $t -ne ""){
       $target += $t
       }
}

I also get the same result by just declaring my array as $Targets = Get-FilteredADComputers

Body:
Posting this for google search purposes.  My issue was that I was trying to pass a DevOps variable to a powershell script. I had to change my DevOps WebServers variable

From:

server1,server2,server3

to:

@("server1","server2","server3")

and in my powershell I used:

$p = "$(password)";
$sv = $(WebServers);  // --> I had to change this line and remove the quotes
$u = "$(username)";


问:
angular testing a component using jasmine when the a method call is made in the html
I have to test this odd situation. In my html i have:

```<code>    <div id="date">
      <h5>
        {{ showFormattedDate(myDate) }}
      </h5>
    </div>
</code>```

The function showFormattedDate() is defined in .ts as follows:

```<code>  showFormattedDate(dateToFormat: string): string {
    return moment(dateToFormat).format('HH:mm DD/M/YYYY');
  }
</code>```

Now i'm trying to test this but i keep getting this error:

Expected ' Created at Invalid date ' to be '12:23 29/5/2020'.

The invalid date part is also what i see for a split of a second on the screen when the page loads but that is because the function call, i think.

I've tried testing it using these two ways:

```<code>  it('should display the date correctly', async () => {
    fixture.detectChanges();
    // await fixture.whenStable();
    // await fixture.isStable();
    // await fixture.whenRenderingDone();

    expect(el.query(By.css('#date')).nativeElement.textContent).toContain(
      getTestData().date);
  });

  it('should display the date correctly (async)', async(() => {
    fixture.detectChanges();

    fixture.whenStable().then(() => {
      // wait for async getQuote
      fixture.detectChanges(); // update view with quote
      expect(el.query(By.css('#date')).nativeElement.textContent).toContain(getTestData().date);
    });
  }));
</code>```

But both return the aforementioned error. How could I solve this?

答:
Calling a method within a template expression is considered bad practice in angular.So you may want to avoid that first.

Read this for more details on that.

You can make use of Angular Pipe here which will which will transform your date to your desired format and you can test the transform method of your pipe.

For more details on usage of Angular pipe click here and to know how to test your angular pipe here is a good article for the same.

Body:
I have to test this odd situation. In my html i have:

        {{ showFormattedDate(myDate) }}

The function showFormattedDate() is defined in .ts as follows:

  showFormattedDate(dateToFormat: string): string {
    return moment(dateToFormat).format('HH:mm DD/M/YYYY');
  }

Now i'm trying to test this but i keep getting this error:

Expected ' Created at Invalid date ' to be '12:23 29/5/2020'.

The invalid date part is also what i see for a split of a second on the screen when the page loads but that is because the function call, i think.

I've tried testing it using these two ways:

  it('should display the date correctly', async () => {
    fixture.detectChanges();
    // await fixture.whenStable();
    // await fixture.isStable();
    // await fixture.whenRenderingDone();

    expect(el.query(By.css('#date')).nativeElement.textContent).toContain(
      getTestData().date);
  });

  it('should display the date correctly (async)', async(() => {
    fixture.detectChanges();

    fixture.whenStable().then(() => {
      // wait for async getQuote
      fixture.detectChanges(); // update view with quote
      expect(el.query(By.css('#date')).nativeElement.textContent).toContain(getTestData().date);
    });
  }));

But both return the aforementioned error. How could I solve this?


问:
Projecting points onto 3D terrain surface in UWP MapControl
I'm creating a windows desktop app using the UWP Map control (MapControl) and inking based on this blog post.

I have the basics working. can draw ink on the canvas and convert them to map locations, but I can't get the points to correctly project onto the map 3D surface.

I'm using mapControl.GetLocationFromOffset to transform the control-space offset to map position but no matter what AltitudeReferenceSystem I use the points are offset above or below the 3D mesh.  I'm basically trying to emulate how inking works in the built in windows Maps app.  But since there's a pause after drawing each stroke I'm thinking it's doing some ray casting onto the 3D mesh. Lat/Long are correct but altitude has an offset.

```<code>Geopoint GeopointFromPoint(Point point)
{
   Geopoint geoPoint = null;
   this.map.GetLocationFromOffset(point, AltitudeReferenceSystem.Geoid, out geoPoint); // Tried all alt ref systems here
   return (geoPoint);
}
...
BasicGeoposition curP;
foreach (var segment in firstStroke.GetRenderingSegments())
{
   curP = GeopointFromPoint(segment.Position).Position;
   geoPoints.Add(curP);
}
...
</code>```

This is my inking around a patch of grass in the Maps App which determines correct altitude:

And the same area using the Map control + GetLocationFromOffset, blue ink is annotation showing altitude offset:

How can I project screen/control space coordinates onto the 3D mesh in the UWP Map control and get the correct altitude?

Edit: And the answer is I'm an idiot, have been thinking in meters from center of earth too long, ie I thought altitude was the altitude above sea level of the map location, but it's not, it's the points altitude above the map.  So just setting altitude to zero works.

答:
Just setting the altitude to zero may still produce unexpected results. The call to GetLocationFromOffset is where your issue is. (you should really use TryGetLocationFromOffset BTW and handle failure cases - it isn't always possible to map a screen offset to a location, for example when you click above the horizon).
The AltitudeReference you pass is is telling the control what to intersect with. You can think of it as a ray you're shooting into the 3D scene at that screen pixel. The ray will intersect the Surface first, then the terrain, then the Geoid or Ellipsoid depending on where you are. You were asking for the intersection with the Geoid, which probably wasn't what you really wanted. You probably want the intersection with the surface for an inking case. The docs aren't terribly clear on what this parameter does and should probably be updated.

If you reset all altitudes to 0 with an altitude reference of surface for the line you pass in, it will always put the line on the surface, but that might not match your ink.

There may actually be a bug here - if your code snippet above was passing the Geopoint returned from GetLocationFromOffset to the polyline, it should appear at the same pixel (you should be able to round-trip values). What was the AltitudeReferenceSystem and value returned for these GeoPoints?

Body:
I'm creating a windows desktop app using the UWP Map control (MapControl) and inking based on this blog post.

I have the basics working. can draw ink on the canvas and convert them to map locations, but I can't get the points to correctly project onto the map 3D surface.

I'm using mapControl.GetLocationFromOffset to transform the control-space offset to map position but no matter what AltitudeReferenceSystem I use the points are offset above or below the 3D mesh.  I'm basically trying to emulate how inking works in the built in windows Maps app.  But since there's a pause after drawing each stroke I'm thinking it's doing some ray casting onto the 3D mesh. Lat/Long are correct but altitude has an offset.

Geopoint GeopointFromPoint(Point point)
{
   Geopoint geoPoint = null;
   this.map.GetLocationFromOffset(point, AltitudeReferenceSystem.Geoid, out geoPoint); // Tried all alt ref systems here
   return (geoPoint);
}
...
BasicGeoposition curP;
foreach (var segment in firstStroke.GetRenderingSegments())
{
   curP = GeopointFromPoint(segment.Position).Position;
   geoPoints.Add(curP);
}
...

This is my inking around a patch of grass in the Maps App which determines correct altitude:

And the same area using the Map control + GetLocationFromOffset, blue ink is annotation showing altitude offset:

How can I project screen/control space coordinates onto the 3D mesh in the UWP Map control and get the correct altitude?

Edit: And the answer is I'm an idiot, have been thinking in meters from center of earth too long, ie I thought altitude was the altitude above sea level of the map location, but it's not, it's the points altitude above the map.  So just setting altitude to zero works.


问:
Ternary operator in perl yields unexpected result when assigning a variable in the statement
I'm trying to make a transition from php to perl and expectedly running into some weirdness.  I cannot understand why one version of my code works vs another.

This fails:

```<code>sub tester
{
$return;
($_[0] < 10) ? $return = "youre a youngin" : $return = "youre an old person";
return $return;
}

print "how old are you?";
$a = <>;
chomp $a;

print  tester($a);  #both result in "youre an old person"
</code>```

however this one works:

```<code>sub tester
{
    return ($_[0] < 10) ? "youre a youngin" : "youre an old person";
}

print "how old are you?";
$a = <>;
chomp $a;
print  tester($a);
</code>```

what is the real difference here?!

答:
It is related to Perl's operator precedence. In Perl,

```<code>($_[0] < 10) ? $return = "youre a youngin" : $return = "youre an old fart";
</code>```

is same as

```<code>( ($_[0] < 10) ? $return = "youre a youngin" : $return ) = "youre an old fart";
</code>```

notice the paren binds to the FRONT.

and this leads to another confusing feature of Perl: conditional lvalues: You can do this
(CONDITION ? $ASSIGN_A_IF_CONDITION_IS_TRUE : $ASSIGN_B_IF_CONDITION_IS_FALSE) = 2

Here is a fix

```<code>($_[0] < 10) ? ($return = "youre a youngin") : ($return = "youre an old fart");
</code>```

http://codepad.org/MxBAy7wy

EDIT:

However, most people would write

```<code>$return = ($_[0] < 10) ? "youre a youngin" : "youre an old fart";
</code>```

, saving the redundancy of typing the variable twice.

According to Perl and PHP docs, Perl ?: is right-associative and PHP ?: is left-associative. (http://perldoc.perl.org/perlop.html ) (http://php.net/manual/en/language.operators.precedence.php )

Body:
I'm trying to make a transition from php to perl and expectedly running into some weirdness.  I cannot understand why one version of my code works vs another.

This fails:

sub tester
{
$return;
($_[0] < 10) ? $return = "youre a youngin" : $return = "youre an old person";
return $return;
}

print "how old are you?";
$a = <>;
chomp $a;

print  tester($a);  #both result in "youre an old person"

however this one works:

sub tester
{
    return ($_[0] < 10) ? "youre a youngin" : "youre an old person";
}

print "how old are you?";
$a = <>;
chomp $a;
print  tester($a);

what is the real difference here?!

Body:
It is related to Perl's operator precedence. In Perl,

($_[0] < 10) ? $return = "youre a youngin" : $return = "youre an old fart";

is same as

( ($_[0] < 10) ? $return = "youre a youngin" : $return ) = "youre an old fart";

notice the paren binds to the FRONT.

and this leads to another confusing feature of Perl: conditional lvalues: You can do this
(CONDITION ? $ASSIGN_A_IF_CONDITION_IS_TRUE : $ASSIGN_B_IF_CONDITION_IS_FALSE) = 2

Here is a fix

($_[0] < 10) ? ($return = "youre a youngin") : ($return = "youre an old fart");

http://codepad.org/MxBAy7wy

EDIT:

However, most people would write

$return = ($_[0] < 10) ? "youre a youngin" : "youre an old fart";

, saving the redundancy of typing the variable twice.

According to Perl and PHP docs, Perl ?: is right-associative and PHP ?: is left-associative. (http://perldoc.perl.org/perlop.html ) (http://php.net/manual/en/language.operators.precedence.php )


问:
list of json files into jsonL file using Python
I have a directory with a large number of json files. Now I want python to read them all in and creates a single jsonl output file.

Here is a post that did something similar (Python conversion from JSON to JSONL), but in comparison to this post the starting point of my question is reading the jsons in to create python object first, before converting them into jsonl.

答:
Here's how you read json files from a directory in python and then output the loaded json files into a single jsonl file:

```<code>import os, json
import pandas as pd

directory = '/Path/To/Your/Json/Directory'  #Specify your json directory path here

json_list=[]    #Initiate a new blank list for storing json data in list format
for dirpath, subdirs, files in os.walk(directory):
    print(dirpath)
    print(filename)
    print(file)
    for file in files:
        if file.endswith(".json"):
            with open(os.path.join(dirpath, file)) as json_file:
                data = json.load(json_file)
                json_list.append(data)

#Now, output the list of json data into a single jsonl file
with open('output.jsonl', 'w') as outfile:
    for entry in json_list:
        json.dump(entry, outfile)
        outfile.write('\n')
</code>```

Body:
Here's how you read json files from a directory in python and then output the loaded json files into a single jsonl file:

import os, json
import pandas as pd

directory = '/Path/To/Your/Json/Directory'  #Specify your json directory path here

json_list=[]    #Initiate a new blank list for storing json data in list format
for dirpath, subdirs, files in os.walk(directory):
    print(dirpath)
    print(filename)
    print(file)
    for file in files:
        if file.endswith(".json"):
            with open(os.path.join(dirpath, file)) as json_file:
                data = json.load(json_file)
                json_list.append(data)

#Now, output the list of json data into a single jsonl file
with open('output.jsonl', 'w') as outfile:
    for entry in json_list:
        json.dump(entry, outfile)
        outfile.write('\n')


问:
OpenAPI. Invalid request example with Generic
I get invalide request example and schema if user Generic, but i get valid response type.

How can I get a correct view?

```<code>@RestController
public abstract class BaseController<D extends BaseObject> {

    @PostMapping
    @Operation(summary = "create")
    public ResponseEntity<D> create(@RequestBody Wrapper<D> payload) {
        return ResponseEntity.ok(payload.getPayload());
    }
}
</code>```

```<code>@RestController
@Tag(name = "example")
public class FirstController extends BaseController<CustomerDto> {

}
</code>```

ps. Invalide request example is object with fields only from parent class/interface - BaseObject

```<code><dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-webmvc-core</artifactId>
    <version>1.3.9</version>
</dependency>
</code>```

答:
You can use v1.4.0, where the support for wrapper types on request has been improved.</p>

```<code><dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-webmvc-core</artifactId>
    <version>1.4.0</version>
</dependency>
</code>```

Body:
I get invalide request example and schema if user Generic, but i get valid response type.

How can I get a correct view?

@RestController
public abstract class BaseController<D extends BaseObject> {

    @PostMapping
    @Operation(summary = "create")
    public ResponseEntity<D> create(@RequestBody Wrapper<D> payload) {
        return ResponseEntity.ok(payload.getPayload());
    }
}

@RestController
@Tag(name = "example")
public class FirstController extends BaseController<CustomerDto> {

}

ps. Invalide request example is object with fields only from parent class/interface - BaseObject

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-webmvc-core</artifactId>
    <version>1.3.9</version>
</dependency>

Body:
You can use v1.4.0, where the support for wrapper types on request has been improved.

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-webmvc-core</artifactId>
    <version>1.4.0</version>
</dependency>


问:
Python: "self" in inheritance
A basic question on inheritance and "self" here.

Good code with no error:
(Correction: Turns out this is NOT GOOD, either. Please refer to MisterMiyagi's answers below.)

```<code>class A:
  def __init__(self, a):
    self.a = 10
    self.b = { 'a': 10, 'b': 20 }
    self.c = [ 1, 2, 3 ]

class B(A):
  def __init__(self):
    super().__init__(self)
    print(self.a)
    print(self.b)
    print(self.c)

i = B()
</code>```

Bad code with errors:

```<code>class A:
  def __init__(self, a, b, c):
    self.a = 10
    self.b = { 'a': 10, 'b': 20 }
    self.c = [ 1, 2, 3 ]

class B(A):
  def __init__(self):
    super().__init__(self)
    print(self.a)
    print(self.b)
    print(self.c)

i = B()
</code>```

ERROR:

```<code>Traceback (most recent call last):
  File "./o", line 16, in <module>
    i = B()
  File "./o", line 11, in __init__
    super().__init__(self)
TypeError: __init__() missing 2 required positional arguments: 'b' and 'c'
</code>```

Could you please explain why it has to be:

```<code>class A:
  def __init__(self, a):
</code>```

but neither

```<code>class A:
  def __init__(self):
</code>```

nor

```<code>class A:
  def __init__(self, a, b, c):
</code>```

?

Thank you!

答:
A's constructor takes 3 arguments, and you're giving it 1.  That's the reason for the error.

Since it doesn't use any of the 3 arguments, it should take 0 arguments, and B in turn should give it 0 arguments:

```<code>class A:
  def __init__(self):
    self.a = 10
    self.b = { 'a': 10, 'b': 20 }
    self.c = [ 1, 2, 3 ]

class B(A):
  def __init__(self):
    super().__init__()
    print(self.a)
    print(self.b)
    print(self.c)

i = B()
</code>```

Title: Python: "self" in inheritance

Body:
A basic question on inheritance and "self" here.

Good code with no error:
(Correction: Turns out this is NOT GOOD, either. Please refer to MisterMiyagi's answers below.)

class A:
  def __init__(self, a):
    self.a = 10
    self.b = { 'a': 10, 'b': 20 }
    self.c = [ 1, 2, 3 ]

class B(A):
  def __init__(self):
    super().__init__(self)
    print(self.a)
    print(self.b)
    print(self.c)

i = B()

Bad code with errors:

class A:
  def __init__(self, a, b, c):
    self.a = 10
    self.b = { 'a': 10, 'b': 20 }
    self.c = [ 1, 2, 3 ]

class B(A):
  def __init__(self):
    super().__init__(self)
    print(self.a)
    print(self.b)
    print(self.c)

i = B()

ERROR:

Traceback (most recent call last):
  File "./o", line 16, in <module>
    i = B()
  File "./o", line 11, in __init__
    super().__init__(self)
TypeError: __init__() missing 2 required positional arguments: 'b' and 'c'

Could you please explain why it has to be:

class A:
  def __init__(self, a):

but neither

class A:
  def __init__(self):

nor

class A:
  def __init__(self, a, b, c):

?

Thank you!

Body:
A's constructor takes 3 arguments, and you're giving it 1.  That's the reason for the error.

Since it doesn't use any of the 3 arguments, it should take 0 arguments, and B in turn should give it 0 arguments:

class A:
  def __init__(self):
    self.a = 10
    self.b = { 'a': 10, 'b': 20 }
    self.c = [ 1, 2, 3 ]

class B(A):
  def __init__(self):
    super().__init__()
    print(self.a)
    print(self.b)
    print(self.c)

i = B()


答:
Maybe this regex will work for you?

/\\"p\\":\\"\((.+?)\)\\"/

Tested here: https://regexr.com/55kah

Title: Extract some part of data from json using regex?

Body:
My json looks like this.

{"d":2,"g":"(0.006, 1.000, -0.013, 0.584)","o":"0.081","t":"{\"Items\":[{\"f\":9,\"b\":{\"i\":72057594037929100,\"j\":[{\"s\":2,\"p\":\"(4.342, 76.616, 235.211)\",\"q\":\"(0.5, 0.2)\",\"o\":\"(0.000, 0.000, 0.000, 0.000)\"},{\"s\":2,\"p\":\"(6.307, 63.818, 237.308)\",\"q\":\"(0.5, 0.3)\",\"o\":\"(0.009, 0.988, -0.075, -0.137)\"},{\"s\":2,\"p\":\"(-6.896, 54.626, 241.427)\",\"q\":\"(0.5, 0.3)\",\"o\":\"(0.780, -0.615, -0.055, 0.103)\"},{\"s\":2,\"p\":\"(19.263, 53.431, 233.939)\",\"q\":\"(0.6, 0.3)\",\"o\":\"(0.790, 0.587, -0.161, -0.071)\"},{\"s\":2,\"p\":\"(-9.756, 36.885, 247.644)\",\"q\":\"(0.5, 0.4)\",\"o\":\"(0.708, -0.170, -0.682, 0.067)\"},{\"s\":2,\"p\":\"(32.613, 40.022, 228.385)\",\"q\":\"(0.6, 0.3)\",\"o\":\"(0.869, 0.301, 0.292, -0.263)\"},{\"s\":2,\"p\":\"(-10.174, 26.525, 230.599)\",\"q\":\"(0.5, 0.4)\",\"o\":\"(0.838, -0.145, 0.238, -0.468)\"},{\"s\":2,\"p\":\"(18.386, 34.191, 215.852)\",\"q\":\"(0.6, 0.3)\",\"o\":\"(-0.159, -0.297, 0.789, 0.515)\"},{\"s\":2,\"p\":\"(-8.486, 24.193, 232.817)\",\"q\":\"(0.5, 0.4)\",\"o\":\"(0.310, 0.404, 0.851, -0.126)\"},{\"s\":2,\"p\":\"(18.643, 35.331, 216.844)\",\"q\":\"(0.6, 0.3)\",\"o\":\"(0.296, -0.315, -0.201, 0.879)\"},{\"s\":2,\"p\":\"(6.328, 57.728, 238.241)\",\"q\":\"(0.5, 0.3)\",\"o\":\"(0.006, 0.989, -0.054, -0.137)\"},{\"s\":2,\"p\":\"(6.372, 39.007, 240.290)\",\"q\":\"(0.5, 0.3)\",\"o\":\"(0.004, 0.990, -0.038, -0.136)\"},{\"s\":2,\"p\":\"(6.421, 13.412, 242.259)\",\"q\":\"(0.5, 0.4)\",\"o\":\"(0.004, 0.990, -0.038, -0.135)\"},{\"s\":2,\"p\":\"(0.544, 13.591, 240.701)\",\"q\":\"(0.5, 0.4)\",\"o\":\"(-0.687, 0.714, -0.116, 0.066)\"},{\"s\":2,\"p\":\"(12.142, 12.902, 237.523)\",\"q\":\"(0.5, 0.4)\",\"o\":\"(0.680, 0.649, -0.268, -0.212)\"},{\"s\":2,\"p\":\"(-8.352, -7.874, 228.395)\",\"q\":\"(0.5, 0.5)\",\"o\":\"(-0.438, -0.137, 0.847, 0.270)\"},{\"s\":2,\"p\":\"(12.378, -15.666, 235.192)\",\"q\":\"(0.5, 0.5)\",\"o\":\"(0.794, -0.021, 0.606, -0.035)\"},{\"s\":2,\"p\":\"(-1.073, -37.353, 238.874)\",\"q\":\"(0.5, 0.6)\",\"o\":\"(-0.659, 0.050, 0.717, -0.222)\"},{\"s\":2,\"p\":\"(15.474, -46.941, 242.354)\",

And I want to extract only the numbers which starts inside the "p\": for example "p\":\"(4.342, 76.616, 235.211)\"

I tried using regex, but it is returning null output.

Code that I tried to run

import re

with open('skeleton.json') as file:

    for line in file:
       headings = re.search('\\\"p\\\":\\\"\([\d, \-.]+\)\\\"', line)
       print(headings)


问:
How do I cross-compile a Qt-project with a recipe in yocto
I am trying to Cross-compile a qt-project from a recipe. I have created a recipe file but when I try to bitbake it. I am met with error

Here is my recipe file

```<code>DESCRIPITION = "my_project File Transfer"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

SRC_URI = "git://git@bitbucket.org/johndoe/my_ui.git;protocol=ssh;rev=master"

S = "${WORKDIR}/git/my_project"

RDEPENDS_${PN} ="bash"
inherit qmake5
require recipes-qt/qt5/qt5.inc

do_install_append() {
    ## Creating Folder Structure
    install -d ${D}/opt/my_project/bin
    install -d ${D}/home/root/my_project
    install -d ${D}/home/root/my_project/font
    install -d ${D}/home/root/my_project/Images
    install -d ${D}/home/root/my_project/Qml
    ###compile the project
    oe_runmake INSTALL_ROOT=${D} install
    #### Copying files
    install -m 0755 ${S}/font/* ${D}/home/root/my_project/font/
    install -m 0755 ${S}/Images/* ${D}/home/root/my_project/Images/
    install -m 0755 ${S}/Qml/* ${D}/home/root/my_project/Qml/
}

FILES_${PN} = "/home/root/my_project"
</code>```

The error that I see is

```<code>Sstate summary: Wanted 335 Found 327 Missed 8 Current 1958 (97% match, 99% complete)
NOTE: Executing SetScene Tasks
NOTE: Executing RunQueue Tasks
ERROR: myproject-project-1.0-r0 do_configure: Error calling /home/blue/yacto/rpi-qt5/build/tmp/work/all-poky-linux/myproject-project/1.0-r0/recipe-sysroot-native/usr/bin/qmake -makefile -o Makefile        /home/blue/yacto/rpi-qt5/build/tmp/work/all-poky-linux/myproject-project/1.0-r0/git/myproject/myproject.pro  --
ERROR: myproject-project-1.0-r0 do_configure: Function failed: do_configure (log file is located at /home/blue/yacto/rpi-qt5/build/tmp/work/all-poky-linux/myproject-project/1.0-r0/temp/log.do_configure.20982)
ERROR: Logfile of failure stored in: /home/blue/yacto/rpi-qt5/build/tmp/work/all-poky-linux/myproject-project/1.0-r0/temp/log.do_configure.20982
Log data follows:
| DEBUG: Executing shell function qmake5_base_preconfigure
| DEBUG: Shell function qmake5_base_preconfigure finished
| DEBUG: Executing shell function do_configure
| NOTE: qmake prevar substitution: '   '
| Could not find qmake spec 'linux-oe-g++'.
| Error processing project file: /home/blue/yacto/rpi-qt5/build/tmp/work/all-poky-linux/myproject-project/1.0-r0/git/myproject/myproject.pro
| ERROR: Error calling /home/blue/yacto/rpi-qt5/build/tmp/work/all-poky-linux/myproject-project/1.0-r0/recipe-sysroot-native/usr/bin/qmake -makefile -o Makefile        /home/blue/yacto/rpi-qt5/build/tmp/work/all-poky-linux/myproject-project/1.0-r0/git/myproject/myproject.pro  --
| WARNING: exit code 1 from a shell command.
| ERROR: Function failed: do_configure (log file is located at /home/blue/yacto/rpi-qt5/build/tmp/work/all-poky-linux/myproject-project/1.0-r0/temp/log.do_configure.20982)
ERROR: Task (/home/blue/yacto/poky-warrior-21.0.1/meta-rpi_custom/recipes-custom/myproject-project/myproject-project_1.0.bb:do_configure) failed with exit code '1'
NOTE: Tasks Summary: Attempted 4242 tasks of which 4241 didn't need to be rerun and 1 failed.

Summary: 1 task failed:
  /home/blue/yacto/poky-warrior-21.0.1/meta-rpi_custom/recipes-custom/myproject-project/myproject-project_1.0.bb:do_configure
</code>```

I know that in order to cross-compile. I had to run qmake from my cross-compile tool-chain location and then run make command on it.

I am guessing that is what's missing in my recipe. So my question is, Do I add that in my do_configure
if thats the case can anyone help me or point me how do I populate my do_configure
Is it as simple as source /opt/poky/2.7.1/environment----
then qmake

I am drawing a blank at this step

Please let me know what am I doing wrong

Edit1: remove inherit allarch from recipe

答: I would just leave inherit qmake5 and put DEPENDS + = "qtbase qtxyz ...", qtxyz would be the list of other dependency modules.

Body:
I am trying to Cross-compile a qt-project from a recipe. I have created a recipe file but when I try to bitbake it. I am met with error

Here is my recipe file

DESCRIPITION = "my_project File Transfer"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

SRC_URI = "git://git@bitbucket.org/johndoe/my_ui.git;protocol=ssh;rev=master"

S = "${WORKDIR}/git/my_project"

RDEPENDS_${PN} ="bash"
inherit qmake5
require recipes-qt/qt5/qt5.inc

do_install_append() {
    ## Creating Folder Structure
    install -d ${D}/opt/my_project/bin
    install -d ${D}/home/root/my_project
    install -d ${D}/home/root/my_project/font
    install -d ${D}/home/root/my_project/Images
    install -d ${D}/home/root/my_project/Qml
    ###compile the project
    oe_runmake INSTALL_ROOT=${D} install
    #### Copying files
    install -m 0755 ${S}/font/* ${D}/home/root/my_project/font/
    install -m 0755 ${S}/Images/* ${D}/home/root/my_project/Images/
    install -m 0755 ${S}/Qml/* ${D}/home/root/my_project/Qml/
}

FILES_${PN} = "/home/root/my_project"

The error that I see is

Sstate summary: Wanted 335 Found 327 Missed 8 Current 1958 (97% match, 99% complete)
NOTE: Executing SetScene Tasks
NOTE: Executing RunQueue Tasks
ERROR: myproject-project-1.0-r0 do_configure: Error calling /home/blue/yacto/rpi-qt5/build/tmp/work/all-poky-linux/myproject-project/1.0-r0/recipe-sysroot-native/usr/bin/qmake -makefile -o Makefile        /home/blue/yacto/rpi-qt5/build/tmp/work/all-poky-linux/myproject-project/1.0-r0/git/myproject/myproject.pro  --
ERROR: myproject-project-1.0-r0 do_configure: Function failed: do_configure (log file is located at /home/blue/yacto/rpi-qt5/build/tmp/work/all-poky-linux/myproject-project/1.0-r0/temp/log.do_configure.20982)
ERROR: Logfile of failure stored in: /home/blue/yacto/rpi-qt5/build/tmp/work/all-poky-linux/myproject-project/1.0-r0/temp/log.do_configure.20982
Log data follows:
| DEBUG: Executing shell function qmake5_base_preconfigure
| DEBUG: Shell function qmake5_base_preconfigure finished
| DEBUG: Executing shell function do_configure
| NOTE: qmake prevar substitution: '   '
| Could not find qmake spec 'linux-oe-g++'.
| Error processing project file: /home/blue/yacto/rpi-qt5/build/tmp/work/all-poky-linux/myproject-project/1.0-r0/git/myproject/myproject.pro
| ERROR: Error calling /home/blue/yacto/rpi-qt5/build/tmp/work/all-poky-linux/myproject-project/1.0-r0/recipe-sysroot-native/usr/bin/qmake -makefile -o Makefile        /home/blue/yacto/rpi-qt5/build/tmp/work/all-poky-linux/myproject-project/1.0-r0/git/myproject/myproject.pro  --
| WARNING: exit code 1 from a shell command.
| ERROR: Function failed: do_configure (log file is located at /home/blue/yacto/rpi-qt5/build/tmp/work/all-poky-linux/myproject-project/1.0-r0/temp/log.do_configure.20982)
ERROR: Task (/home/blue/yacto/poky-warrior-21.0.1/meta-rpi_custom/recipes-custom/myproject-project/myproject-project_1.0.bb:do_configure) failed with exit code '1'
NOTE: Tasks Summary: Attempted 4242 tasks of which 4241 didn't need to be rerun and 1 failed.

Summary: 1 task failed:
  /home/blue/yacto/poky-warrior-21.0.1/meta-rpi_custom/recipes-custom/myproject-project/myproject-project_1.0.bb:do_configure

I know that in order to cross-compile. I had to run qmake from my cross-compile tool-chain location and then run make command on it.

I am guessing that is what's missing in my recipe. So my question is, Do I add that in my do_configure
if thats the case can anyone help me or point me how do I populate my do_configure
Is it as simple as source /opt/poky/2.7.1/environment----
then qmake

I am drawing a blank at this step

Please let me know what am I doing wrong

Edit1: remove inherit allarch from recipe


问:
Why is Interop.WMPLib unable to load assembly in Release mode, but works in Debug mode?
I have added the Windows Media Player com control into my toolbox and then used the control successfully on a Form in Debug mode.

However, when I try running the application in Release mode it errors with...

Could not load file or assembly
  'Interop.WMPLib, ... or one of its
  dependecies. An attempt was made to
  load a program with an incorrect
  format.

Through some tracing I've established that the error occurs not when creating the control but on the EndInit method.

```<code>Public Sub New

    InitializeComponent()

    wmp = New AxWMPLib.AxWindowsMediaPlayer()
    wmp.BeginInit()
    wmp.Enabled = True
    wmp.Name = "wmp"
    wmp.OcxState = CType(resources.GetObject("wmp.OcxState"), AxHost.State)
    Me.Controls.Add(wmp)
    Me.Controls.SetChildIndex(wmp, 0)
    wmp.Dock = System.Windows.Forms.DockStyle.Fill
    wmp.EndInit()   ' <<< errors here !

End Sub
</code>```

What am I missing?

答: You changed the Platform target setting in the Debug configuration.  Possibly weeks ago, maybe even in a previous version of Visual Studio.  But didn't change it in the Release configuration.  It is one of the settings that is configuration specific.</p>

Body:
I have added the Windows Media Player com control into my toolbox and then used the control successfully on a Form in Debug mode.

However, when I try running the application in Release mode it errors with...

Could not load file or assembly
  'Interop.WMPLib, ... or one of its
  dependecies. An attempt was made to
  load a program with an incorrect
  format.

Through some tracing I've established that the error occurs not when creating the control but on the EndInit method.

Public Sub New

    InitializeComponent()

    wmp = New AxWMPLib.AxWindowsMediaPlayer()
    wmp.BeginInit()
    wmp.Enabled = True
    wmp.Name = "wmp"
    wmp.OcxState = CType(resources.GetObject("wmp.OcxState"), AxHost.State)
    Me.Controls.Add(wmp)
    Me.Controls.SetChildIndex(wmp, 0)
    wmp.Dock = System.Windows.Forms.DockStyle.Fill
    wmp.EndInit()   ' <<< errors here !

End Sub

What am I missing?


问:
Random number generator with conditions - Python
I am new to Python and trying to generate 5 numbers with 2 conditions:

There must be 3 even and 2 odd numbers

From those 5 numbers 3 must be low (1,51) and 2 high (51,100). Which number will be low or high is not of interest.

I have managed to solve the first part:

```<code>import random
rand_even = random.sample(range(0, 100, 2), 3)
rand_odd = random.sample(range(1, 100, 2), 2)
rand_total = rand_even,rand_odd
print(rand_total)
</code>```

Obviously this is not getting me anywhere
For the second part i thought i could use something like:

```<code>rand_low = random.sample(range(0, 51), 3)
rand_high = random.sample(range(51,100), 2)
</code>```

But obviously this is not the way as i am getting more than 5 numbers.

Any help would be appriciated.
Thank you

答:
If you don't care which numbers are high/low or even/odd, you can just say that the high numbers are even (since you need 3 low, and 3 even numbers).

This code just gives 3 low even numbers, and 2 high odd numbers:

```<code>import random
rand_even_low = random.sample(range(0, 52, 2), 3)
rand_odd_high = random.sample(range(51, 1000, 2), 2)
rand_total = rand_even_low + rand_odd_high
print(rand_total)
</code>```

Body:
I am new to Python and trying to generate 5 numbers with 2 conditions:

There must be 3 even and 2 odd numbers

From those 5 numbers 3 must be low (1,51) and 2 high (51,100). Which number will be low or high is not of interest.

I have managed to solve the first part:

import random
rand_even = random.sample(range(0, 100, 2), 3)
rand_odd = random.sample(range(1, 100, 2), 2)
rand_total = rand_even,rand_odd
print(rand_total)

Obviously this is not getting me anywhere
For the second part i thought i could use something like:

rand_low = random.sample(range(0, 51), 3)
rand_high = random.sample(range(51,100), 2)

But obviously this is not the way as i am getting more than 5 numbers.

Any help would be appriciated.
Thank you

Body:
If you don't care which numbers are high/low or even/odd, you can just say that the high numbers are even (since you need 3 low, and 3 even numbers).

This code just gives 3 low even numbers, and 2 high odd numbers:

import random
rand_even_low = random.sample(range(0, 52, 2), 3)
rand_odd_high = random.sample(range(51, 1000, 2), 2)
rand_total = rand_even_low + rand_odd_high
print(rand_total)


问:
How do I use multiple classes in css module based on a const?
Currently my extraClassName const is never read and I would like the css module to follow what extraClassName is based on the if statements. Not sure how to go about doing this.   </p>

```<code>render() {
    const { isFinish, isStart } = this.props;
    const extraClassName = isFinish
      ? "node-finish"
      : isStart
      ? "node-start"
      : "";

    return <div className={`node ${styles.extraClassName}`}></div>;
  }```
</code>```

答:
I found a solution for my question after poking around. The last case should be added in as styles.node as state does not matter while the const of extraClassName (which should now be renamed) should hold the css modules of the classes I want to edit. Thanks for all the replies and help I've gotten!</p>

```<code>  render() {
    const { isFinish, isStart } = this.props;
    const extraClassName = isFinish
      ? styles.nodeFinish
      : isStart
      ? styles.nodeStart
      : "";

    return <div className={`${extraClassName} ${styles.node}`}></div>;
  }
</code>```

Body:
Currently my extraClassName const is never read and I would like the css module to follow what extraClassName is based on the if statements. Not sure how to go about doing this.

render() {
    const { isFinish, isStart } = this.props;
    const extraClassName = isFinish
      ? "node-finish"
      : isStart
      ? "node-start"
      : "";

    return <div className={`node ${styles.extraClassName}`}>
;
  }```

Body:
I found a solution for my question after poking around. The last case should be added in as styles.node as state does not matter while the const of extraClassName (which should now be renamed) should hold the css modules of the classes I want to edit. Thanks for all the replies and help I've gotten!

  render() {
    const { isFinish, isStart } = this.props;
    const extraClassName = isFinish
      ? styles.nodeFinish
      : isStart
      ? styles.nodeStart
      : "";

    return <div className={`${extraClassName} ${styles.node}`}></div>;
  }


问:
Rotating a div element
Is it possible to rotate a div element using Javascript & NOT using HTML 5?

If so what attributes of the element do I set/change to make it rotate? Ie, div.what?

PS: When I say rotate I mean rotate an imagae around an axis, not every x milliseconds show a different image rotation.

答:
If you are looking for a way to do it instantaneously, than you can use

element.style.transform = "rotateZ(90deg");

Make sure to use quotes around the CSS statement.

If you want it over the duration of, say, a second (I know you don't want this, I am just doing it anyways), you can put

element.style.transition = "1s";
element.style.transform = "rotateZ(90deg)";

ContentLicense: CC BY-SA 2.5

Title: Rotating a div element


问:
Label help for histograms
I have a set of histograms and would like to put labels on the +- 1 stdev and the mean.  I have the lines, but want the labels as well.  I would like the labels toward the bottom of the histograms with white background so the font is legible against the histogram colors.

```<code>library(dply)
library(ggplot2)

a = runif(1000,1,100)
b = runif(1000,1,100)
c = runif(1000,1,100)

amount = c(a,b,c)

cat = c(rep("a",1000), rep("b",1000), rep("c",1000))

hist.data = data.frame(amount,cat)
names(hist.data) = c("amount","cat")

hist.data$cat = factor(hist.data$cat, levels = c("a","b","c"))
pricedata = ddply(hist.data, c("cat"), summarize, avg = mean(amount), minus.stdev = mean(amount)-sd(amount),
  plus.stdev = mean(amount) + sd(amount))
pricedata = pricedata[order(pricedata$avg),]

ggplot(hist.data, aes(x=amount, fill = cat))+
  geom_histogram(color="white", alpha = .8, position = 'identity', binwidth = 5)+
  theme_test()+
  geom_vline(aes(xintercept = avg), data = pricedata, color = "black", size = 1)+

  geom_vline(aes(xintercept = minus.stdev), data = pricedata, color = "black", size = .75, linetype = "dotted")+

  geom_vline(aes(xintercept = plus.stdev), data = pricedata, color = "black", size = .75, linetype = "dotted")+

  facet_grid(cat ~., scales = "free")+
  scale_y_continuous(expand = c(0,0),name = "Count")+
  scale_x_continuous(labels = scales::dollar, name="\nAmount", limits = c(0,100))
</code>```

答:
I'd recommend converting your pricedata to long format - that somewhat simplifies your geom_vline calls (though you have to add size and linetype scales...) and makes using geom_label pretty simple. At this point, geom_label is pretty new, and doesn't allow you to do things like change the angle.

```<code>pricedata_long = tidyr::pivot_longer(pricedata, -cat)

ggplot(hist.data, aes(x=amount, fill = cat))+
  geom_histogram(color="white", alpha = .8, position = 'identity', binwidth = 5)+
  theme_test()+
  geom_vline(aes(xintercept = value, linetype = name, size = name),
             data = pricedata_long, color = "black", show.legend = FALSE) +
  geom_label(aes(x = value, label = scales::dollar_format()(value)), data = pricedata_long,
             y = 0, fill = "white", vjust = -.1,
             show.legend = FALSE) +
  scale_size_manual(values = c("avg" = 1, "minus.stdev" = 0.75, "plus.stdev" = 0.75)) +
  scale_linetype_manual(values = c("avg" = "solid", "minus.stdev" = "dotted", "plus.stdev" = "dotted")) +

  facet_grid(cat ~., scales = "free")+
  scale_y_continuous(expand = c(0,0),name = "Count")+
  scale_x_continuous(labels = scales::dollar, name="\nAmount", limits = c(0,100))
</code>```

Title: Label help for histograms

Body:
I have a set of histograms and would like to put labels on the +- 1 stdev and the mean.  I have the lines, but want the labels as well.  I would like the labels toward the bottom of the histograms with white background so the font is legible against the histogram colors.

library(dply)
library(ggplot2)

a = runif(1000,1,100)
b = runif(1000,1,100)
c = runif(1000,1,100)

amount = c(a,b,c)

cat = c(rep("a",1000), rep("b",1000), rep("c",1000))

hist.data = data.frame(amount,cat)
names(hist.data) = c("amount","cat")

hist.data$cat = factor(hist.data$cat, levels = c("a","b","c"))
pricedata = ddply(hist.data, c("cat"), summarize, avg = mean(amount), minus.stdev = mean(amount)-sd(amount),
  plus.stdev = mean(amount) + sd(amount))
pricedata = pricedata[order(pricedata$avg),]

ggplot(hist.data, aes(x=amount, fill = cat))+
  geom_histogram(color="white", alpha = .8, position = 'identity', binwidth = 5)+
  theme_test()+
  geom_vline(aes(xintercept = avg), data = pricedata, color = "black", size = 1)+

  geom_vline(aes(xintercept = minus.stdev), data = pricedata, color = "black", size = .75, linetype = "dotted")+

  geom_vline(aes(xintercept = plus.stdev), data = pricedata, color = "black", size = .75, linetype = "dotted")+

  facet_grid(cat ~., scales = "free")+
  scale_y_continuous(expand = c(0,0),name = "Count")+
  scale_x_continuous(labels = scales::dollar, name="\nAmount", limits = c(0,100))

Body:
I'd recommend converting your pricedata to long format - that somewhat simplifies your geom_vline calls (though you have to add size and linetype scales...) and makes using geom_label pretty simple. At this point, geom_label is pretty new, and doesn't allow you to do things like change the angle.

pricedata_long = tidyr::pivot_longer(pricedata, -cat)

ggplot(hist.data, aes(x=amount, fill = cat))+
  geom_histogram(color="white", alpha = .8, position = 'identity', binwidth = 5)+
  theme_test()+
  geom_vline(aes(xintercept = value, linetype = name, size = name),
             data = pricedata_long, color = "black", show.legend = FALSE) +
  geom_label(aes(x = value, label = scales::dollar_format()(value)), data = pricedata_long,
             y = 0, fill = "white", vjust = -.1,
             show.legend = FALSE) +
  scale_size_manual(values = c("avg" = 1, "minus.stdev" = 0.75, "plus.stdev" = 0.75)) +
  scale_linetype_manual(values = c("avg" = "solid", "minus.stdev" = "dotted", "plus.stdev" = "dotted")) +

  facet_grid(cat ~., scales = "free")+
  scale_y_continuous(expand = c(0,0),name = "Count")+
  scale_x_continuous(labels = scales::dollar, name="\nAmount", limits = c(0,100))


问:
Is there a way to Open an App just by its Name in Python
I'm making an "Advanced Virtual Assistant" by using Python and I want to be able to run any app on the PC with just entering its name. Something likes:

```<code>i = input("What App Do You Want To Open?:  ")
d = getDirectory(i)
os.startfile(d)
</code>```

Now I can set this up manually for some apps by getting their directory but it won't be for every app so its not what I need. Is there any easy way to do this?

答:
From Lucan's answer, I got this code:

```<code>import wmi
w = wmi.WMI()
for p in w.Win32_Product():
    if 'Box, Inc.' == p.Vendor and p.Caption and 'Box Sync' in p.Caption:
        print 'Installed {}'.format(p.Version)
</code>```

Sorry but I couldn't figure it out, Where exactly does the app name go in this?

Body:
I'm making an "Advanced Virtual Assistant" by using Python and I want to be able to run any app on the PC with just entering its name. Something likes:

i = input("What App Do You Want To Open?:  ")
d = getDirectory(i)
os.startfile(d)

Now I can set this up manually for some apps by getting their directory but it won't be for every app so its not what I need. Is there any easy way to do this?

Body:
From Lucan's answer, I got this code:

import wmi
w = wmi.WMI()
for p in w.Win32_Product():
    if 'Box, Inc.' == p.Vendor and p.Caption and 'Box Sync' in p.Caption:
        print 'Installed {}'.format(p.Version)

Sorry but I couldn't figure it out, Where exactly does the app name go in this?


问:
DiscordAPIError: Unknown role
I was trying to make a command in discord.js in which the bot finds the highest role it can give to a person and gives it to the person.

      const myrole = message.guild.me.roles.highest.rawPosition
      const therole = message.guild.roles.cache.find(r => r.rawPosition = myrole-1)
      const person = message.guild.member(client.users.cache.get("the id"))
      person.roles.add(therole.id);
```

<p>And I get the following error:</p>

<pre class="lang-js prettyprint-override"><code>    (node:18926) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Role
        at RequestHandler.execute (/rbd/pnpm-volume/d8568466-4a2a-4c3a-ac47-cee06cded9bb/node_modules/.registry.npmjs.org/discord.js/12.2.0/node_modules/discord.js/src/rest/RequestHandler.js:170:25)
        at processTicksAndRejections (internal/process/task_queues.js:88:5)
</code>```

Can anyone help me out with this?

答:
Your current code is not checking if r.rawPosition is equal to myrole - 1 it is defining r.rawPosition as myrole - 1

const myrole = message.guild.me.roles.highest.rawPosition
const therole = message.guild.roles.cache.find(r => r.rawPosition === myrole-1)
const person = message.guild.member(client.users.cache.get("the id"))
person.roles.add(therole.id);
```

Title: DiscordAPIError: Unknown role

Body:
I was trying to make a command in discord.js in which the bot finds the highest role it can give to a person and gives it to the person.

      const myrole = message.guild.me.roles.highest.rawPosition
      const therole = message.guild.roles.cache.find(r => r.rawPosition = myrole-1)
      const person = message.guild.member(client.users.cache.get("the id"))
      person.roles.add(therole.id);

And I get the following error:

    (node:18926) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Role
        at RequestHandler.execute (/rbd/pnpm-volume/d8568466-4a2a-4c3a-ac47-cee06cded9bb/node_modules/.registry.npmjs.org/discord.js/12.2.0/node_modules/discord.js/src/rest/RequestHandler.js:170:25)
        at processTicksAndRejections (internal/process/task_queues.js:88:5)

Can anyone help me out with this?


答:
When you call a method on an object, the object will be assigned to the self argument of the function, for example:

```<code>class A:
  def someFunc(self):
    pass

a = A()
a.someFunc() # self == a
</code>```

When you are calling the super function, your own class will be assigned to self, you should be calling super like this:

```<code>class A:
  def __init__(self, a):
    sef.a = a

class B(A):
  def __init__(self):
    a = # something
    super(self).__init__(a)
    print(self.a)

i = B()
</code>```

The problem with your code is that you are assigning a to self, and then not providing a value for b and c.

Title: Python: "self" in inheritance

Body:
When you call a method on an object, the object will be assigned to the self argument of the function, for example:

class A:
  def someFunc(self):
    pass

a = A()
a.someFunc() # self == a

When you are calling the super function, your own class will be assigned to self, you should be calling super like this:

class A:
  def __init__(self, a):
    sef.a = a

class B(A):
  def __init__(self):
    a = # something
    super(self).__init__(a)
    print(self.a)

i = B()

The problem with your code is that you are assigning a to self, and then not providing a value for b and c.


问:
Count the number of appearances of char given a ID
I have to perform a query where I can count the number of distinct codes per Id.

```<code>   |Id  | Code
   ------------
   | 1  |   C
   | 1  |   I
   | 2  |   I
   | 2  |   C
   | 2  |   D
   | 2  |   D
   | 3  |   C
   | 3  |   I
   | 3  |   D
   | 4  |   I
   | 4  |   C
   | 4  |   C
</code>```

The output should be something like:

```<code>   |Id  | Count | #Code C | #Code I | #Code D
   -------------------------------------------
   | 1  | 2     |    1    |    1    |   0
   | 2  | 3     |    1    |    0    |   2
   | 3  | 3     |    1    |    1    |   1
   | 4  | 2     |    2    |    1    |   0
</code>```

Can you give me some advise on this?

答:
If the codes are only to the provided ones, the following query can provide the desired result.

```<code>    select
      pvt.Id,
      codes.total As [Count],
      COALESCE(C, 0) AS [#Code C],
      COALESCE(I, 0) AS [#Code I],
      COALESCE(D, 0) AS [#Code D]
      from
      ( select Id, Code,  Count(code) cnt
        from t
        Group by Id, Code) s
      PIVOT(MAX(cnt) FOR Code IN ([C], [I], [D])) pvt
      join (select Id, count(distinct Code) total from t group by Id) codes on pvt.Id = codes.Id ;
</code>```

Note: as I can see from sample input data, code 'I' is found in all of Ids. Its count is zero for Id = 3 in the expected output (in the question).

Here is the correct output:

DB Fiddle

Body:
I have to perform a query where I can count the number of distinct codes per Id.

   |Id  | Code
   ------------
   | 1  |   C
   | 1  |   I
   | 2  |   I
   | 2  |   C
   | 2  |   D
   | 2  |   D
   | 3  |   C
   | 3  |   I
   | 3  |   D
   | 4  |   I
   | 4  |   C
   | 4  |   C

The output should be something like:

   |Id  | Count | #Code C | #Code I | #Code D
   -------------------------------------------
   | 1  | 2     |    1    |    1    |   0
   | 2  | 3     |    1    |    0    |   2
   | 3  | 3     |    1    |    1    |   1
   | 4  | 2     |    2    |    1    |   0

Can you give me some advise on this?

Body:
If the codes are only to the provided ones, the following query can provide the desired result.

    select
      pvt.Id,
      codes.total As [Count],
      COALESCE(C, 0) AS [#Code C],
      COALESCE(I, 0) AS [#Code I],
      COALESCE(D, 0) AS [#Code D]
      from
      ( select Id, Code,  Count(code) cnt
        from t
        Group by Id, Code) s
      PIVOT(MAX(cnt) FOR Code IN ([C], [I], [D])) pvt
      join (select Id, count(distinct Code) total from t group by Id) codes on pvt.Id = codes.Id ;

Note: as I can see from sample input data, code 'I' is found in all of Ids. Its count is zero for Id = 3 in the expected output (in the question).

Here is the correct output:

DB Fiddle


问:
pyspark job execution in yarn cluster
I am trying to understand how spark job work in yarn cluster

I am using below commands to submit job

spark-submit --master yarn --deploy-mode cluster sparksessionexample.py

After submitting job console shows below console log

```<code>2020-05-29 20:52:48,668 INFO yarn.Client: Uploading resource file:/tmp/spark-bcd415f0-a22e-46b2-951c-5b6e4385a0c6/__spark_libs__2908230569257238890.zip -> hdfs://localhost:9000/user/hadoop/.sparkStaging/application_1590759398715_0003/__spark_libs__2908230569257238890.zip
2020-05-29 20:53:14,164 INFO yarn.Client: Uploading resource file:/home/hadoop/pythonprojects/Python/src/spark_jobs/sparksessionexample.py -> hdfs://localhost:9000/user/hadoop/.sparkStaging/application_1590759398715_0003/sparksessionexample.py
2020-05-29 20:53:14,610 INFO yarn.Client: Uploading resource file:/home/hadoop/clouderaapp/apache-spark/python/lib/pyspark.zip -> hdfs://localhost:9000/user/hadoop/.sparkStaging/application_1590759398715_0003/pyspark.zip
2020-05-29 20:53:15,984 INFO yarn.Client: Uploading resource file:/home/hadoop/clouderaapp/apache-spark/python/lib/py4j-0.10.7-src.zip -> hdfs://localhost:9000/user/hadoop/.sparkStaging/application_1590759398715_0003/py4j-0.10.7-src.zip
2020-05-29 20:53:18,362 INFO yarn.Client: Uploading resource file:/tmp/spark-bcd415f0-a22e-46b2-951c-5b6e4385a0c6/__spark_conf__7123551182035223076.zip -> hdfs://localhost:9000/user/hadoop/.sparkStaging/application_1590759398715_0003/__spark_conf__.zip
</code>```

I just to understand how yarn execute sparksessionexample.py file, i mean whether it create python virtual env on node? as above log shows only uploading lib, confs but what about python client to execute sparksessionexample.py?

Can anyone help understand this?

答:
The "Spark client" is used to bootstrap the Spark job execution.

In your case it is the only thing that runs on your local machine, because you requested cluster execution mode:

the "client" contacts the cluster manager (here YARN Resource Manager, could be Kubernetes Master, etc.) to start the Spark driver inside an AppMaster container

then the driver contacts again the cluster manager to request some containers for the executors

then the driver runs your Python code and distributes the work to the executors

finally the driver de-allocates its executors and itself

at this point the "client" notices that the YARN job has reached success or failure status, and can terminate

In short, the "client" never gets any kind of useful information from the driver running inside the cluster. You must inspect the YARN logs for the container running the driver (it's the AppMaster, typically number 00001).

If you want to see some feedback from the driver, then run your job in client execution mode -- it means the driver will run in the same JVM as the "client", in your local machine, and spit its logs in your console.

Title: pyspark job execution in yarn cluster

Body:
I am trying to understand how spark job work in yarn cluster

I am using below commands to submit job

spark-submit --master yarn --deploy-mode cluster sparksessionexample.py

After submitting job console shows below console log

2020-05-29 20:52:48,668 INFO yarn.Client: Uploading resource file:/tmp/spark-bcd415f0-a22e-46b2-951c-5b6e4385a0c6/__spark_libs__2908230569257238890.zip -> hdfs://localhost:9000/user/hadoop/.sparkStaging/application_1590759398715_0003/__spark_libs__2908230569257238890.zip
2020-05-29 20:53:14,164 INFO yarn.Client: Uploading resource file:/home/hadoop/pythonprojects/Python/src/spark_jobs/sparksessionexample.py -> hdfs://localhost:9000/user/hadoop/.sparkStaging/application_1590759398715_0003/sparksessionexample.py
2020-05-29 20:53:14,610 INFO yarn.Client: Uploading resource file:/home/hadoop/clouderaapp/apache-spark/python/lib/pyspark.zip -> hdfs://localhost:9000/user/hadoop/.sparkStaging/application_1590759398715_0003/pyspark.zip
2020-05-29 20:53:15,984 INFO yarn.Client: Uploading resource file:/home/hadoop/clouderaapp/apache-spark/python/lib/py4j-0.10.7-src.zip -> hdfs://localhost:9000/user/hadoop/.sparkStaging/application_1590759398715_0003/py4j-0.10.7-src.zip
2020-05-29 20:53:18,362 INFO yarn.Client: Uploading resource file:/tmp/spark-bcd415f0-a22e-46b2-951c-5b6e4385a0c6/__spark_conf__7123551182035223076.zip -> hdfs://localhost:9000/user/hadoop/.sparkStaging/application_1590759398715_0003/__spark_conf__.zip

I just to understand how yarn execute sparksessionexample.py file, i mean whether it create python virtual env on node? as above log shows only uploading lib, confs but what about python client to execute sparksessionexample.py?

Can anyone help understand this?


问:
Android Multiple Choice List SQLite
How can i save the info from a multiple choice listview into the database? I want to save the status of a item from a list. For instance, if i have 2 items checked i want to save this status in the database.

Thanks

答:
Sure fegol,

I assume you already set up the multiple choice listview. (if not, please check online there are heaps of them http://www.androidpeople.com/android-listview-multiple-choice-example).

Here I'd like to give you some hint on data-saving problem.

Basically, there are two common choices. The first is to use getCheckedItemIds() or getCheckedItemPositions() on your listview (http://developer.android.com/reference/android/widget/AbsListView.html#getCheckedItemIds()).

The second one which is more flexible is to write a custom adapter. You can use isChecked() to check whether the checkbox was checked, and then save the status into your hashmap. Then you can get all status of checkboxes at the last.

I put some pseudo-code for the second approach for you. Hope this helps.

```<code>    ArrayList<Boolean> checkList = new ArrayList<Boolean>();
    // TODO: put some empty data into checkList

    private OnItemClickListener myListItemClickListener = new ListView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {

        if(checkList.get(position)){
            checkList.set(position, false);
        }else{
            checkList.set(position, true);
        }

        ((mAdapter)mList.getAdapter()).notifyDataSetChanged();

        }
    }

    class mAdapter extends BaseAdapter{

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (checkList.get(position)){
                checkBox.setChecked(true);
            }else{
                checkBox.setChecked(false);
            }
        }
    }
</code>```

Title: Android Multiple Choice List SQLite

Body:
Sure fegol,

I assume you already set up the multiple choice listview. (if not, please check online there are heaps of them http://www.androidpeople.com/android-listview-multiple-choice-example).

Here I'd like to give you some hint on data-saving problem.

Basically, there are two common choices. The first is to use getCheckedItemIds() or getCheckedItemPositions() on your listview (http://developer.android.com/reference/android/widget/AbsListView.html#getCheckedItemIds()).

The second one which is more flexible is to write a custom adapter. You can use isChecked() to check whether the checkbox was checked, and then save the status into your hashmap. Then you can get all status of checkboxes at the last.

I put some pseudo-code for the second approach for you. Hope this helps.

    ArrayList<Boolean> checkList = new ArrayList<Boolean>();
    // TODO: put some empty data into checkList

    private OnItemClickListener myListItemClickListener = new ListView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {

        if(checkList.get(position)){
            checkList.set(position, false);
        }else{
            checkList.set(position, true);
        }

        ((mAdapter)mList.getAdapter()).notifyDataSetChanged();

        }
    }

    class mAdapter extends BaseAdapter{

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (checkList.get(position)){
                checkBox.setChecked(true);
            }else{
                checkBox.setChecked(false);
            }
        }
    }


问:
Problem accessing dockerized node application from outside of container
i have been trying to dockerize an angular project, using Docker Desktop for windows, with linux containers, and Hyper-V.

Here is my dockerfile:

```<code>FROM node:alpine

WORKDIR /var/app

EXPOSE 4200

COPY package*.json ./
COPY proxy*.json ./

COPY . .
RUN npm install @angular/cli -g
#Custom dependencies
RUN npm config set registry http://maven.corp.com.br:8081/artifactory/api/npm/
RUN npm install

RUN npm run build:dev

ENTRYPOINT npm start
</code>```

i build it and can run it just fine with:

```<code>docker build -t name .

docker run -p 4200:4200 name
</code>```

The problem is, when i try to access https://localhost:4200 from my windows pc, i get ERR_CONNECTION_CLOSED.

However, if i go into the container cli, and use Links (the command line web browser https://i.imgur.com/jwhD9cm.gif) to access the url, it works just fine, i'm just having issues trying to access it from my windows pc.

I tried using the host.docker.domain dns aswell but no success.

Any help will be greatly appreciated.

Thanks!

答:
change ENTRYPOINT npm start to

ENTRYPOINT npm start -- --host 0.0.0.0 --disable-host-check

or update package.json

"start": "ng serve --host 0.0.0.0 --disable-host-check",

Body:
i have been trying to dockerize an angular project, using Docker Desktop for windows, with linux containers, and Hyper-V.

Here is my dockerfile:

FROM node:alpine

WORKDIR /var/app

EXPOSE 4200

COPY package*.json ./
COPY proxy*.json ./

COPY . .
RUN npm install @angular/cli -g
#Custom dependencies
RUN npm config set registry http://maven.corp.com.br:8081/artifactory/api/npm/
RUN npm install

RUN npm run build:dev

ENTRYPOINT npm start

i build it and can run it just fine with:

docker build -t name .

docker run -p 4200:4200 name

The problem is, when i try to access https://localhost:4200 from my windows pc, i get ERR_CONNECTION_CLOSED.

However, if i go into the container cli, and use Links (the command line web browser https://i.imgur.com/jwhD9cm.gif) to access the url, it works just fine, i'm just having issues trying to access it from my windows pc.

I tried using the host.docker.domain dns aswell but no success.

Any help will be greatly appreciated.

Thanks!


问:
Why do we write [0] after get_or_create in model_name.object.get_or_create() in django
A function in Faker script to add data in my model Department.

department = ['I.T.','C.S.E','M.E.','E.C.']
def add_dept():
    d = Department.objects.get_or_create(dept_name=random.choice(depatment))[0]

答:
get_or_create() is a queryset method, which returns a tuple (d, created). where d is the model instance and created is boolean flag which tells us if the object is created or not.

so by getting the first index like this

```<code>Department.objects.get_or_create(dept_name=random.choice(depatment))[0]
</code>```

You are actually doing (d, created)[0] which always returns the object. A better way to do this is to use underscore (_) to ignore created flag, like this:

```<code>d, _ = Department.objects.get_or_create(dept_name=random.choice(depatment))
</code>```

reference: https://docs.djangoproject.com/en/3.0/ref/models/querysets/#get-or-create

Body:
get_or_create() is a queryset method, which returns a tuple (d, created). where d is the model instance and created is boolean flag which tells us if the object is created or not.

so by getting the first index like this

Department.objects.get_or_create(dept_name=random.choice(depatment))[0]

You are actually doing (d, created)[0] which always returns the object. A better way to do this is to use underscore (_) to ignore created flag, like this:

d, _ = Department.objects.get_or_create(dept_name=random.choice(depatment))

reference: https://docs.djangoproject.com/en/3.0/ref/models/querysets/#get-or-create


问:
Unable to create an object of type 'MyContext'. For the different patterns supported at design time
I have ConsoleApplication on .NET Core and also I added my DbContext to dependencies, but howewer I have an error:

Unable to create an object of type 'MyContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

I've added: var context = host.Services.GetRequiredService<MyContext>();
Also I've added private readonly DbContextOptions<MyContext> _opts; in my Post Class:

using (MyContext db = new MyContext(_opts))
{
    db.Posts.Add(postData);
    db.SaveChanges();
}
```
<p>This how I added service:</p>
<pre class="lang-cs prettyprint-override"><code>.ConfigureServices((context, services) =>
{
    services.Configure<DataOptions>(opts =>
        context.Configuration.GetSection(nameof(DataOptions)).Bind(opts)
    );
    services.AddDbContext<MyContext>((provider, builder) =>
        builder.UseSqlite(provider.GetRequiredService<IOptions<DataOptions>>().Value.ConnectionString)
    );
});
</code>```

And this is my Context:

public sealed class MyContext : DbContext
{
    private readonly DbContextOptions<MyContext> _options;

    public DbSet<PostData> Posts { get; set; }
    public DbSet<VoteData> Votes { get; set; }

    public MyContext(DbContextOptions<MyContext> options) : base(options)
    {
        _options = options;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlite("ConnectionString");
        }
    }
}
```

I tried add-migration and has this error

What I do wrong?

答:
I came across this problem today. In my case, the SqlDbContext was in a separate ASP.Net Core 3.1 class library project, and I was trying to setup migrations using the dotnet CLI from that project's root folder. The main web application, which is the default project, contains the connection string configuration inside the appsettings.json and the startup configurations therefore I had to specify the startup project path using the -s switch as follows.

```<code>>dotnet ef migrations add initialcreation -s ..\MyWebApp\MyWebApp.csproj
</code>```

-s, short for startup project, is a quick alternative to implementing IDesignTimeDbContextFactory when the DbContext is in a different project than the web application project.

Body:
I have ConsoleApplication on .NET Core and also I added my DbContext to dependencies, but howewer I have an error:

Unable to create an object of type 'MyContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

I've added: var context = host.Services.GetRequiredService<MyContext>();
Also I've added private readonly DbContextOptions<MyContext> _opts; in my Post Class:

using (MyContext db = new MyContext(_opts))
{
    db.Posts.Add(postData);
    db.SaveChanges();
}

This how I added service:

.ConfigureServices((context, services) =>
{
    services.Configure<DataOptions>(opts =>
        context.Configuration.GetSection(nameof(DataOptions)).Bind(opts)
    );
    services.AddDbContext<MyContext>((provider, builder) =>
        builder.UseSqlite(provider.GetRequiredService<IOptions<DataOptions>>().Value.ConnectionString)
    );
});

And this is my Context:

public sealed class MyContext : DbContext
{
    private readonly DbContextOptions<MyContext> _options;

    public DbSet<PostData> Posts { get; set; }
    public DbSet<VoteData> Votes { get; set; }

    public MyContext(DbContextOptions<MyContext> options) : base(options)
    {
        _options = options;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlite("ConnectionString");
        }
    }
}

I tried add-migration and has this error

What I do wrong?

Body:
I came across this problem today. In my case, the SqlDbContext was in a separate ASP.Net Core 3.1 class library project, and I was trying to setup migrations using the dotnet CLI from that project's root folder. The main web application, which is the default project, contains the connection string configuration inside the appsettings.json and the startup configurations therefore I had to specify the startup project path using the -s switch as follows.

>dotnet ef migrations add initialcreation -s ..\MyWebApp\MyWebApp.csproj

-s, short for startup project, is a quick alternative to implementing IDesignTimeDbContextFactory when the DbContext is in a different project than the web application project.


问:
Swapping function in Dart, not swapping the original values
this parameterized swapping function in DART is not swapping the original values when called.

```<code>`void main() {
  int var1 = 10;
  int var2 = 20;
  swap(var1, var2);
  print(var1);
  print(var2);
}

swap(var1, var2) {
  var1 = var1 + var2;
  var2 = var1 - var2;
  var1 = var1 - var2;
}`
</code>```

The output should be 20,10 but it remains 10, 20.

答: Primitives (like int, bool, and num) are passed by value. But in the case of an object, the reference of the object is passed. This is the same behavior as in Java for passing arguments. So the values won't swap in main().

Body:
this parameterized swapping function in DART is not swapping the original values when called.

`void main() {
  int var1 = 10;
  int var2 = 20;
  swap(var1, var2);
  print(var1);
  print(var2);
}

swap(var1, var2) {
  var1 = var1 + var2;
  var2 = var1 - var2;
  var1 = var1 - var2;
}`

The output should be 20,10 but it remains 10, 20.


问:
Can Laravel 5 handle 1000 concurrent users without lagging badly?
I wanted to know that if 1000 users are concurrently using a website built with laravel 5 and also querying database regularly then how does laravel 5 perform ?
I know it would be slow but will it be highly slow that it would be unbearable ?
Note that i am also going to use ajax a lot.

And lets assume i am using digital ocean cloud service with following configurations

```<code>2GB memory
2 vCPU
40GB SSD
</code>```

I don't expect completely real figures as it is impossible to do so but at least provide some details whether i should go with laravel with some considerable performance.

Please also provide some some tools through which i can check the speed of my laravel 5 application as well as how it will perform when there is actual load as well as other tools through which i can test speed and performance.

And it would be great if someone has real experience of using laravel especially Laravel 5.

And what about Lumen does that really make application faster than laravel and how much ?

答:
In short, yes. At least newer versions of Laravel are capable (Laravel 7.*).

That being said, this is really a three part conundrum.

1. Laravel (Php)

High Concurrency Architecture And Laravel Performance Tuning

Honestly, I wouldn't be able to provide half the details as this amazing article provides. He's got everything in there from the definition of concurrency all the way to pre-optimization times vs. after-optimization times.

2. Reading, Writing, & Partitioning Persisted Data (Databases)

MySQL vs. MongoDB

I'd be curious if the real concern is Php's Laravel, or more of a database read/write speed timing bottleneck. Non relational databases are an incredible technology, that benefit big data much more than traditional relational databases.

Non-relational Databases (Mongo) have a much faster read speed than MySql (Something like 60% faster if I'm remembering correctly)

Non-relational Databases (Mongo) do have a slower write speed, but this usually is not an inhibitor to the user experience

Unlike Relational Databases (MySQL), Mongo DB can truly be partitioned, spread out across multiple servers.

Mongo DB has collections of documents, collections are pretty synonymous to tables and documents are pretty synonymous to rows.

The difference being, MongoDB has a very JSON like feel to it. (Collections of documents, where each document looks like a JSON object).

The huge difference, and benefit, is that each document - AKA row - does not have have the same keys. When using mongo DB on a fortune 500 project, my mentor and lead at the time, Logan, had a phenomenal quote.

"Mongo Don't Care"

This means that you can shape the data how you're wanting to retrieve it, so not only is your read speed faster, you're usually not being slowed by having to retrieve data from multiple tables.

Here's a package, personally tested and loved, to set up MongoDB within Laravel

Jessengers ~ MongoDB In Laravel

If you are concerned about immense amounts of users and transferring data, MongoDB may be what you're looking for. With that, let's move on to the 3rd, and most important point.

3. Serverless Architecture (Aka Horizontal scaling)

Aws, Google Cloud, Microsoft Azure, etc... I'm sure you've hear of The Cloud.

This, ultimately, is what you're looking for if you're having concurrency issues and want to stay within the realm of Laravel.

It's a whole new world of incredible tools one can hammer away at -- they'er awesome. It's also a whole new, quite large, world of tools and thought to learn.

First, let's dive into a few serverless concepts.

Infrastructure as Code Terraform

"Use Infrastructure as Code to provision and manage any cloud, infrastructure, or service"

Horizontal Scaling Example via The Cloud

"Create a Laravel application. It's a single application, monolithic. Then you dive Cloud. You discover Terraform. Ahaha, first you use terraform to define how many instances of your app will run at once. You decide you want 8 instances of your application. Next, you of course define a Load Balancer. The Load Balancer simply balances the traffic load between your 8 application instances. Each application is connected to the same database, ultimately sharing the same data source. You're simply spreading out the traffic across multiples instances of the same application."

We can of course top that, very simplified answer of cloud, and dive into lambdas, the what Not to do's of serverless, setting up your internal virtual cloud network...

Or...we can thank the Laravel team in advance for simplifying Serverless Architecture

Yep, Laravel Simplified Serverless (Shout out Laravel team)

Serverless Via Laravel Vapor

Laravel Vapor Opening Paragraph

"Laravel Vapor is an auto-scaling, serverless deployment platform for Laravel, powered by AWS Lambda. Manage your Laravel infrastructure on Vapor and fall in love with the scalability and simplicity of serverless."

Coming to a close, let's summarize.

Oringal Concern

Ability to handle a certain amount of traffic in a set amount of time

Potential Bottlenecks with potential solutions

Laravel & Php

(High Concurrency Architecture And Laravel Performance
Tuning

Database & Persisting/Retrieving Data Efficiently

Jessengers ~ MongoDB In Laravel

Serverless Architecture For Horizontal Scaling

Serverless Via Laravel Vapor

Body:
I wanted to know that if 1000 users are concurrently using a website built with laravel 5 and also querying database regularly then how does laravel 5 perform ?
I know it would be slow but will it be highly slow that it would be unbearable ?
Note that i am also going to use ajax a lot.

And lets assume i am using digital ocean cloud service with following configurations

2GB memory
2 vCPU
40GB SSD

I don't expect completely real figures as it is impossible to do so but at least provide some details whether i should go with laravel with some considerable performance.

Please also provide some some tools through which i can check the speed of my laravel 5 application as well as how it will perform when there is actual load as well as other tools through which i can test speed and performance.

And it would be great if someone has real experience of using laravel especially Laravel 5.

And what about Lumen does that really make application faster than laravel and how much ?


问:
Python: Converting multiple binary columns to single categorical column
I have a csv file dataset that contains 170 columns, the first 5 columns contain unique identifiers (Platform, ID, date, length of call, name). The remaining columns 175 contain binary data covering 10 categories. I want to condense those columns so that the number of columns in my data frame is 15. Including an example below:

```<code>import pandas as pd

df1 = pd.DataFrame({'Platform': ['Telephone', 'Chat', 'Text'], 'ID': [1, 2,
3], 'Length': [1545,1532,1511], 'Name': ['andy', 'helen', 'peter'], 'Problem:
A':[0,1,0], 'Problem: B':[1,0,0], 'Problem: C': [0,0,1], 'Solution: A':
[0,1,0], 'Solution: B':[1,0,0], 'Solution: C': [0,0,1]})
</code>```

The output is:

```<code>df.head()

ID  Date        Length\\
1   2015-10-16    1545
2   2015-10-09    1532
3   2015-10-13    1511

Name Problem: A Problem: B  Problem: C  Solution: A Solution: B Solution: C
andy         0          1           0            0           1           0
helen        1          0           0            1           0           0
peter        0          0           1            0           0           1
</code>```

What I want the data frame to look like:

```<code>  Platform ID Length  Name   Problem  Solution
  Telephone 1 1545    andy    B        B
  Chat      2 1532    helen   A        A
  Text      3 1511    peter   C        C
</code>```

FYI this is not the full dataframe. There are a total of 170 colums that I would like to transform into 15.

答:
I created this custom function which will serve your purpose. I got the idea from this stackoverflow article

```<code>def condenseCols(data,finalCol,*cols):
    cols = list(cols)
    x = data[cols] # Slice the cols
    x = x.idxmax(axis=1)
    # x is now a series, holding column name of the max value in the row i.e one of the column from cols
    x = x.apply(lambda s : s.split(": ")[1]) # extract only the prefix (A,B,C)

    data[finalCol] = x
    data = data.drop(cols, axis=1, inplace=True) # Drop the columns : cols
    return data
</code>```

Call this method, by passing the column names you want to condense, along with the final name of column

```<code>condenseCols(df1,'Problem','Problem: A','Problem: B','Problem: C')
condenseCols(df1,'Solution','Solution: A','Solution: B','Solution: C')
</code>```

There are other ways too, to do this, as cited in the article stackoverflow article

Body:
I have a csv file dataset that contains 170 columns, the first 5 columns contain unique identifiers (Platform, ID, date, length of call, name). The remaining columns 175 contain binary data covering 10 categories. I want to condense those columns so that the number of columns in my data frame is 15. Including an example below:

import pandas as pd

df1 = pd.DataFrame({'Platform': ['Telephone', 'Chat', 'Text'], 'ID': [1, 2,
3], 'Length': [1545,1532,1511], 'Name': ['andy', 'helen', 'peter'], 'Problem:
A':[0,1,0], 'Problem: B':[1,0,0], 'Problem: C': [0,0,1], 'Solution: A':
[0,1,0], 'Solution: B':[1,0,0], 'Solution: C': [0,0,1]})

The output is:

df.head()

ID  Date        Length\\
1   2015-10-16    1545
2   2015-10-09    1532
3   2015-10-13    1511

Name Problem: A Problem: B  Problem: C  Solution: A Solution: B Solution: C
andy         0          1           0            0           1           0
helen        1          0           0            1           0           0
peter        0          0           1            0           0           1

What I want the data frame to look like:

  Platform ID Length  Name   Problem  Solution
  Telephone 1 1545    andy    B        B
  Chat      2 1532    helen   A        A
  Text      3 1511    peter   C        C

FYI this is not the full dataframe. There are a total of 170 colums that I would like to transform into 15.

Body:
I created this custom function which will serve your purpose. I got the idea from this stackoverflow article

def condenseCols(data,finalCol,*cols):
    cols = list(cols)
    x = data[cols] # Slice the cols
    x = x.idxmax(axis=1)
    # x is now a series, holding column name of the max value in the row i.e one of the column from cols
    x = x.apply(lambda s : s.split(": ")[1]) # extract only the prefix (A,B,C)

    data[finalCol] = x
    data = data.drop(cols, axis=1, inplace=True) # Drop the columns : cols
    return data

Call this method, by passing the column names you want to condense, along with the final name of column

condenseCols(df1,'Problem','Problem: A','Problem: B','Problem: C')
condenseCols(df1,'Solution','Solution: A','Solution: B','Solution: C')

There are other ways too, to do this, as cited in the article stackoverflow article