问:
How to match two column values in df1 and extract corresponding values in R
Table 1:

Pos
Samples

129
ERR5678

460
ERR7890

568
ERR7689

Table 2:

Pos
ERR5678
ERR7890
ERR7689

129
67890
76879
67894

460
56782
123478
678390

568
78926
890765
345678

Result Table

Pos
Samples
Dp_value

129
ERR5678
67890

460
ERR7890
123478

568
ERR7689
345678

table 1 contains the list of Positions and their corresponding samples and another table contains the Position and Depth values for each sample. Using R, two tables read into data.table then I used: df1[(df1$Pos%in%df2%pos),]

It extracted the position. Please someone kindly tell me how to match both Pos and Samples in df2 to get the result table.

答:
Reshape the second data to 'long' format and do an inner_join

```<code>library(dplyr)
library(tidyr)
df2 %>%
    pivot_longer(cols = starts_with("ERR"),
       names_to = "Samples", values_to = "Dp_value") %>%
   inner_join(df1)
</code>```

-output

```<code># A tibble: 3 × 3
    Pos Samples Dp_value
  <int> <chr>      <int>
1   129 ERR5678    67890
2   460 ERR7890   123478
3   568 ERR7689   345678
</code>```

data

```<code>df1 <- structure(list(Pos = c(129L, 460L, 568L), Samples = c("ERR5678",
"ERR7890", "ERR7689")), class = "data.frame", row.names = c(NA,
-3L))

df2 <- structure(list(Pos = c(129L, 460L, 568L), ERR5678 = c(67890L,
56782L, 78926L), ERR7890 = c(76879L, 123478L, 890765L), ERR7689 = c(67894L,
678390L, 345678L)), class = "data.frame", row.names = c(NA, -3L
))
</code>```

Body:
Reshape the second data to 'long' format and do an inner_join

library(dplyr)
library(tidyr)
df2 %>%
    pivot_longer(cols = starts_with("ERR"),
       names_to = "Samples", values_to = "Dp_value") %>%
   inner_join(df1)

-output

# A tibble: 3 × 3
    Pos Samples Dp_value
  <int> <chr>      <int>
1   129 ERR5678    67890
2   460 ERR7890   123478
3   568 ERR7689   345678

data

df1 <- structure(list(Pos = c(129L, 460L, 568L), Samples = c("ERR5678",
"ERR7890", "ERR7689")), class = "data.frame", row.names = c(NA,
-3L))

df2 <- structure(list(Pos = c(129L, 460L, 568L), ERR5678 = c(67890L,
56782L, 78926L), ERR7890 = c(76879L, 123478L, 890765L), ERR7689 = c(67894L,
678390L, 345678L)), class = "data.frame", row.names = c(NA, -3L
))


来源: stackexchange

问:
Regularly pull files from On-Prem server to S3 using AWS Transfer family
I'm trying to prepare a flow where we can regularly pull the available new files in third parties' on-prem server to our S3 using AWS Transfer family.
I read this documentation https://aws.amazon.com/blogs/storage/how-discover-financial-secures-file-transfers-with-aws-transfer-family/, but it was not clear on setting up and configuring the process.
Can someone share any clear documentation or reference links on using AWS Transfer Family to pull files from external on-prem server to our S3?</p>

答:
With the AWS Transfer Family service you can create servers that uses SFTP, FTPS, and FTP protocols for your file transfers, and use the Amazon S3 and EFS as domains to store and access your files.

To connect your on-premise servers with the Transfer Family server you will need to use a service like File Gateway/Storage Gateway and connect via HTTPS to S3 to sync your files.

Your architecture will be something like this:

If you want more details of how to connect with your on-premises servers with the AWS S3/Transfer Family services take a look on this blog post: Centralize data access using AWS Transfer Family and AWS Storage Gateway

ContentLicense: CC BY-SA 4.0


问:
How Do I Render Form Attributes Manually in Django?
I am trying to render the name attribute manually.

{% for language in form.languages %}

  <input class="form-check-input" id="{{ language.id_for_label }}" name="{{ language.field.name }}" type="checkbox">
  {{ language.choice_label }}

{% endfor %}
```
<p>Everything gets rendered nicely except the name attribute of the input tag.</p>
<p>form.languages is a ManyToManyField shown on my form as a ModelMultipleChoiceField using the following code in my forms.py.</p>
<pre class="lang-py prettyprint-override"><code>languages = forms.ModelMultipleChoiceField(
  queryset=Language.objects.all(),
  widget=forms.CheckboxSelectMultiple
)
</code>```

EDIT: Found the culprit, apparently I need a value attribute, not a name attribute, now I just need to find a way to get the value into the template.

答: I fixed the issue. What I did was use {{ language.data.value }}.

Body:
I am trying to render the name attribute manually.

{% for language in form.languages %}

  <input class="form-check-input" id="{{ language.id_for_label }}" name="{{ language.field.name }}" type="checkbox">
  {{ language.choice_label }}

{% endfor %}

Everything gets rendered nicely except the name attribute of the input tag.

form.languages is a ManyToManyField shown on my form as a ModelMultipleChoiceField using the following code in my forms.py.

languages = forms.ModelMultipleChoiceField(
  queryset=Language.objects.all(),
  widget=forms.CheckboxSelectMultiple
)

EDIT: Found the culprit, apparently I need a value attribute, not a name attribute, now I just need to find a way to get the value into the template.


问:
Reversing a hash, getting its keys, and sorting
I'm still learning Perl, so there's probably a more efficient way of doing this. I'm trying to take a hash, reverse it so $values => $keys, grab the new key (the old value) and then sort those keys.

Here's the code in question:

```<code>foreach my $key (sort keys reverse %hash){

...}
</code>```

What I'm expecting to happen is that reverse %hash will return a hash type, which is what keys is looking for. However, I get the following error:

Type of arg 1 to keys must be hash (not reverse)

I've tried putting parentheses around reverse %hash, but still get the same thing.

Any ideas why this wouldn't work?

答:
Pre 5.14, keys returns the keys of hash. That requires a hash. You didn't provide one. reverse doesn't return a hash. In fact, it's impossible to return a hash as only scalars can be returned. (Internally, Perl can put hashes directly on the stack, but that will never be visible to the user without causing a "Bizarre" error message.) This error is detected at compile-time.

5.14 is more flexible. It will also accept a reference to a hash. (It will also accept arrays and references to arrays, but that's not relevant here.) References are scalars, so they can be returned by functions. Your code will actually make it to run-time, but whatever your reverse returns in scalar context won't a reference to a hash that doesn't exist, so your code will die at that point.

Do you have a reason to want to reverse the hash?

```<code>foreach my $key (sort { $hash{$a} cmp $hash{$b} } keys %hash) {
   my $val = $hash{$key};
   ...
}
</code>```

If you do,

```<code>foreach my $val (sort keys %{ { reverse %hash } }) {
   # No access to original key
   ...
}
</code>```

or

```<code>my %flipped = reverse %hash;
foreach my $val (sort keys %flipped) {
   my $key = $flipped{$val};
   ...
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm still learning Perl, so there's probably a more efficient way of doing this. I'm trying to take a hash, reverse it so $values => $keys, grab the new key (the old value) and then sort those keys.

Here's the code in question:

foreach my $key (sort keys reverse %hash){

...}

What I'm expecting to happen is that reverse %hash will return a hash type, which is what keys is looking for. However, I get the following error:

Type of arg 1 to keys must be hash (not reverse)

I've tried putting parentheses around reverse %hash, but still get the same thing.

Any ideas why this wouldn't work?

Body:
Pre 5.14, keys returns the keys of hash. That requires a hash. You didn't provide one. reverse doesn't return a hash. In fact, it's impossible to return a hash as only scalars can be returned. (Internally, Perl can put hashes directly on the stack, but that will never be visible to the user without causing a "Bizarre" error message.) This error is detected at compile-time.

5.14 is more flexible. It will also accept a reference to a hash. (It will also accept arrays and references to arrays, but that's not relevant here.) References are scalars, so they can be returned by functions. Your code will actually make it to run-time, but whatever your reverse returns in scalar context won't a reference to a hash that doesn't exist, so your code will die at that point.

Do you have a reason to want to reverse the hash?

foreach my $key (sort { $hash{$a} cmp $hash{$b} } keys %hash) {
   my $val = $hash{$key};
   ...
}

If you do,

foreach my $val (sort keys %{ { reverse %hash } }) {
   # No access to original key
   ...
}

or

my %flipped = reverse %hash;
foreach my $val (sort keys %flipped) {
   my $key = $flipped{$val};
   ...
}


问:
C# and Microsoft Teams PowerShell Module 3.1.0
I have a C# program that uses the Microsoft Teams PowerShell Module to read policies etc.
It did work well with Module Version 2.6.1
After updating to 3.1.0, login via MFA doesn't work anymore (non-MFA still works).

PowerShell Error:
Exception = {"Broker response returned error: WAM Error Wam plugin Microsoft.Identity.Client.Platforms.Features.WamBroker.AadPlugin Error code: 3399548929 Error Message: Need user interaction to continue."}

In WIndows Event Viewer:
Error: 0xCAA2000C The request requires user interaction.
Code: interaction_required
Description: AADSTS50078: Presented multi-factor authentication has expired due to policies configured by your administrator, you must refresh your multi-factor authentication to access 'c5fde071-9440-4083-9e3c-b6712ad6e4d5'.
Trace ID: 195be915-61f3-4dcc-a53a-70f455ce7200
Correlation ID: 49f54e0f-c928-46c2-b000-8bf1511383a7
Timestamp: 2022-01-27 17:06:55Z
TokenEndpoint: https://login.microsoftonline.com/common/oauth2/token
Logged at OAuthTokenRequestBase.cpp, line: 449, method: OAuthTokenRequestBase::ProcessOAuthResponse.

Request: authority: https://login.microsoftonline.com/common, client: ecd6b820-32c2-49b6-98a6-444530e5a77a, redirect URI: ms-appx-web://Microsoft.AAD.BrokerPlugin/ecd6b820-32c2-49b6-98a6-444530e5a77a, resource: c5fde071-9440-4083-9e3c-b6712ad6e4d5, correlation ID (request): 49f54e0f-c928-46c2-b000-8bf1511383a7

Any ideas?

Thanks in advance, Joerg

c# code:
'''C#

```<code>powershell.AddScript("Connect-MicrosoftTeams -AccountId " + App.userName);
Collection<System.Management.Automation.PSObject> result = new Collection<PSObject>();
try
{
result = powershell.Invoke();
}
catch (Exception ex)
{...}
</code>```

'''

The Execption is not thrown, only

答:
Problem solved!
Just omit the -AccountId Parameter from the "Connect-MicrosoftTeams" and it works.
That's a different behavior than AzureAD Modul, where you can prepopulate the interactive Logon Window with a username.</p>

Body:
I have a C# program that uses the Microsoft Teams PowerShell Module to read policies etc.
It did work well with Module Version 2.6.1
After updating to 3.1.0, login via MFA doesn't work anymore (non-MFA still works).

PowerShell Error:
Exception = {"Broker response returned error: WAM Error Wam plugin Microsoft.Identity.Client.Platforms.Features.WamBroker.AadPlugin Error code: 3399548929 Error Message: Need user interaction to continue."}

In WIndows Event Viewer:
Error: 0xCAA2000C The request requires user interaction.
Code: interaction_required
Description: AADSTS50078: Presented multi-factor authentication has expired due to policies configured by your administrator, you must refresh your multi-factor authentication to access 'c5fde071-9440-4083-9e3c-b6712ad6e4d5'.
Trace ID: 195be915-61f3-4dcc-a53a-70f455ce7200
Correlation ID: 49f54e0f-c928-46c2-b000-8bf1511383a7
Timestamp: 2022-01-27 17:06:55Z
TokenEndpoint: https://login.microsoftonline.com/common/oauth2/token
Logged at OAuthTokenRequestBase.cpp, line: 449, method: OAuthTokenRequestBase::ProcessOAuthResponse.

Request: authority: https://login.microsoftonline.com/common, client: ecd6b820-32c2-49b6-98a6-444530e5a77a, redirect URI: ms-appx-web://Microsoft.AAD.BrokerPlugin/ecd6b820-32c2-49b6-98a6-444530e5a77a, resource: c5fde071-9440-4083-9e3c-b6712ad6e4d5, correlation ID (request): 49f54e0f-c928-46c2-b000-8bf1511383a7

Any ideas?

Thanks in advance, Joerg

c# code:
'''C#

powershell.AddScript("Connect-MicrosoftTeams -AccountId " + App.userName);
Collection<System.Management.Automation.PSObject> result = new Collection<PSObject>();
try
{
result = powershell.Invoke();
}
catch (Exception ex)
{...}

'''

The Execption is not thrown, only


问:
Jest tests do not show timings for individual tests at random
Jest does not show the timings for each individual test. It will leave some out at random. Here is an example of a test run (in watch mode).

Now if I run this again, I get this result:

You can see how the timings for each individual test sometimes shows, sometimes it doesnt. What drives this? And how can i make it show timings for every test always?

Here is my jest config inside package.json

"jest": {
    "verbose": true,
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".*\\.spec\\.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  },
```

答:
This is determined by the reporter used by Jest (e.g default, jest-junit). Using the default reporter, you can get the timings for all tests using jest --verbose.

EDIT:

It looks like you might be using a custom reporter, and slowTestThreshold and colors might be overridden in your project. The default is 5 seconds, according to https://github.com/facebook/jest/blob/e7edb75f8357090714213f252c5aaaa9b3c29f5f/packages/jest-config/src/Defaults.ts#L64 .


问:
How can I get a Python generator to return None rather than StopIteration?
I am using generators to perform searches in lists like this simple example:

```<code>>>> a = [1,2,3,4]
>>> (i for i, v in enumerate(a) if v == 4).next()
3
</code>```

(Just to frame the example a bit, I am using very much longer lists compared to the one above, and the entries are a little bit more complicated than int. I do it this way so the entire lists won't be traversed each time I search them)

Now if I would instead change that to i == 666, it would return a StopIteration because it can't find any 666 entry in a.

How can I make it return None instead? I could of course wrap it in a try ... except clause, but is there a more pythonic way to do it?

答:
If you are using Python 2.6+ you should use the next built-in function, not the next method (which was replaced with __next__ in 3.x). The next built-in takes an optional default argument to return if the iterator is exhausted, instead of raising StopIteration:

```<code>next((i for i, v in enumerate(a) if i == 666), None)
</code>```

Body:
I am using generators to perform searches in lists like this simple example:

>>> a = [1,2,3,4]
>>> (i for i, v in enumerate(a) if v == 4).next()
3

(Just to frame the example a bit, I am using very much longer lists compared to the one above, and the entries are a little bit more complicated than int. I do it this way so the entire lists won't be traversed each time I search them)

Now if I would instead change that to i == 666, it would return a StopIteration because it can't find any 666 entry in a.

How can I make it return None instead? I could of course wrap it in a try ... except clause, but is there a more pythonic way to do it?

Body:
If you are using Python 2.6+ you should use the next built-in function, not the next method (which was replaced with __next__ in 3.x). The next built-in takes an optional default argument to return if the iterator is exhausted, instead of raising StopIteration:

next((i for i, v in enumerate(a) if i == 666), None)


问:
XOR of two strings Angular
I have to perform a XOR operation on the two strings, I got the python implementation of it:

```<code>def sxor(s1,s2):
    return ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(s1,s2))
</code>```

In the above code , we are running the for loop on the strings and we are creating the tuples of it.

```<code>string 1: abcdefghijklmn

string 2: 12345
</code>```

it will create the tuples out of it

```<code>[('a','1'),('b','2'),('c','3'),('d','4'),('e','5')]
</code>```

we have to perform the xor operation on this tuples

```<code>chr(ord('a')^ord('1'))  which will result => p
chr(ord('b')^ord('2'))  which will result => p
chr(ord('c')^ord('3'))  which will result => p
chr(ord('d')^ord('4'))  which will result => p
chr(ord('e')^ord('5'))  which will result => p
</code>```

I want output as ppppp.
I want to implement the same algorithm in angular

I have done this

```<code>export class AppComponent implements OnInit {
  name = 'Angular ' + VERSION.major;
  array1 = [1, 7, 8, 8, 7];
  array2 = ['r', 'u', 'm', 'a', 'n'];
  zip: any;
  ordValue: any;
  value: any;

  ngOnInit(): void {
    this.ordValue = this.ord('r') ^ this.ord('1');
    console.log(this.ordValue);
    this.value = String.fromCharCode(this.ordValue);
    console.log('ASCII ' + this.value);
  }

  ord(str) {
    return str.charCodeAt(0);
  }
}
</code>```

which is giving the character after XOR

stackblitz Demo : stackblitz

答:
You could use the String.fromCodePoint() and the String.charCodeAt() functions.
Something like this (I didn't test it):</p>
```<code>function sxor (s1, s2){
let str = '';
for (let i = 0; i < Math.min(s1.length, s2.length); ++i)
    str += String.fromCodePoint(s1.charCodeAt(i) ^ s2.charCodeAt(i));
return str;
}
</code>```

Title: XOR of two strings Angular

Body:
I have to perform a XOR operation on the two strings, I got the python implementation of it:

def sxor(s1,s2):
    return ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(s1,s2))

In the above code , we are running the for loop on the strings and we are creating the tuples of it.

string 1: abcdefghijklmn

string 2: 12345

it will create the tuples out of it

[('a','1'),('b','2'),('c','3'),('d','4'),('e','5')]

we have to perform the xor operation on this tuples

chr(ord('a')^ord('1'))  which will result => p
chr(ord('b')^ord('2'))  which will result => p
chr(ord('c')^ord('3'))  which will result => p
chr(ord('d')^ord('4'))  which will result => p
chr(ord('e')^ord('5'))  which will result => p

I want output as ppppp.
I want to implement the same algorithm in angular

I have done this

export class AppComponent implements OnInit {
  name = 'Angular ' + VERSION.major;
  array1 = [1, 7, 8, 8, 7];
  array2 = ['r', 'u', 'm', 'a', 'n'];
  zip: any;
  ordValue: any;
  value: any;

  ngOnInit(): void {
    this.ordValue = this.ord('r') ^ this.ord('1');
    console.log(this.ordValue);
    this.value = String.fromCharCode(this.ordValue);
    console.log('ASCII ' + this.value);
  }

  ord(str) {
    return str.charCodeAt(0);
  }
}

which is giving the character after XOR

stackblitz Demo : stackblitz

Body:
You could use the String.fromCodePoint() and the String.charCodeAt() functions.
Something like this (I didn't test it):

function sxor (s1, s2){
let str = '';
for (let i = 0; i < Math.min(s1.length, s2.length); ++i)
    str += String.fromCodePoint(s1.charCodeAt(i) ^ s2.charCodeAt(i));
return str;
}


问:
Reactive forms - Warning when using the disabled attribute
I want to disable a select box in one of my forms while there is nothing to select in it until the data for this select box was returned from the server. I need to do this because the data shown in the select box depends on what was selected in another select box. Whenever something is selected in that other select box, I need to load the corresponding options from the server. To disable the select box while there is no data available for it, I am using the disabled attribute like this:

```<code><mat-select formControlName="formId" [disabled]="formNames.length === 0">
  <mat-option
    *ngFor="let formName of formNames"
    [value]="formName.id"
  >
    {{ formName.formName }}
  </mat-option>
</mat-select>
</code>```

I then subscribed to the valueChanges event of the other select box like this:

```<code>this.createForm.controls.formTypeId.valueChanges.subscribe((value: number) => {
  this.formsService.getFormNames(value).subscribe((formNames) => {
    this.formNames = formNames;
  });
});
</code>```

While this seems to work perfectly fine, I keep getting the following warning in the browser console:

```<code>  It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true
  when you set up this control in your component class, the disabled attribute will actually be set in the DOM for
  you. We recommend using this approach to avoid 'changed after checked' errors.

  Example:
  form = new FormGroup({
    first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
    last: new FormControl('Drew', Validators.required)
  });
</code>```

I do not understand what this warning means and the suggested solution also doesn't really help me because I do not simply want to set the disabled property to true. What am I supposed to actually do to achieve the desired behavior of disabling the select box while there are no form names available? Or is my approach fine and I should just ignore this warning?

答:
Since you're using reactive forms, it means that YOU are controlling the forms, unlike template forms where Angular does it all for you.

Disabling a control as an attribute, you're asking Angular to do it for you, so Angular reminds you that you're in control.

The error message shows you how set the disable state when you create the control, but if you need to enable/disable it after, you need to use the "enable" and "disable" functions of the control.

```<code>this.createForm.controls.formTypeId.disable()
or
this.createForm.controls.formTypeId.enable()
</code>```

Body:
I want to disable a select box in one of my forms while there is nothing to select in it until the data for this select box was returned from the server. I need to do this because the data shown in the select box depends on what was selected in another select box. Whenever something is selected in that other select box, I need to load the corresponding options from the server. To disable the select box while there is no data available for it, I am using the disabled attribute like this:

<mat-select formControlName="formId" [disabled]="formNames.length === 0">
  <mat-option
    *ngFor="let formName of formNames"
    [value]="formName.id"
  >
    {{ formName.formName }}
  </mat-option>
</mat-select>

I then subscribed to the valueChanges event of the other select box like this:

this.createForm.controls.formTypeId.valueChanges.subscribe((value: number) => {
  this.formsService.getFormNames(value).subscribe((formNames) => {
    this.formNames = formNames;
  });
});

While this seems to work perfectly fine, I keep getting the following warning in the browser console:

  It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true
  when you set up this control in your component class, the disabled attribute will actually be set in the DOM for
  you. We recommend using this approach to avoid 'changed after checked' errors.

  Example:
  form = new FormGroup({
    first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
    last: new FormControl('Drew', Validators.required)
  });

I do not understand what this warning means and the suggested solution also doesn't really help me because I do not simply want to set the disabled property to true. What am I supposed to actually do to achieve the desired behavior of disabling the select box while there are no form names available? Or is my approach fine and I should just ignore this warning?

Body:
Since you're using reactive forms, it means that YOU are controlling the forms, unlike template forms where Angular does it all for you.

Disabling a control as an attribute, you're asking Angular to do it for you, so Angular reminds you that you're in control.

The error message shows you how set the disable state when you create the control, but if you need to enable/disable it after, you need to use the "enable" and "disable" functions of the control.

this.createForm.controls.formTypeId.disable()
or
this.createForm.controls.formTypeId.enable()


问:
Windows service does not recognize network path. Whats the workaround?
We have a Buffalo NAS drive as a backup drive.

And when we map this drive as B:\ , our backup application seems to understand this and run as an application.

But when run as a service, it does not recognize the mapping and crashes.

I tried giving the path as \\\192.168.x.x\Backups\ as the backup path, the service runs but then a lot of submodules fail because it sees the \\\ as a escape character.

What is the workaround so that the windows service can see the mapped drive.

I am trying to run zip.exe via a CreateProcess();

""C:\Users\jvenkatraj\Documents\SQLite\Debug\zip.exe" -9 -q -g -u "\\\192.168.123.60\Backup\store\location1\50\f2\25\43\d8\88\b9\68\49\8d\2b\d0\08\9e\7e\df\z.zip" "\\\192.168.123.60\Backup\store\temp\SPD405.tmp\file_contents""

The backslashes are messing with the quotes. And it is a WCHAR type, and I can't change it to any other type, else I will have to redefine this elsewhere as well. How many backslashes should I use?

答:
Create a symbolic link somewhere to the NAS share:

```<code>mklink /D c:\nas-backups \\192.168.x.x\Backups
</code>```

and point your backup application to c:\nas-backups\etc.

Body:
Create a symbolic link somewhere to the NAS share:

mklink /D c:\nas-backups \\192.168.x.x\Backups

and point your backup application to c:\nas-backups\etc.


问:
Whats wrong in the syntax of my SELECT VBA Statement?
What's wrong in the syntax of

"SELECT * FROM Tbl_Appointments WHERE Tbl_Appointments.[MRN] = '" & Me.MRN.Value & "' ORDERBY Tbl_Appointments.[Patient_Name];"
```

I keep getting a syntax error.

Btw I am not a professional programmer and I just create little databases for my own use in my clinic, and I didn't get this error earlier.

答: ORDERBY is incorrect, should be ORDER BY

Body:
What's wrong in the syntax of

"SELECT * FROM Tbl_Appointments WHERE Tbl_Appointments.[MRN] = '" & Me.MRN.Value & "' ORDERBY Tbl_Appointments.[Patient_Name];"

I keep getting a syntax error.

Btw I am not a professional programmer and I just create little databases for my own use in my clinic, and I didn't get this error earlier.


问:
No communication between electron app and user AddData on production
I created an electron app that has user configuration/settings (changing of theme, tracking and persisting window's current size and position). I saved the json files that contained all of these in user AppData (app.getPath('userData')) working well on development but after being packaged with electron-builder, the app no longer communicates the AppData. Tried to change the theme but the new colors could not be written in AppData, size and position not changing. Frustrated ...

Please what next should I do if I must use the AppData

```<code>const { app, BrowserWindow, ipcMain } = require("electron");
let isDev = require('electron-is-dev');
const path = require('path');
const fs = require('fs');
const { setColors } = require('./ipc');

const userDir = app.getPath('userData');

let isConfigDir = fs.existsSync(path.join(userDir, 'config'));
let isSizeDir = fs.existsSync(path.join(userDir, 'config/size.json'))
let isPosDir = fs.existsSync(path.join(userDir, 'config/pos.json'));
let isColorDir = fs.existsSync(path.join(userDir, 'config/colors.json'));

//create config dir if not already exists
if(!isConfigDir){
    fs.mkdirSync(path.join(userDir, '/config'))
}

//check and create config files if not already exist
let pos;
if(!isPosDir){
    let pos_ = {"x":636,"y":0};
    fs.writeFileSync(path.join(userDir, 'config/pos.json'), JSON.stringify(pos_));
    pos = pos_
}else{
    pos = JSON.parse(fs.readFileSync(path.join(userDir, 'config/pos.json'), "utf8"))
}

let size
if(!isSizeDir){
    let size_ = {"width":701,"height":768}
    fs.writeFileSync(path.join(userDir, 'config/size.json'), JSON.stringify(size_));
    size = size_;
}else{
    size = JSON.parse(fs.readFileSync(path.join(userDir, 'config/size.json'), "utf8"))
}

ipcMain.handle("getColors", (event, args)=>{
    let colors;
    if(!isColorDir){
        let colors_ = {"bg":"gold","text":"#000"}
        fs.writeFileSync(path.join(userDir, 'config/colors.json'), JSON.stringify(colors_));
        colors = colors_
        return colors;
    }else{
        colors = JSON.parse(fs.readFileSync(path.join(userDir, 'config/colors.json'), "utf8"));
        return colors;
    }
})

let win;
function createWin(){
    win = new BrowserWindow({
        width:size.width,
        height: size.height,
        x: pos.x,
        y: pos.y,
        title: 'BMS',
        webPreferences:{
            preload: path.join(__dirname, "preload.js")
        }
    });
    isDev ? win.loadURL('http://localhost:3000') : win.loadFile('views/build/index.html')

    win.on("closed", ()=>win = null);

    // set window size in file size.json when the system resized
    win.on('resized', ()=>{
        let size = {
            width: win.getBounds().width,
            height: win.getBounds().height,
        }
        fs.writeFileSync(path.join(userDir, 'config/size.json'), JSON.stringify(size))
    })

    // set window position in file size.json when the window moves
    win.on('move', ()=>{
        let pos = {
            x: win.getBounds().x,
            y: win.getBounds().y
        }
        fs.writeFileSync(path.join(userDir, 'config/pos.json'), JSON.stringify(pos))
    })
}

app.on("ready", ()=>{
    //create window
    createWin();

    setColors(userDir)

})

app.on("window-all-closed", ()=>{
    if(process.platform !== 'darwin'){
        app.quit()
    }
})
app.on('active', ()=>{
    if(win===null){
        createWin()
    }
})
</code>```

答:
Got it working now.

So basically.
app.getPath('userData') gives you path up into electron app dir so I have been writing into my electron app directory.

But using app.getPath('appData') get path unto electron app directory level and does not include it. hence won't be packages by electron-builder and it always be in the pc app dir.

```<code>const appDir = app.getPath('appData');
</code>```

instead of

```<code>const appDir = app.getPath('userData');
</code>```

I got this from Jay. chatted with him earlier. His youtube channel - ithinktechnologies

Thanks @Guillaume and @Dony for your time. Means a lot to me

Body:
I created an electron app that has user configuration/settings (changing of theme, tracking and persisting window's current size and position). I saved the json files that contained all of these in user AppData (app.getPath('userData')) working well on development but after being packaged with electron-builder, the app no longer communicates the AppData. Tried to change the theme but the new colors could not be written in AppData, size and position not changing. Frustrated ...

Please what next should I do if I must use the AppData

const { app, BrowserWindow, ipcMain } = require("electron");
let isDev = require('electron-is-dev');
const path = require('path');
const fs = require('fs');
const { setColors } = require('./ipc');

const userDir = app.getPath('userData');

let isConfigDir = fs.existsSync(path.join(userDir, 'config'));
let isSizeDir = fs.existsSync(path.join(userDir, 'config/size.json'))
let isPosDir = fs.existsSync(path.join(userDir, 'config/pos.json'));
let isColorDir = fs.existsSync(path.join(userDir, 'config/colors.json'));

//create config dir if not already exists
if(!isConfigDir){
    fs.mkdirSync(path.join(userDir, '/config'))
}

//check and create config files if not already exist
let pos;
if(!isPosDir){
    let pos_ = {"x":636,"y":0};
    fs.writeFileSync(path.join(userDir, 'config/pos.json'), JSON.stringify(pos_));
    pos = pos_
}else{
    pos = JSON.parse(fs.readFileSync(path.join(userDir, 'config/pos.json'), "utf8"))
}

let size
if(!isSizeDir){
    let size_ = {"width":701,"height":768}
    fs.writeFileSync(path.join(userDir, 'config/size.json'), JSON.stringify(size_));
    size = size_;
}else{
    size = JSON.parse(fs.readFileSync(path.join(userDir, 'config/size.json'), "utf8"))
}

ipcMain.handle("getColors", (event, args)=>{
    let colors;
    if(!isColorDir){
        let colors_ = {"bg":"gold","text":"#000"}
        fs.writeFileSync(path.join(userDir, 'config/colors.json'), JSON.stringify(colors_));
        colors = colors_
        return colors;
    }else{
        colors = JSON.parse(fs.readFileSync(path.join(userDir, 'config/colors.json'), "utf8"));
        return colors;
    }
})

let win;
function createWin(){
    win = new BrowserWindow({
        width:size.width,
        height: size.height,
        x: pos.x,
        y: pos.y,
        title: 'BMS',
        webPreferences:{
            preload: path.join(__dirname, "preload.js")
        }
    });
    isDev ? win.loadURL('http://localhost:3000') : win.loadFile('views/build/index.html')

    win.on("closed", ()=>win = null);

    // set window size in file size.json when the system resized
    win.on('resized', ()=>{
        let size = {
            width: win.getBounds().width,
            height: win.getBounds().height,
        }
        fs.writeFileSync(path.join(userDir, 'config/size.json'), JSON.stringify(size))
    })

    // set window position in file size.json when the window moves
    win.on('move', ()=>{
        let pos = {
            x: win.getBounds().x,
            y: win.getBounds().y
        }
        fs.writeFileSync(path.join(userDir, 'config/pos.json'), JSON.stringify(pos))
    })
}

app.on("ready", ()=>{
    //create window
    createWin();

    setColors(userDir)

})

app.on("window-all-closed", ()=>{
    if(process.platform !== 'darwin'){
        app.quit()
    }
})
app.on('active', ()=>{
    if(win===null){
        createWin()
    }
})

Body:
Got it working now.

So basically.
app.getPath('userData') gives you path up into electron app dir so I have been writing into my electron app directory.

But using app.getPath('appData') get path unto electron app directory level and does not include it. hence won't be packages by electron-builder and it always be in the pc app dir.

const appDir = app.getPath('appData');

instead of

const appDir = app.getPath('userData');

I got this from Jay. chatted with him earlier. His youtube channel - ithinktechnologies

Thanks @Guillaume and @Dony for your time. Means a lot to me


问:
Running multiple sites in one CF instance
I'm running 2 sites (Dev and QA) under one instance of CF 2018.  When I send a REST call to a CFC on Dev, the QA instance gets confused and starts delivering pages from the Dev site, probably due to Application or Session vars being changed.
I verified that the REST call is using the session vars from Application.cfm for the dev environment, as it should. But the QA instance somehow gets switched over to the Dev folder and starts running cfm modules from there. I can't find where the QA pages are getting redirected.
Thanks in advance, for any ideas on things to look at.</p>

答:
Both DEV and QA are sharing the same application name and therefore the same application and session variables. You're switching context between requests, based on which domain / environment made the previous request.

In addition, you should convert your Application.cfm to Appliction.cfc and refactor how and when you're defining application and session variables. It feels like the CFM is just setting those values on every request instead of only once, which is why the different requests are switching context.

http://www.learncfinaweek.com/course/index/section/Application_cfc/item/Application_cfc/

You need to run

each environment on their own CF instance

the application name should be dynamic

each instance should point their data sources to their own database.

Isolating the instances allow you to track separate logs based on environment.

Dynamic application names isolates the application's shared scopes from each other.

The data should be separated per environment to isolate in-development DB related changes from QA testing.

https://coldbox.ortusbooks.com/getting-started/configuration/bootstrapper-application.cfc

Your code is in source control. You checkout a copy for DEV and one for QA, each to their own "web root".

```<code>/code/DEV/repo
/code/QA/repo
</code>```

In your Application.cfc:

```<code>this.name = hash( getCurrentTemplatePath() );
</code>```

This creates a dynamic application name based on the current folder path, so DEV and QA will be different and easily isolate the shared scopes. Also helps with local DEV efforts.

It's a bit of work, but there's no way to shortcut this.

Body:
Both DEV and QA are sharing the same application name and therefore the same application and session variables. You're switching context between requests, based on which domain / environment made the previous request.

In addition, you should convert your Application.cfm to Appliction.cfc and refactor how and when you're defining application and session variables. It feels like the CFM is just setting those values on every request instead of only once, which is why the different requests are switching context.

http://www.learncfinaweek.com/course/index/section/Application_cfc/item/Application_cfc/

You need to run

each environment on their own CF instance

the application name should be dynamic

each instance should point their data sources to their own database.

Isolating the instances allow you to track separate logs based on environment.

Dynamic application names isolates the application's shared scopes from each other.

The data should be separated per environment to isolate in-development DB related changes from QA testing.

https://coldbox.ortusbooks.com/getting-started/configuration/bootstrapper-application.cfc

Your code is in source control. You checkout a copy for DEV and one for QA, each to their own "web root".

/code/DEV/repo
/code/QA/repo

In your Application.cfc:

this.name = hash( getCurrentTemplatePath() );

This creates a dynamic application name based on the current folder path, so DEV and QA will be different and easily isolate the shared scopes. Also helps with local DEV efforts.

It's a bit of work, but there's no way to shortcut this.


问:
Android: How to access a file in the SD Card
I'm trying to access the image on the SD card using below code but I"m getting File not found exception. Can someone tell me a correct way to acess the file???</p>

```<code>new File("/mnt/sdcard/splah2.jpg")
</code>```

答:
Try like this:</p>

```<code>String SD_CARD_PATH = Environment.getExternalStorageDirectory().toString();
new File(SD_CARD_PATH + "/" + "splah2.jpg");
</code>```

Body:
I'm trying to access the image on the SD card using below code but I"m getting File not found exception. Can someone tell me a correct way to acess the file???

new File("/mnt/sdcard/splah2.jpg")

Body:
Try like this:

String SD_CARD_PATH = Environment.getExternalStorageDirectory().toString();
new File(SD_CARD_PATH + "/" + "splah2.jpg");


问:
telebot delete message pytelegrambotapi
How can I delete the last N number of messages from any users. After writing the delete command, the bot must delete the latest messages by the given number. I could not find complete documentation on the pytelegrambotapi library in any way.</p>

答:
In my experience you should save the message_id of  the lasts N messagges and cycling with the delete_message function when you need to do it.

```<code>bot = telegram.Bot(token=TOKEN)

message_ids = {}

message_id = bot.send_message(chat_id, text).message_id

if chat_id in message_ids.keys():
  message_ids[chat_id].append(message_id)
else:
  message_ids[chat_id] = [message_id]
</code>```

When you need to delete the messages from some chat you can do (remember that messages after 48h aren't possible to be deleted)

```<code>for message_id in message_ids[chat_id]:
   bot.delete_message(chat_id, message_id)
</code>```

I'm sure it's perfectible, but I think it's a good basic idea

Title: telebot delete message pytelegrambotapi

Body:
In my experience you should save the message_id of  the lasts N messagges and cycling with the delete_message function when you need to do it.

bot = telegram.Bot(token=TOKEN)

message_ids = {}

message_id = bot.send_message(chat_id, text).message_id

if chat_id in message_ids.keys():
  message_ids[chat_id].append(message_id)
else:
  message_ids[chat_id] = [message_id]

When you need to delete the messages from some chat you can do (remember that messages after 48h aren't possible to be deleted)

for message_id in message_ids[chat_id]:
   bot.delete_message(chat_id, message_id)

I'm sure it's perfectible, but I think it's a good basic idea


问:
VueJS: How can I pass params into a component?
I am new to vueJS.
What I want to do is passing parameters to a component, depending on the selection of the routes. Here is my App.vue:

```<code><template>
  <div id="main">
    <header>
      <h1 style="color:red">{{msg}}</h1>
    </header>

    <div>
      <aside class="sidebar">
        <router-link v-for="el in this.$router.options.routes" :to="el">
          {{el.name}}
        </router-link>
      </aside>
      <SubMenu></SubMenu>

      <div class="content">
        <router-view></router-view>
      </div>
    </div>
  </div>
</template>

<script>
  import SubMenu from './components/SubMenu.vue'
  export default {
    components: {
      'SubMenu': SubMenu
    },
    data() {
      return {
        msg: 'Welcome to Your Vue.js App'      }
    }
  }

</script>

<style>
  @import 'style.css';
  @import 'grid.css';
</style>
</code>```

and the SubMenu component I would like to make dynamic:

```<code><template>
  <div>
    something dynamic
  </div>
</template>
</code>```

How can I pass some parameters to use in the component?
thank you

答:
Welcome to SO,

In Vue.js passing parameters to components is called "Props"

You can pass  props to your SubMenu like below

```<code><SubMenu :id="12345" someText="Some Text About Something" :dataArray="[1,2,3,4,5]" />
</code>```

then inside your SubMenu component you can define Prop Types as below

```<code>props: ['dataArray']
</code>```

or

```<code>props: {
  dataArray: {
   type: Array,
   default: []
  }
}
</code>```

After that you can use the data you passed to your liking

You can also read up on this Vue Documentation regarding the Props, which has much more detailed explanations about various Props related stuff and sample code

Body:
I am new to vueJS.
What I want to do is passing parameters to a component, depending on the selection of the routes. Here is my App.vue:

<template>

{{msg}}

        <router-link v-for="el in this.$router.options.routes" :to="el">
          {{el.name}}
        </router-link>

      <SubMenu></SubMenu>

        <router-view></router-view>

</template>

and the SubMenu component I would like to make dynamic:

<template>

    something dynamic

</template>

How can I pass some parameters to use in the component?
thank you

Body:
Welcome to SO,

In Vue.js passing parameters to components is called "Props"

You can pass  props to your SubMenu like below

<SubMenu :id="12345" someText="Some Text About Something" :dataArray="[1,2,3,4,5]" />

then inside your SubMenu component you can define Prop Types as below

props: ['dataArray']

or

props: {
  dataArray: {
   type: Array,
   default: []
  }
}

After that you can use the data you passed to your liking

You can also read up on this Vue Documentation regarding the Props, which has much more detailed explanations about various Props related stuff and sample code


问:
Number guessing game c#. Tie least guesses to best round and vice versa
I'am super new to coding and this is probably an easy fix but I just dont know how to solve it or what exactly to search for. I'm doing this assignment from school and it's a random number guessing game. In this assignment they want to know which round was the best round.

The problem I have is that I want to implement a sort of a round tracker and simultaneously tie the best/worst amount of guesses to the best/worst round the user guessed.

I hope I'am being clear with what I'm asking, I don't know the coding language too well.

This is what I've done so far and I just can't tie the "int min_tries/max_tries" to a specific round number.

```<code>else
  {
   BestRound.Add(tries);
   RoundNumber.Add(rounds);
   totaltries++;
   tries++;
   Console.WriteLine();
   Console.WriteLine(guess + " is correct. You win! It took you " + tries + " tries to guess right!");

   Console.WriteLine();

   Console.WriteLine("Do you want to play again? Yes/No?");
   playAgain = Console.ReadLine();

  if (playAgain.Equals("Yes", StringComparison.OrdinalIgnoreCase))
  {
   reset = true;
  }
  else
  {
   reset = false;
  }
  }

  if (attempt >= totalattemtp)
  {
   BestRound.Add(tries);
   RoundNumber.Add(rounds);
   Console.WriteLine("!GAME OVER!");
   Console.WriteLine("You have have no attempts left.");

   Console.WriteLine();

   Console.WriteLine("Do you want to play again? Yes/No?");
   playAgain = Console.ReadLine();

  if (playAgain.Equals("Yes", StringComparison.OrdinalIgnoreCase))
  {
   reset = true;
  }
  else
  {
   reset = false;
  }
  break;
  }

 }
}

int max_tries = BestRound.AsQueryable().Max();
int min_tries = BestRound.AsQueryable().Min();
int best_round = RoundNumber.AsQueryable().Min();
int worst_round = RoundNumber.AsQueryable().Max();

if(BestRound.AsQueryable().Max() == 10)
{
  max_tries = 10 - 1;

   Console.WriteLine("Thank you for playing! Your total tries where " + totaltries + ".");
   Console.WriteLine("Your best round was number " + best_round + " and had " + (min_tries + 1) + " tries.");
   Console.WriteLine("Your worst round was round number " + worst_round + " and had " + (max_tries + 1) + " tries.");
}
else
{
   //thanking user for playing and keeping program running until random key-input.
   Console.WriteLine("Thank you for playing! Your total tries where " + totaltries + ".");
   Console.WriteLine("Your best round was number " + best_round + " and had " + (min_tries + 1) + " tries.");
   Console.WriteLine("Your worst round was round number " + worst_round + " and had " + (max_tries + 1) + " tries.");
}

Console.WriteLine("Press enter to quit.");
Console.ReadKey();
</code>```

答:
This is what I was talking about in the comments.

Create a simple POCO ("Plain old CLR object") class named RoundInfo to hold the results of a round:

```<code>internal class RoundInfo
{
    public int RoundNumber { get; set; }
    public int NumTries { get; set; }
    public int NumberToGuess { get; set; }

    public RoundInfo(int roundNumber, int numTries, int numberToGuess)
    {
        RoundNumber = roundNumber;
        NumTries = numTries;
        NumberToGuess = numberToGuess;
    }
}
</code>```

It's just three properties and a convenience constructor.

Now to plug it into a guessing game... Here's a guessing game I threw together:

```<code>var random = new Random();
var round = 1;
var timeToQuit = false;
Console.WriteLine("Welcome to the Guessing Game");
var roundsInformation = new List<RoundInfo>();

while (!timeToQuit) {
    var numToGuess = random.Next(10) + 1;
    var guess = -1;
    var tries = 1;
    Console.WriteLine($"Round {round}:");
    while (true)
    {
        guess = GetNumberFromUser("Enter a guess between 1 and 10", 1, 10);
        if (guess == numToGuess)
        {
            Console.WriteLine($"Congratulation, you guessed correctly in {tries} tries");

            // Here is where I add the result from this round into the list of round information
            roundsInformation.Add(new RoundInfo(round, tries, numToGuess));

            Console.Write("Is it time to Quit (Y/N): ");
            var response = Console.ReadLine();
            if (response.Equals("Y", StringComparison.CurrentCultureIgnoreCase) || response.Equals("Yes", StringComparison.CurrentCultureIgnoreCase))
            {
                timeToQuit = true;
            }
            break;      //from the inner "while(true)"
        }
        ++tries;
    }
    ++round;
}
</code>```

Then, once the user has quit, I simply sort the list of round information (using LINQ's orderby) to show him/her the results:

```<code>var sortedResults = (from result in roundsInformation orderby result.NumTries select result).ToList();
Console.WriteLine("Here are your results (Best to worst):");
foreach (var result in sortedResults)
{
    Console.WriteLine($"Round {result.RoundNumber}, trying to guess: {result.NumberToGuess}, {result.NumTries} tries");
}
Console.ReadLine();
</code>```

Note that I call GetNumberFromUser to get the number from the user.  I like to do my UI checking outside the main logic of the program.  Here is that method:

```<code>static int GetNumberFromUser(string prompt, int min, int max)
{
    while (true) {
        Console.Write($"{prompt}: ");
        var read = Console.ReadLine();
        if (int.TryParse(read, out var number) && number >= min && number <= max){
            return number;
        }
        Console.WriteLine($"Entered data must be an integer between {min} and {max} inclusive");
    }
}
</code>```

If I run this program, I get something like this in the console:

```<code>Welcome to the Guessing Game
Round 1:
Enter a guess between 1 and 10: 1
Enter a guess between 1 and 10: 0
Entered data must be an integer between 1 and 10 inclusive
Enter a guess between 1 and 10: 2
Enter a guess between 1 and 10: 11
Entered data must be an integer between 1 and 10 inclusive
Enter a guess between 1 and 10: 3
Enter a guess between 1 and 10: 4
Enter a guess between 1 and 10: abc
Entered data must be an integer between 1 and 10 inclusive
Enter a guess between 1 and 10: 5
Enter a guess between 1 and 10: 6
Congratulation, you guessed correctly in 6 tries
Is it time to Quit (Y/N): n
Round 2:
Enter a guess between 1 and 10: 1
Enter a guess between 1 and 10: 2
Enter a guess between 1 and 10: 3
Enter a guess between 1 and 10: 4
Enter a guess between 1 and 10: 5
Enter a guess between 1 and 10: 6
Enter a guess between 1 and 10: 7
Enter a guess between 1 and 10: 8
Enter a guess between 1 and 10: 9
Enter a guess between 1 and 10: 10
Congratulation, you guessed correctly in 10 tries
Is it time to Quit (Y/N): n
Round 3:
Enter a guess between 1 and 10: 2
Enter a guess between 1 and 10: 3
Enter a guess between 1 and 10: 5
Congratulation, you guessed correctly in 3 tries
Is it time to Quit (Y/N): n
Round 4:
Enter a guess between 1 and 10: 1
Enter a guess between 1 and 10: 2
Enter a guess between 1 and 10: 3
Enter a guess between 1 and 10: 4
Congratulation, you guessed correctly in 4 tries
Is it time to Quit (Y/N): y
Here are your results (Best to worst):
Round 3, trying to guess: 5, 3 tries
Round 4, trying to guess: 4, 4 tries
Round 1, trying to guess: 6, 6 tries
Round 2, trying to guess: 10, 10 tries
</code>```

Body:
I'am super new to coding and this is probably an easy fix but I just dont know how to solve it or what exactly to search for. I'm doing this assignment from school and it's a random number guessing game. In this assignment they want to know which round was the best round.

The problem I have is that I want to implement a sort of a round tracker and simultaneously tie the best/worst amount of guesses to the best/worst round the user guessed.

I hope I'am being clear with what I'm asking, I don't know the coding language too well.

This is what I've done so far and I just can't tie the "int min_tries/max_tries" to a specific round number.

else
  {
   BestRound.Add(tries);
   RoundNumber.Add(rounds);
   totaltries++;
   tries++;
   Console.WriteLine();
   Console.WriteLine(guess + " is correct. You win! It took you " + tries + " tries to guess right!");

   Console.WriteLine();

   Console.WriteLine("Do you want to play again? Yes/No?");
   playAgain = Console.ReadLine();

  if (playAgain.Equals("Yes", StringComparison.OrdinalIgnoreCase))
  {
   reset = true;
  }
  else
  {
   reset = false;
  }
  }

  if (attempt >= totalattemtp)
  {
   BestRound.Add(tries);
   RoundNumber.Add(rounds);
   Console.WriteLine("!GAME OVER!");
   Console.WriteLine("You have have no attempts left.");

   Console.WriteLine();

   Console.WriteLine("Do you want to play again? Yes/No?");
   playAgain = Console.ReadLine();

  if (playAgain.Equals("Yes", StringComparison.OrdinalIgnoreCase))
  {
   reset = true;
  }
  else
  {
   reset = false;
  }
  break;
  }

 }
}

int max_tries = BestRound.AsQueryable().Max();
int min_tries = BestRound.AsQueryable().Min();
int best_round = RoundNumber.AsQueryable().Min();
int worst_round = RoundNumber.AsQueryable().Max();

if(BestRound.AsQueryable().Max() == 10)
{
  max_tries = 10 - 1;

   Console.WriteLine("Thank you for playing! Your total tries where " + totaltries + ".");
   Console.WriteLine("Your best round was number " + best_round + " and had " + (min_tries + 1) + " tries.");
   Console.WriteLine("Your worst round was round number " + worst_round + " and had " + (max_tries + 1) + " tries.");
}
else
{
   //thanking user for playing and keeping program running until random key-input.
   Console.WriteLine("Thank you for playing! Your total tries where " + totaltries + ".");
   Console.WriteLine("Your best round was number " + best_round + " and had " + (min_tries + 1) + " tries.");
   Console.WriteLine("Your worst round was round number " + worst_round + " and had " + (max_tries + 1) + " tries.");
}

Console.WriteLine("Press enter to quit.");
Console.ReadKey();

Body:
This is what I was talking about in the comments.

Create a simple POCO ("Plain old CLR object") class named RoundInfo to hold the results of a round:

internal class RoundInfo
{
    public int RoundNumber { get; set; }
    public int NumTries { get; set; }
    public int NumberToGuess { get; set; }

    public RoundInfo(int roundNumber, int numTries, int numberToGuess)
    {
        RoundNumber = roundNumber;
        NumTries = numTries;
        NumberToGuess = numberToGuess;
    }
}

It's just three properties and a convenience constructor.

Now to plug it into a guessing game... Here's a guessing game I threw together:

var random = new Random();
var round = 1;
var timeToQuit = false;
Console.WriteLine("Welcome to the Guessing Game");
var roundsInformation = new List<RoundInfo>();

while (!timeToQuit) {
    var numToGuess = random.Next(10) + 1;
    var guess = -1;
    var tries = 1;
    Console.WriteLine($"Round {round}:");
    while (true)
    {
        guess = GetNumberFromUser("Enter a guess between 1 and 10", 1, 10);
        if (guess == numToGuess)
        {
            Console.WriteLine($"Congratulation, you guessed correctly in {tries} tries");

            // Here is where I add the result from this round into the list of round information
            roundsInformation.Add(new RoundInfo(round, tries, numToGuess));

            Console.Write("Is it time to Quit (Y/N): ");
            var response = Console.ReadLine();
            if (response.Equals("Y", StringComparison.CurrentCultureIgnoreCase) || response.Equals("Yes", StringComparison.CurrentCultureIgnoreCase))
            {
                timeToQuit = true;
            }
            break;      //from the inner "while(true)"
        }
        ++tries;
    }
    ++round;
}

Then, once the user has quit, I simply sort the list of round information (using LINQ's orderby) to show him/her the results:

var sortedResults = (from result in roundsInformation orderby result.NumTries select result).ToList();
Console.WriteLine("Here are your results (Best to worst):");
foreach (var result in sortedResults)
{
    Console.WriteLine($"Round {result.RoundNumber}, trying to guess: {result.NumberToGuess}, {result.NumTries} tries");
}
Console.ReadLine();

Note that I call GetNumberFromUser to get the number from the user.  I like to do my UI checking outside the main logic of the program.  Here is that method:

static int GetNumberFromUser(string prompt, int min, int max)
{
    while (true) {
        Console.Write($"{prompt}: ");
        var read = Console.ReadLine();
        if (int.TryParse(read, out var number) && number >= min && number <= max){
            return number;
        }
        Console.WriteLine($"Entered data must be an integer between {min} and {max} inclusive");
    }
}

If I run this program, I get something like this in the console:

Welcome to the Guessing Game
Round 1:
Enter a guess between 1 and 10: 1
Enter a guess between 1 and 10: 0
Entered data must be an integer between 1 and 10 inclusive
Enter a guess between 1 and 10: 2
Enter a guess between 1 and 10: 11
Entered data must be an integer between 1 and 10 inclusive
Enter a guess between 1 and 10: 3
Enter a guess between 1 and 10: 4
Enter a guess between 1 and 10: abc
Entered data must be an integer between 1 and 10 inclusive
Enter a guess between 1 and 10: 5
Enter a guess between 1 and 10: 6
Congratulation, you guessed correctly in 6 tries
Is it time to Quit (Y/N): n
Round 2:
Enter a guess between 1 and 10: 1
Enter a guess between 1 and 10: 2
Enter a guess between 1 and 10: 3
Enter a guess between 1 and 10: 4
Enter a guess between 1 and 10: 5
Enter a guess between 1 and 10: 6
Enter a guess between 1 and 10: 7
Enter a guess between 1 and 10: 8
Enter a guess between 1 and 10: 9
Enter a guess between 1 and 10: 10
Congratulation, you guessed correctly in 10 tries
Is it time to Quit (Y/N): n
Round 3:
Enter a guess between 1 and 10: 2
Enter a guess between 1 and 10: 3
Enter a guess between 1 and 10: 5
Congratulation, you guessed correctly in 3 tries
Is it time to Quit (Y/N): n
Round 4:
Enter a guess between 1 and 10: 1
Enter a guess between 1 and 10: 2
Enter a guess between 1 and 10: 3
Enter a guess between 1 and 10: 4
Congratulation, you guessed correctly in 4 tries
Is it time to Quit (Y/N): y
Here are your results (Best to worst):
Round 3, trying to guess: 5, 3 tries
Round 4, trying to guess: 4, 4 tries
Round 1, trying to guess: 6, 6 tries
Round 2, trying to guess: 10, 10 tries


问:
Restricting options method in javalin
We have a kotlin code like the following, I am trying to disable the options method for the API's as follows using Javalin(3.12.0), but it is resulting in blocking all the other methods like get and post as well. What is that I am missing here?

```<code>val app = Javalin.create {
        it.defaultContentType = "application/json"
        it.enableWebjars()
        it.addStaticFiles("", Location.CLASSPATH)
        it.enableCorsForAllOrigins()
        it.dynamicGzip = true
    }

app.options("/*") {ctx -> ctx.status(405)}

app.routes {
        path("/auth") {
             post("/login") {
                Auth.doLogin(it)
            }
             get("/metrics") {
                val results = getData()
                it.json(results)
            }
         }
</code>```

Also there are 2 questions
1.want to implement the ratelimit for the get APi's for 20 request for an hour using the below code

```<code>   app.get("/") { ctx ->
     RateLimit(ctx).requestPerTimeUnit(5, TimeUnit.MINUTES) // throws if rate limit is exceeded
     ctx.status("Hello, rate-limited World!")
   }
</code>```

How to achieve it?

How to restrict the jetty server version to display when the API call is made?

答:
For Jetty...

There is only 1 Rate Limit concept in Jetty, and that's the org.eclipse.jetty.server.AcceptRateLimit, added as a Jetty Container LifeCycle bean to the ServerConnector, it cannot adjust rates for specific request endpoints, only for the entire connector.

If you want specific endpoint rates, then the org.eclipse.jetty.servlets.QoSFilter is the way that's done with Jetty.

The org.eclipse.jetty.server.HttpConfiguration for the org.eclipse.jetty.server.ServerConnector contains the controls to enable/disable the server announcement.

See

HttpConfiguration.setSendServerVersion(boolean)

HttpConfiguration.setSendXPoweredBy(boolean)

HttpConfiguration.setSendDateHeader(boolean)

Title: Restricting options method in javalin

Body:
We have a kotlin code like the following, I am trying to disable the options method for the API's as follows using Javalin(3.12.0), but it is resulting in blocking all the other methods like get and post as well. What is that I am missing here?

val app = Javalin.create {
        it.defaultContentType = "application/json"
        it.enableWebjars()
        it.addStaticFiles("", Location.CLASSPATH)
        it.enableCorsForAllOrigins()
        it.dynamicGzip = true
    }

app.options("/*") {ctx -> ctx.status(405)}

app.routes {
        path("/auth") {
             post("/login") {
                Auth.doLogin(it)
            }
             get("/metrics") {
                val results = getData()
                it.json(results)
            }
         }

Also there are 2 questions
1.want to implement the ratelimit for the get APi's for 20 request for an hour using the below code

   app.get("/") { ctx ->
     RateLimit(ctx).requestPerTimeUnit(5, TimeUnit.MINUTES) // throws if rate limit is exceeded
     ctx.status("Hello, rate-limited World!")
   }

How to achieve it?

How to restrict the jetty server version to display when the API call is made?


问:
Webpage Parsing
I am trying to parse a webpage and store the result in a table. However, I can't proceed any further as the parse result has some unwanted text at the top, middle and bottom of the csv. http://lottery.merseyworld.com/cgi-bin/lottery?days=20&Machine=Z&Ballset=0&order=1&show=1&year=0&display=CSV

```<code>import requests
from bs4 import BeautifulSoup
import pandas as pd

URL = "http://lottery.merseyworld.com/cgi-bin/lottery?days=20&Machine=Z&Ballset=0&order=1&show=1&year=0&display=CSV"

response = requests.get(URL)
mywebpage = response.text
mysoup = BeautifulSoup(mywebpage, "html.parser")

print(mysoup)
</code>```

gives...

```<code><html>
<head>
<title> Euro Millions Winning Numbers</title>
<body>
``` Euro Millions Winning Numbers

No., Day,DD,MMM,YYYY, N1,N2,N3,N4,N5,L1,L2,  Jackpot,   Wins
1500, Fri, 4,Feb,2022, 03,25,38,43,49,03,07, 109915000,    1
1499, Tue, 1,Feb,2022, 01,19,36,38,49,06,09,  52442757,    0
1498, Fri,28,Jan,2022, 10,25,29,34,45,09,10,  42779117,    0
...
1451, Tue,17,Aug,2021, 12,31,41,42,47,04,06,  14502700,    0
1450, Fri,13,Aug,2021, 06,12,44,47,49,08,12,  96295864,    1

All lotteries below have exceeded the 180 days expiry date
No., Day,DD,MMM,YYYY, N1,N2,N3,N4,N5,L1,L2,  Jackpot,   Wins
1449, Tue,10,Aug,2021, 09,37,47,48,49,02,07,  80768518,    0
1448, Fri, 6,Aug,2021, 07,14,21,26,32,04,12,  71953143,    0
...
3, Fri,27,Feb,2004, 14,18,19,31,37,04,05,  11880304,    0
  2, Fri,20,Feb,2004, 07,13,39,47,50,02,05,  10111500,    0
  1, Fri,13,Feb,2004, 16,29,32,36,41,07,09,  10143000,    1

This page shows all the draws that used any machine and any ball set in any year.

Data obtained from http://lottery.merseyworld.com/Euro/
```
</body></head></html>

</code>```

I just want to be able to extract the 1500 rows in a pandas dataframe and get rid of the text that occurs at the beginning, middle and end! Any help is appreciated. Thanks!

答:
This should give you the desired effect:</p>
```<code># Access the ``` tag
mysoup = mysoup.pre.text.split("\n")

# Create a DataFrame object
df = pd.DataFrame(mysoup)

# Split column 0 based on the seperator ","
df = df[0].str.split(',', expand=True)

# Strip each cell by using a lambda function
df = df.apply(lambda row: row.str.strip(), axis=1)

# Exclude all rows which do not have an entry in column 1
df = df[~df[1].isnull()]

# Set the column names based on the first row
df.columns = df.iloc[0]

# drop the first row since it is the same as our column names
df = df.drop(df.index[0])
</code>```

Title: Webpage Parsing

Body:
I am trying to parse a webpage and store the result in a table. However, I can't proceed any further as the parse result has some unwanted text at the top, middle and bottom of the csv. http://lottery.merseyworld.com/cgi-bin/lottery?days=20&Machine=Z&Ballset=0&order=1&show=1&year=0&display=CSV

import requests
from bs4 import BeautifulSoup
import pandas as pd

URL = "http://lottery.merseyworld.com/cgi-bin/lottery?days=20&Machine=Z&Ballset=0&order=1&show=1&year=0&display=CSV"

response = requests.get(URL)
mywebpage = response.text
mysoup = BeautifulSoup(mywebpage, "html.parser")

print(mysoup)

gives...

<title> Euro Millions Winning Numbers</title>

 Euro Millions Winning Numbers

No., Day,DD,MMM,YYYY, N1,N2,N3,N4,N5,L1,L2,  Jackpot,   Wins
1500, Fri, 4,Feb,2022, 03,25,38,43,49,03,07, 109915000,    1
1499, Tue, 1,Feb,2022, 01,19,36,38,49,06,09,  52442757,    0
1498, Fri,28,Jan,2022, 10,25,29,34,45,09,10,  42779117,    0
...
1451, Tue,17,Aug,2021, 12,31,41,42,47,04,06,  14502700,    0
1450, Fri,13,Aug,2021, 06,12,44,47,49,08,12,  96295864,    1

All lotteries below have exceeded the 180 days expiry date
No., Day,DD,MMM,YYYY, N1,N2,N3,N4,N5,L1,L2,  Jackpot,   Wins
1449, Tue,10,Aug,2021, 09,37,47,48,49,02,07,  80768518,    0
1448, Fri, 6,Aug,2021, 07,14,21,26,32,04,12,  71953143,    0
...
3, Fri,27,Feb,2004, 14,18,19,31,37,04,05,  11880304,    0
  2, Fri,20,Feb,2004, 07,13,39,47,50,02,05,  10111500,    0
  1, Fri,13,Feb,2004, 16,29,32,36,41,07,09,  10143000,    1

This page shows all the draws that used any machine and any ball set in any year.

Data obtained from http://lottery.merseyworld.com/Euro/

I just want to be able to extract the 1500 rows in a pandas dataframe and get rid of the text that occurs at the beginning, middle and end! Any help is appreciated. Thanks!

Body:
This should give you the desired effect:

# Access the <pre> tag
mysoup = mysoup.pre.text.split("\n")

# Create a DataFrame object
df = pd.DataFrame(mysoup)

# Split column 0 based on the seperator ","
df = df[0].str.split(',', expand=True)

# Strip each cell by using a lambda function
df = df.apply(lambda row: row.str.strip(), axis=1)

# Exclude all rows which do not have an entry in column 1
df = df[~df[1].isnull()]

# Set the column names based on the first row
df.columns = df.iloc[0]

# drop the first row since it is the same as our column names
df = df.drop(df.index[0])


问:
Transition Drawable - 3 options
I want to change button's style between 3 drawables : "normal", "green" and "red". I used TransitionDrawable, but it works only with 2 layers.

```<code><transition xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:drawable="@drawable/button" />
     <item android:drawable="@drawable/buttongreen" />
</transition>
</code>```

How would I implement another "android:drawable" or is there other way to achieve this, else than TransitionDrawable? How to switch between drawables, based on input (0 - stands for red, 1 - for green)?

答:
At this point you can't have more than 2 layers.

So, here is how I did it:

```<code>myView.setBackgroundResource(R.drawable.transition_drawable_green_yellow);
TransitionDrawable transition = (TransitionDrawable) myView.getBackground();
transition.startTransition(2000);

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {

myView.setBackgroundResource(R.drawable.transition_drawable_yellow_red);
TransitionDrawable transition = (TransitionDrawable) myView.getBackground();
transition.startTransition(2000);
     }
}, 2000);
</code>```

Title: Transition Drawable - 3 options

Body:
I want to change button's style between 3 drawables : "normal", "green" and "red". I used TransitionDrawable, but it works only with 2 layers.

<transition xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:drawable="@drawable/button" />
     <item android:drawable="@drawable/buttongreen" />
</transition>

How would I implement another "android:drawable" or is there other way to achieve this, else than TransitionDrawable? How to switch between drawables, based on input (0 - stands for red, 1 - for green)?

Body:
At this point you can't have more than 2 layers.

So, here is how I did it:

myView.setBackgroundResource(R.drawable.transition_drawable_green_yellow);
TransitionDrawable transition = (TransitionDrawable) myView.getBackground();
transition.startTransition(2000);

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {

myView.setBackgroundResource(R.drawable.transition_drawable_yellow_red);
TransitionDrawable transition = (TransitionDrawable) myView.getBackground();
transition.startTransition(2000);
     }
}, 2000);


问:
How to pass the latitude and longitude values to the ns url?
Iam developing one application.In that i use the google api for getting the location information.For that i use the CLLocationManager for getting the location latitude and longitude values.And my pblm is how to pass these latitude and longitude values to nsurl .ANd iam directly given the one location values to the url like below.

```<code>NSURL *URL = [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search           /json?location=40.7143528,-74.0059731&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM"];
</code>```

I write this one in below method for get and pass the latitude and longitude values.

```<code>- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
}
</code>```

So please tell me how to pass the newlocation.Coordinates.latitude and newlocation.Coordinates.longitude to that url in that method. Or Is there any way to pass that values in any other method.

答:
Just use this..</p>

```<code>NSString *url = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM",newLocation.latitude, newLocation.longitude];
NSURL *URL = [NSURL URLWithString:url];
</code>```

Body:
Iam developing one application.In that i use the google api for getting the location information.For that i use the CLLocationManager for getting the location latitude and longitude values.And my pblm is how to pass these latitude and longitude values to nsurl .ANd iam directly given the one location values to the url like below.

NSURL *URL = [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search           /json?location=40.7143528,-74.0059731&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM"];

I write this one in below method for get and pass the latitude and longitude values.

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
}

So please tell me how to pass the newlocation.Coordinates.latitude and newlocation.Coordinates.longitude to that url in that method. Or Is there any way to pass that values in any other method.

Body:
Just use this..

NSString *url = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM",newLocation.latitude, newLocation.longitude];
NSURL *URL = [NSURL URLWithString:url];


问:
React Native App crashes after updating Node Version
I have updated my node version, now my react native project is not working I am using react native cli. I have tried uninstalling the other versions of Node and gradlew clean and npm cache clean.

答:
If you don't plan to upgrade your react-native version, downgrade your node version to the one compatible with your project.

Check if node is installed and which version

```<code>node -v
</code>```

If you often have to switch between node versions you should use a version manager for node like nvm for easy switch.

Body:
If you don't plan to upgrade your react-native version, downgrade your node version to the one compatible with your project.

Check if node is installed and which version

node -v

If you often have to switch between node versions you should use a version manager for node like nvm for easy switch.


问:
Postman POST request works but doesnt when exported to cURL / request / http.request
I am completly lost because I got no idea anymore what I am doing wrong.

I want to make a simple POST request to a certain address. I visited the website using firefox, opened it's terminal, copied the POST request as cURL and executed in the terminal. The recieved response has status 200 but it's body is unreadable like "������q9i".

But when I use Postman->Import->cURL and execute the request it works?! Also status 200 but this time the body contains a properly readable html code just as expected.
So I though maybe it's because Postman is adjusted the request. So I opened the code panel to the right side of the program and exported Postman's request again as cURL, python - http.client and python - request, but none of them are working?! Again I just recieve an unreadable body. How on earth can this happen?

I'm using the same machine for all requests, there is no VPN or something so it cannot be related to IP address. There is no authentification or anything.

There is just maybe one hint I noticed: The response recieved in Postman is exactly one byte shorter then the one recieved in cURL or python. Could this be the problem? Is Postman handling the response's body differently?

I appreciate any help a lot!

答:
cURL is displaying the raw response of the body, while Postman and Firefox process the response. In your case, I suspect that you request a zipped response with a header like Accept-Encoding: gzip, deflate. If you remove that header, you will get the uncompressed response.

If there is no such header in your request, it would be good to see the request you are trying to execute.


问:
How to set value to input field in react
How to set the value to the input field in react. Data is fetching from firebase.
I was trying to fetch data from the firebase and then data is populated to the input field. But data is sometimes set to input field sometimes not.</p>

答:
You can use the useRef hook to avoid unnecessary rerender:</p>
```<code>import {useRef, userEffect} from 'react'

const Test:React.FC = () => {
   const inputRef = useRef(null)

   userEffect(() => {
      const resp = yourAsyncGetData()
      inputRef.current.value = (resp)
   }, [])

   return <input ref={inputRef} />
}

export default Test
</code>```

Body:
You can use the useRef hook to avoid unnecessary rerender:

import {useRef, userEffect} from 'react'

const Test:React.FC = () => {
   const inputRef = useRef(null)

   userEffect(() => {
      const resp = yourAsyncGetData()
      inputRef.current.value = (resp)
   }, [])

   return <input ref={inputRef} />
}

export default Test


问:
IAM Permissions Errors When Using boto3 for AWS Comprehend
I'm playing around with the command line to run some sentiment analysis through aws and am running into some IAM issues. When running the "detect_dominant_language" function, I'm hitting NotAuthorizedExceptions despite having the policy in place to allow for all comprehend functions. The policy for the account is:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "comprehend:*",
                "s3:ListAllMyBuckets",
                "s3:ListBucket",
                "s3:GetBucketLocation",
                "iam:ListRoles",
                "iam:GetRole"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}
</code>```

Any ideas of where I might be going wrong with this? I've triple-checked my access key to make sure that I'm referring to the correct account. When I check the policy, it's there so I'm a little bit at a loss as to the disconnect. S3 seems to be working fine as well.

Steps already taken:

Resetting access key/secret access key.

Creating iam policy which explicitly refers to the needed functionality and attaching it to the "Admin" user.

Calling this method from the CLI (get the same error).

Below, I've included additional information that may be helpful...

Code to check iam policies:

```<code>iam = boto3.client('iam',
                   aws_access_key_id = '*********************',
                   aws_secret_access_key = '*************************************')

iam.list_attached_user_policies(UserName="Admin")
</code>```

Output:

```<code>{'AttachedPolicies': [{'PolicyName': 'ComprehendFullAccess',
   'PolicyArn': 'arn:aws:iam::aws:policy/ComprehendFullAccess'},
  {'PolicyName': 'AdministratorAccess',
   'PolicyArn': 'arn:aws:iam::aws:policy/AdministratorAccess'},
  {'PolicyName': 'Comprehend-Limitied',
   'PolicyArn': 'arn:aws:iam::401311205158:policy/Comprehend-Limitied'}],
 'IsTruncated': False,
 'ResponseMetadata': {'RequestId': '9094d8ff-1730-44b8-af0f-9222a63b32e9',
  'HTTPStatusCode': 200,
  'HTTPHeaders': {'x-amzn-requestid': '9094d8ff-1730-44b8-af0f-9222a63b32e9',
   'content-type': 'text/xml',
   'content-length': '871',
   'date': 'Thu, 20 Jan 2022 21:48:11 GMT'},
  'RetryAttempts': 0}}
</code>```

Code to trigger error:

```<code>comprehend = boto3.client('comprehend',
                   aws_access_key_id = '*********************',
                   aws_secret_access_key = '********************************')

test_language_string = "This is a test string. I'm hoping that AWS Comprehend can interprete this as english..."

comprehend.detect_dominant_language(Text=test_language_string)
</code>```

Output:

```<code>ClientError: An error occurred (NotAuthorizedException) when calling the DetectDominantLanguage operation: Your account is not authorized to make this call.
</code>```

答:
I encountered the same error and I end up creating a new user group and a user for that particular API access. Here're the steps in a nutshell:

Create a user group (e.g. Research)

Give access to ComprehendFullAccess

Create a user (e.g.
ComprehendUser) under the newly created user group (i.e.
Research)

Bingo! It should work now.

Here is my code snippet:

```<code># import packages
import boto3

# aws access credentials
AWS_ACCESS_KEY_ID = 'your-access-key'
AWS_SECRET_ACCESS_KEY = 'your-secret-key'

comprehend = boto3.client('comprehend',
                          aws_access_key_id=AWS_ACCESS_KEY_ID,
                          aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
                          region_name='us-east-1')

test_language_string = "This is a test string. I'm hoping that AWS Comprehend can interprete this as english..."
comprehend.detect_dominant_language(Text=test_language_string)
</code>```

Expected Output

```<code>{'Languages': [{'LanguageCode': 'en', 'Score': 0.9753355979919434}],
 'ResponseMetadata': {'RequestId': 'd2ab429f-6ff7-4f9b-9ec2-dbf494ebf20a',
  'HTTPStatusCode': 200,
  'HTTPHeaders': {'x-amzn-requestid': 'd2ab429f-6ff7-4f9b-9ec2-dbf494ebf20a',
   'content-type': 'application/x-amz-json-1.1',
   'content-length': '64',
   'date': 'Mon, 07 Feb 2022 16:31:36 GMT'},
  'RetryAttempts': 0}}
</code>```

Body:
I'm playing around with the command line to run some sentiment analysis through aws and am running into some IAM issues. When running the "detect_dominant_language" function, I'm hitting NotAuthorizedExceptions despite having the policy in place to allow for all comprehend functions. The policy for the account is:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "comprehend:*",
                "s3:ListAllMyBuckets",
                "s3:ListBucket",
                "s3:GetBucketLocation",
                "iam:ListRoles",
                "iam:GetRole"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}

Any ideas of where I might be going wrong with this? I've triple-checked my access key to make sure that I'm referring to the correct account. When I check the policy, it's there so I'm a little bit at a loss as to the disconnect. S3 seems to be working fine as well.

Steps already taken:

Resetting access key/secret access key.

Creating iam policy which explicitly refers to the needed functionality and attaching it to the "Admin" user.

Calling this method from the CLI (get the same error).

Below, I've included additional information that may be helpful...

Code to check iam policies:

iam = boto3.client('iam',
                   aws_access_key_id = '*********************',
                   aws_secret_access_key = '*************************************')

iam.list_attached_user_policies(UserName="Admin")

Output:

{'AttachedPolicies': [{'PolicyName': 'ComprehendFullAccess',
   'PolicyArn': 'arn:aws:iam::aws:policy/ComprehendFullAccess'},
  {'PolicyName': 'AdministratorAccess',
   'PolicyArn': 'arn:aws:iam::aws:policy/AdministratorAccess'},
  {'PolicyName': 'Comprehend-Limitied',
   'PolicyArn': 'arn:aws:iam::401311205158:policy/Comprehend-Limitied'}],
 'IsTruncated': False,
 'ResponseMetadata': {'RequestId': '9094d8ff-1730-44b8-af0f-9222a63b32e9',
  'HTTPStatusCode': 200,
  'HTTPHeaders': {'x-amzn-requestid': '9094d8ff-1730-44b8-af0f-9222a63b32e9',
   'content-type': 'text/xml',
   'content-length': '871',
   'date': 'Thu, 20 Jan 2022 21:48:11 GMT'},
  'RetryAttempts': 0}}

Code to trigger error:

comprehend = boto3.client('comprehend',
                   aws_access_key_id = '*********************',
                   aws_secret_access_key = '********************************')

test_language_string = "This is a test string. I'm hoping that AWS Comprehend can interprete this as english..."

comprehend.detect_dominant_language(Text=test_language_string)

Output:

ClientError: An error occurred (NotAuthorizedException) when calling the DetectDominantLanguage operation: Your account is not authorized to make this call.

Body:
I encountered the same error and I end up creating a new user group and a user for that particular API access. Here're the steps in a nutshell:

Create a user group (e.g. Research)

Give access to ComprehendFullAccess

Create a user (e.g.
ComprehendUser) under the newly created user group (i.e.
Research)

Bingo! It should work now.

Here is my code snippet:

# import packages
import boto3

# aws access credentials
AWS_ACCESS_KEY_ID = 'your-access-key'
AWS_SECRET_ACCESS_KEY = 'your-secret-key'

comprehend = boto3.client('comprehend',
                          aws_access_key_id=AWS_ACCESS_KEY_ID,
                          aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
                          region_name='us-east-1')

test_language_string = "This is a test string. I'm hoping that AWS Comprehend can interprete this as english..."
comprehend.detect_dominant_language(Text=test_language_string)

Expected Output

{'Languages': [{'LanguageCode': 'en', 'Score': 0.9753355979919434}],
 'ResponseMetadata': {'RequestId': 'd2ab429f-6ff7-4f9b-9ec2-dbf494ebf20a',
  'HTTPStatusCode': 200,
  'HTTPHeaders': {'x-amzn-requestid': 'd2ab429f-6ff7-4f9b-9ec2-dbf494ebf20a',
   'content-type': 'application/x-amz-json-1.1',
   'content-length': '64',
   'date': 'Mon, 07 Feb 2022 16:31:36 GMT'},
  'RetryAttempts': 0}}


问:
Error: Couldn't load css dependency nv.d3.css when accessing odoo via nginx proxy
I do not get any error when I access and login to odoo with the below default URL

http://erp.mybank.com:8069

However, after setting up SSL with nginx proxy pass I get the below error after login with my credentials

https://erp.mybank.com

Below is nginx configuration for setting up proxy pass to odoo

```<code>root /var/www/html;

# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name erp.mybank.com; # managed by Certbot

location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
  try_files $uri $uri/ =404;
  proxy_pass      http://localhost:8069;
}

location /web {
  proxy_pass      http://localhost:8069;
}
</code>```

Error output:

```<code>Error: Couldn't load css dependency: https://erp.mybank.com/hrms_dashboard/static/src/css/lib/nv.d3.css
    at HTMLLinkElement.<anonymous> (https://erp.mybank.com/web/assets/835-f142dd9/web.assets_common.min.js:4674:359)
    at HTMLLinkElement.dispatch (https://erp.mybank.com/web/assets/835-f142dd9/web.assets_common.min.js:1785:447)
    at HTMLLinkElement.elemData.handle (https://erp.mybank.com/web/assets/835-f142dd9/web.assets_common.min.js:1771:166)
</code>```

There is not many suggestions/solution online.

Any clues on how to resolve this?

答:
Your nginx configuration is not enough to load all static assets for Odoo, you need to follow Odoo official documentation for deploying Odoo with Nginx as a reverse proxy server. Here is the simplest configuration for your setup:

```<code>upstream odoo {
server 127.0.0.1:8069;
}
upstream odoochat {
server 127.0.0.1:8072;
}

# http -> https
server {
listen 80;
server_name erp.mybank.com;
proxy_read_timeout 720s;
proxy_connect_timeout 720s;
proxy_send_timeout 720s;

# Add Headers for odoo proxy mode
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;

# log
access_log /var/log/nginx/odoo.access.log;
error_log /var/log/nginx/odoo.error.log;

# Redirect longpoll requests to odoo longpolling port
location /longpolling {
    proxy_pass http://odoochat;
}

# Redirect requests to odoo backend server
location / {
    proxy_redirect off;
    proxy_pass http://odoo;
}

# common gzip
gzip_types text/css text/scss text/plain text/xml application/xml application/json application/javascript;
gzip on;
}
</code>```

For more information please follow the official documentation.

Body:
I do not get any error when I access and login to odoo with the below default URL

http://erp.mybank.com:8069

However, after setting up SSL with nginx proxy pass I get the below error after login with my credentials

https://erp.mybank.com

Below is nginx configuration for setting up proxy pass to odoo

root /var/www/html;

# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name erp.mybank.com; # managed by Certbot

location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
  try_files $uri $uri/ =404;
  proxy_pass      http://localhost:8069;
}

location /web {
  proxy_pass      http://localhost:8069;
}

Error output:

Error: Couldn't load css dependency: https://erp.mybank.com/hrms_dashboard/static/src/css/lib/nv.d3.css
    at HTMLLinkElement.<anonymous> (https://erp.mybank.com/web/assets/835-f142dd9/web.assets_common.min.js:4674:359)
    at HTMLLinkElement.dispatch (https://erp.mybank.com/web/assets/835-f142dd9/web.assets_common.min.js:1785:447)
    at HTMLLinkElement.elemData.handle (https://erp.mybank.com/web/assets/835-f142dd9/web.assets_common.min.js:1771:166)

There is not many suggestions/solution online.

Any clues on how to resolve this?

Body:
Your nginx configuration is not enough to load all static assets for Odoo, you need to follow Odoo official documentation for deploying Odoo with Nginx as a reverse proxy server. Here is the simplest configuration for your setup:

upstream odoo {
server 127.0.0.1:8069;
}
upstream odoochat {
server 127.0.0.1:8072;
}

# http -> https
server {
listen 80;
server_name erp.mybank.com;
proxy_read_timeout 720s;
proxy_connect_timeout 720s;
proxy_send_timeout 720s;

# Add Headers for odoo proxy mode
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;

# log
access_log /var/log/nginx/odoo.access.log;
error_log /var/log/nginx/odoo.error.log;

# Redirect longpoll requests to odoo longpolling port
location /longpolling {
    proxy_pass http://odoochat;
}

# Redirect requests to odoo backend server
location / {
    proxy_redirect off;
    proxy_pass http://odoo;
}

# common gzip
gzip_types text/css text/scss text/plain text/xml application/xml application/json application/javascript;
gzip on;
}

For more information please follow the official documentation.


问:
Why does the JScrollPane show up but not its scroll bar?
Here is my code. The JScrollpanel shows up but now the scrollbar. I also can't use the scroll wheel if the text goes below the area.</p>
```<code>JTextArea textArea = new JTextArea("Enter text here");
textArea.setPreferredSize(new Dimension(100,100));
textArea.setLineWrap(true);
textArea.setEditable(true);
textArea.setVisible(true);
JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

//frame
this.setTitle("GUI Practice");
this.setLayout(new BorderLayout());
this.setResizable(true);
this.setSize(720,480);
this.setLocationRelativeTo ( null );
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.add(scroll, BorderLayout.SOUTH);
this.setVisible(true);
</code>```

答:
Never, never, NEVER do this:

```<code>textArea.setPreferredSize(new Dimension(100,100));
</code>```

You are artificially constraining the size of the JTextArea, and you yourself are causing the JScrollPane to fail. Instead, set the JTextArea's column and row properties.

e.g.,

```<code>import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.*;

@SuppressWarnings("serial")
public class GuiPracticePanel extends JPanel {
    private static final int ROWS = 10;
    private static final int COLS = 80;
    private static final String INIT_TEXT = "Enter text here";

    private JTextArea textArea = new JTextArea(INIT_TEXT, ROWS, COLS);

    public GuiPracticePanel() {
        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        setLayout(new BorderLayout());
        add(Box.createRigidArea(new Dimension(400, 300)));
        add(scrollPane, BorderLayout.PAGE_END);

        textArea.selectAll();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            GuiPracticePanel mainPanel = new GuiPracticePanel();

            JFrame frame = new JFrame("GUI");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(mainPanel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}
</code>```

Body:
Here is my code. The JScrollpanel shows up but now the scrollbar. I also can't use the scroll wheel if the text goes below the area.

JTextArea textArea = new JTextArea("Enter text here");
textArea.setPreferredSize(new Dimension(100,100));
textArea.setLineWrap(true);
textArea.setEditable(true);
textArea.setVisible(true);
JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

//frame
this.setTitle("GUI Practice");
this.setLayout(new BorderLayout());
this.setResizable(true);
this.setSize(720,480);
this.setLocationRelativeTo ( null );
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.add(scroll, BorderLayout.SOUTH);
this.setVisible(true);

Body:
Never, never, NEVER do this:

textArea.setPreferredSize(new Dimension(100,100));

You are artificially constraining the size of the JTextArea, and you yourself are causing the JScrollPane to fail. Instead, set the JTextArea's column and row properties.

e.g.,

import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.*;

@SuppressWarnings("serial")
public class GuiPracticePanel extends JPanel {
    private static final int ROWS = 10;
    private static final int COLS = 80;
    private static final String INIT_TEXT = "Enter text here";

    private JTextArea textArea = new JTextArea(INIT_TEXT, ROWS, COLS);

    public GuiPracticePanel() {
        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        setLayout(new BorderLayout());
        add(Box.createRigidArea(new Dimension(400, 300)));
        add(scrollPane, BorderLayout.PAGE_END);

        textArea.selectAll();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            GuiPracticePanel mainPanel = new GuiPracticePanel();

            JFrame frame = new JFrame("GUI");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(mainPanel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}


问:
Vue 2 - Styling HTML returned in a switch statement
I'm building a generic component supposed to receive various backend data. I wrote a switch. One condition is :

```<code>case 'Bases':
                let bases = variant[tableName][colValue].map((base) => {
                    return `<div class="base b${base.strongestIndication}">${base.name}</div>`
                })
                return bases.join('')
</code>```

I use v-html in my template, therefore in this case, we have 3 divs created, each with a class of "base" and then "b1", "b2", "b3". I can see on the webpage that these classes are properly set when I inspect the elements.

I've described in my style some rules for theses classes (mostly background-color, border-radius and so on), but they do not apply.

I'm guessing this might have something to do with the CSS being applied before these divs are created but I'm not sure of this.

What should I do to get these tags created by JS to be styled properly ?

(Also, I know using v-html can be dangerous, therefore if you have a better idea for this whole thing, I'm all ears)

答:
There is no need to build the markup in component methods. Define it in template and bind the classes dynamically. Since you didn't post the api data structure, neither how you are using this snippet of code, I can only refactor the specific case.

<div
  v-for="base in colValues"
  :class="['base', `b${base.strongestIndication}`]">
  {{base.name}}

```

Body:
I'm building a generic component supposed to receive various backend data. I wrote a switch. One condition is :

case 'Bases':
                let bases = variant[tableName][colValue].map((base) => {
                    return `<div class="base b${base.strongestIndication}">${base.name}</div>`
                })
                return bases.join('')

I use v-html in my template, therefore in this case, we have 3 divs created, each with a class of "base" and then "b1", "b2", "b3". I can see on the webpage that these classes are properly set when I inspect the elements.

I've described in my style some rules for theses classes (mostly background-color, border-radius and so on), but they do not apply.

I'm guessing this might have something to do with the CSS being applied before these divs are created but I'm not sure of this.

What should I do to get these tags created by JS to be styled properly ?

(Also, I know using v-html can be dangerous, therefore if you have a better idea for this whole thing, I'm all ears)

Body:
There is no need to build the markup in component methods. Define it in template and bind the classes dynamically. Since you didn't post the api data structure, neither how you are using this snippet of code, I can only refactor the specific case.

<div
  v-for="base in colValues"
  :class="['base', `b${base.strongestIndication}`]">
  {{base.name}}
</div>


问:
How to customize BotFramework webchat react UI
I'm just started exploring botframework webchat with React. I have tried to come until below UI.

current ui image

In docs, its mentioned like we can control each parts of the UI using React. But I couldn't see samples that could modify webchat message styles like (user/bot message height, customize message input field). In the ReactWebChat component, there is a className prop.

```<code><ReactWebChat
    className={`${className || ''} web-chat`}
</code>```

Is it recommended to use this classname in-conjunction with message class selector (.web-chat .webchat__bubble__content p) to customize UI ?

user image inspect element

Thanks

答:
This document should get you started. Most basic styling is available via configuration-settings.

The border of a textmessage for instance could be implemented via styleoptions:

```<code><!DOCTYPE html>
<head>
    <script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
</head>
<body>
  <div style="height: 60%; width: 40%; margin-top:5%; margin-left:10%" id="webchat" role="main"></div>
  <script>
     // Set the CSS rules.
     const styleSet = window.WebChat.createStyleSet({
         ...
         bubbleBorderColor: '#E6E6E6',
         bubbleBorderRadius: 2,
         bubbleBorderStyle: 'solid',
         bubbleBorderWidth: 1,
         ...
      });

    window.WebChat.renderWebChat({
      directLine: window.WebChat.createDirectLine({
          token: '<Your Direct Line token>'}),
      styleSet
    }, document.getElementById('webchat'));

  </script>
</body>
</code>```

Body:
I'm just started exploring botframework webchat with React. I have tried to come until below UI.

current ui image

In docs, its mentioned like we can control each parts of the UI using React. But I couldn't see samples that could modify webchat message styles like (user/bot message height, customize message input field). In the ReactWebChat component, there is a className prop.

<ReactWebChat
    className={`${className || ''} web-chat`}

Is it recommended to use this classname in-conjunction with message class selector (.web-chat .webchat__bubble__content p) to customize UI ?

user image inspect element

Thanks

Body:
This document should get you started. Most basic styling is available via configuration-settings.

The border of a textmessage for instance could be implemented via styleoptions:

<!DOCTYPE html>
<head>
    <script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
</head>
<body>
  <div style="height: 60%; width: 40%; margin-top:5%; margin-left:10%" id="webchat" role="main"></div>
  <script>
     // Set the CSS rules.
     const styleSet = window.WebChat.createStyleSet({
         ...
         bubbleBorderColor: '#E6E6E6',
         bubbleBorderRadius: 2,
         bubbleBorderStyle: 'solid',
         bubbleBorderWidth: 1,
         ...
      });

    window.WebChat.renderWebChat({
      directLine: window.WebChat.createDirectLine({
          token: '<Your Direct Line token>'}),
      styleSet
    }, document.getElementById('webchat'));

  </script>
</body>