问:
Is it possible to programatically alter tables with Core Data
I'm working on a project in which I might need to change my local database, according to information fetched from a server.
I've read about Core Data, but from all I saw it uses a pre-defined database structures, and I haven't found a way to alter a table by code with it.

I was wondering - should I use Core Data for this use? or should I stick with low-level objective-c wrap for SQLite?

Tnx in advance!

答:
I am going to go ahead and say "no, that is not a good idea" mainly because core data requires a lot of generated code to work properly...code which is generated in the XCode environment, not in the application environment.

For example, if you come up with schema for your data, XCode creates data entity objects and links them in specific ways which you shouldn't tamper with. If you were to attempt to alter the schema in real time, you would have to effectively regenerate all those entities and their linkages...which seems impossible. In my experience, any core data schema change requires a clean, delete and reinstall of the application before it will run again as well as resetting the host device's data entirely in some cases to get rid of the old data.

So no...seems unlikely to work.


来源: stackexchange

问:
Microsoft Graph API - OData Filter - Invalid filter clause
I cannot seem to get an Odata filter to work for the below URL... an error is always returned Invalid filter clause

https://graph.microsoft.com/beta/identity/b2cUserFlows/B2C_1_api-v3-signin/userflowIdentityProviders?$filter=value/domainHint eq 'mydomain.com'

I have tried other similar combinations such as...

$filter=domainHint eq 'mydomain.com'

$filter=startsWith(value/domainHint, 'mydomain.com')

$filter=startsWith(domainHint, 'mydomain.com')

{
    "@odata.context": "https://graph.microsoft.com/beta/$metadata#Collection(microsoft.graph.identityProviderBase)",
    "value": [
        {
            "@odata.type": "#microsoft.graph.openIdConnectIdentityProvider",
            "id": "OIDC-V1-00000000-0000-0000-0000-000000000000",
            "displayName": "Azure AD",
            "clientId": "00000000-0000-0000-0000-000000000000",
            "clientSecret": "******",
            "scope": "openid profile",
            "metadataUrl": "https://login.microsoftonline.com/mydomain.onmicrosoft.com/v2.0/.well-known/openid-configuration",
            "domainHint": "mydomain.com",
            "responseType": "code",
            "responseMode": "form_post",
            "claimsMapping": {
                "userId": "oid",
                "displayName": "name",
                "givenName": "given_name",
                "surname": "family_name",
                "email": "email"
            }
        },
        {
            "@odata.type": "#microsoft.graph.openIdConnectIdentityProvider",
            "id": "OIDC-V1-11111111-1111-1111-1111-111111111111",
            "displayName": "Okta",
            "clientId": "11111111-1111-1111-1111-111111111111",
            "clientSecret": "******",
            "scope": "openid profile email",
            "metadataUrl": "https://XYZ.okta.com/.well-known/openid-configuration",
            "domainHint": "otherdomain.com",
            "responseType": "code",
            "responseMode": "form_post",
            "claimsMapping": {
                "userId": "sub",
                "displayName": "name",
                "givenName": "given_name",
                "surname": "family_name",
                "email": "email"
            }
        }
    ]
}
```

答:
You don't filter on the value node at all, value is not part of the model, it is a part of the response wrapper only.

```<code>https://graph.microsoft.com/beta/identity/b2cUserFlows/B2C_1_api-v3-signin/userflowIdentityProviders?$filter=domainHint eq 'mydomain.com'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You don't filter on the value node at all, value is not part of the model, it is a part of the response wrapper only.

https://graph.microsoft.com/beta/identity/b2cUserFlows/B2C_1_api-v3-signin/userflowIdentityProviders?$filter=domainHint eq 'mydomain.com'


问:
Renderer2.setProperty() doesn't update the value
I am trying to update the value using the rendered.setproperty() where value is updating the second time on listen  event

these are the value that I am sending for the first time as empty in some widget

<ols-giftcard-payment-widget site-id="dddd" customer-last-name="" jwt-token="abcd"></ols-giftcard-payment-widget>```
</div>
</div>
</p>
<p>here I want to update the customer-last-name as a dynamic value</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component, Renderer2 } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular';
  constructor(private renderer: Renderer2) {}
  createRecaptchaContainer() {
    const recaptchaContainer = this.renderer.createElement(
      'ols-giftcard-payment-widget'
    );
    this.renderer.setProperty(recaptchaContainer, 'siteId', '56711');
    this.renderer.setProperty(
      recaptchaContainer,
      'jwtToken',
      'abcd'
    );
    let cardClickEvent = this.renderer.listen(
      recaptchaContainer,
      'addCard',
      (evt) => {
        this.renderer.setProperty(
          recaptchaContainer,
          'customerLastName',
          'anonymousLastName'
        );
        this.renderer.appendChild(
          document.getElementById('payment-widget'),
          recaptchaContainer
        );

        return recaptchaContainer;

        debugger;
      }
    );
    this.renderer.appendChild(
      document.getElementById('payment-widget'),
      recaptchaContainer
    );

    return recaptchaContainer;
  }

  ngOnInit(): void {
    this.createRecaptchaContainer();
  }
}</code>```

```

Here I am trying to add the customerLastname in this setProperty
this.renderer.setProperty(
recaptchaContainer,
'customerLastName',
'anonymousLastName'
);
it is updating on the second click, not on the first click

please help me to find here where I am wrong in the implementation

答:
Your error message was Please provide the last name. Apparently recaptchaContainer needs a name to work.

When you click "Add card" for the first time customerLastName is empty. Look it up on localStorage under key cardDetails. anonymousLastName is added with click listener event from the component after data has been sent, that's why it works second time around.

```<code>{
  "siteId": "56711",
  "customerNumber": "",
  "customerFirstName": "",
  "customerLastName": "anonymousLastName",
  "customerSession": "",
  "companyId": "",
  "primaryColor": "#2196F3"
}
</code>```

To fix this, we could also setProperty for customerLastName outside of the event listener, so that customerLastName would be populated on first click. Either that or put something in customer-last-name="".

```<code><hello name="{{ name }}"></hello>

<div id="payment-widget" (click)="setUsername('123')"></div>
<br>
<input [(ngModel)]="username" (input)="onChange()" #ctrl="ngModel" required>

<p>Value: {{ username }}</p>
<p>Valid: {{ ctrl.valid }}</p>
</code>```

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  show: boolean = false;
  jwtToknVal = of();
  title = 'angular';
  username: string;
  recaptchaContainer: any;

  constructor(private renderer: Renderer2) {}
  createRecaptchaContainer() {
    this.recaptchaContainer = this.renderer.createElement(
      'ols-giftcard-payment-widget'
    );
    this.renderer.setProperty(this.recaptchaContainer, 'siteId', '56711');
    this.renderer.setProperty(
      this.recaptchaContainer,
      'jwtToken',
      'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vMXJ5ZzMwZjZnay5leGVjdXRlLWFwaS51cy13ZXN0LTIuYW1hem9uYXdzLmNvbS9hdXRoZW50aWNhdGUiLCJzY29wZSI6InNlbGYiLCJpYXQiOjE2MTkxMTIxMjcsImV4cCI6MTcxOTE5ODUyNywicm9sZXMiOlsiY29tbXVuaXR5X2FwcGxpY2F0aW9uX2FjY2Vzc3wxMTE4N3wxIl0sInVzZXIiOnsiaWQiOiIyNTc1NyIsIm5hbWUiOiJTaG9ydGN1dHMiLCJzdXJuYW1lIjoiUFBGIiwiZ2l2ZW5fbmFtZSI6IlNob3J0Y3V0cyIsImRpc3BsYXlfbmFtZSI6IlNob3J0Y3V0cyBQUEYiLCJlbWFpbCI6InNob3J0Y3V0c0BzaG9ydGN1dHNzb2Z0d2FyZWRldi5jb20ifX0.vll2mLmdtBuuz0mnlENEAs1xT0In0NmYKBWD67VfYdw'
    );
    this.renderer.appendChild(
      document.getElementById('payment-widget'),
      this.recaptchaContainer
    );

    this.renderer.setProperty(
      this.recaptchaContainer,
      'customerLastName',
      this.username
    );
    this.renderer.listen(this.recaptchaContainer, 'addCard', (evt) => {
      console.log(this.recaptchaContainer, evt);
      this.renderer.setProperty(
        this.recaptchaContainer,
        'customerLastName',
        this.username
      );
      return this.recaptchaContainer;
    });
  }

  ngOnInit(): void {
    this.createRecaptchaContainer();
  }

  onChange() {
    console.log(this.username);
  }

  setUsername(name: string) {
    this.renderer.setProperty(
      this.recaptchaContainer,
      'customerLastName',
      name
    );
  }
}

```

Here is a working example: https://stackblitz.com/edit/angular-rkua7n?file=src%2Fapp%2Fapp.component.ts

Body:
I am trying to update the value using the rendered.setproperty() where value is updating the second time on listen  event

these are the value that I am sending for the first time as empty in some widget

<ols-giftcard-payment-widget site-id="dddd" customer-last-name="" jwt-token="abcd"></ols-giftcard-payment-widget>

here I want to update the customer-last-name as a dynamic value

import { Component, Renderer2 } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular';
  constructor(private renderer: Renderer2) {}
  createRecaptchaContainer() {
    const recaptchaContainer = this.renderer.createElement(
      'ols-giftcard-payment-widget'
    );
    this.renderer.setProperty(recaptchaContainer, 'siteId', '56711');
    this.renderer.setProperty(
      recaptchaContainer,
      'jwtToken',
      'abcd'
    );
    let cardClickEvent = this.renderer.listen(
      recaptchaContainer,
      'addCard',
      (evt) => {
        this.renderer.setProperty(
          recaptchaContainer,
          'customerLastName',
          'anonymousLastName'
        );
        this.renderer.appendChild(
          document.getElementById('payment-widget'),
          recaptchaContainer
        );

        return recaptchaContainer;

        debugger;
      }
    );
    this.renderer.appendChild(
      document.getElementById('payment-widget'),
      recaptchaContainer
    );

    return recaptchaContainer;
  }

  ngOnInit(): void {
    this.createRecaptchaContainer();
  }
}

Here I am trying to add the customerLastname in this setProperty
this.renderer.setProperty(
recaptchaContainer,
'customerLastName',
'anonymousLastName'
);
it is updating on the second click, not on the first click

please help me to find here where I am wrong in the implementation

Body:
Your error message was Please provide the last name. Apparently recaptchaContainer needs a name to work.

When you click "Add card" for the first time customerLastName is empty. Look it up on localStorage under key cardDetails. anonymousLastName is added with click listener event from the component after data has been sent, that's why it works second time around.

{
  "siteId": "56711",
  "customerNumber": "",
  "customerFirstName": "",
  "customerLastName": "anonymousLastName",
  "customerSession": "",
  "companyId": "",
  "primaryColor": "#2196F3"
}

To fix this, we could also setProperty for customerLastName outside of the event listener, so that customerLastName would be populated on first click. Either that or put something in customer-last-name="".

<hello name="{{ name }}"></hello>

<div id="payment-widget" (click)="setUsername('123')"></div>
<br>
<input [(ngModel)]="username" (input)="onChange()" #ctrl="ngModel" required>

<p>Value: {{ username }}</p>
<p>Valid: {{ ctrl.valid }}</p>

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  show: boolean = false;
  jwtToknVal = of();
  title = 'angular';
  username: string;
  recaptchaContainer: any;

  constructor(private renderer: Renderer2) {}
  createRecaptchaContainer() {
    this.recaptchaContainer = this.renderer.createElement(
      'ols-giftcard-payment-widget'
    );
    this.renderer.setProperty(this.recaptchaContainer, 'siteId', '56711');
    this.renderer.setProperty(
      this.recaptchaContainer,
      'jwtToken',
      'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vMXJ5ZzMwZjZnay5leGVjdXRlLWFwaS51cy13ZXN0LTIuYW1hem9uYXdzLmNvbS9hdXRoZW50aWNhdGUiLCJzY29wZSI6InNlbGYiLCJpYXQiOjE2MTkxMTIxMjcsImV4cCI6MTcxOTE5ODUyNywicm9sZXMiOlsiY29tbXVuaXR5X2FwcGxpY2F0aW9uX2FjY2Vzc3wxMTE4N3wxIl0sInVzZXIiOnsiaWQiOiIyNTc1NyIsIm5hbWUiOiJTaG9ydGN1dHMiLCJzdXJuYW1lIjoiUFBGIiwiZ2l2ZW5fbmFtZSI6IlNob3J0Y3V0cyIsImRpc3BsYXlfbmFtZSI6IlNob3J0Y3V0cyBQUEYiLCJlbWFpbCI6InNob3J0Y3V0c0BzaG9ydGN1dHNzb2Z0d2FyZWRldi5jb20ifX0.vll2mLmdtBuuz0mnlENEAs1xT0In0NmYKBWD67VfYdw'
    );
    this.renderer.appendChild(
      document.getElementById('payment-widget'),
      this.recaptchaContainer
    );

    this.renderer.setProperty(
      this.recaptchaContainer,
      'customerLastName',
      this.username
    );
    this.renderer.listen(this.recaptchaContainer, 'addCard', (evt) => {
      console.log(this.recaptchaContainer, evt);
      this.renderer.setProperty(
        this.recaptchaContainer,
        'customerLastName',
        this.username
      );
      return this.recaptchaContainer;
    });
  }

  ngOnInit(): void {
    this.createRecaptchaContainer();
  }

  onChange() {
    console.log(this.username);
  }

  setUsername(name: string) {
    this.renderer.setProperty(
      this.recaptchaContainer,
      'customerLastName',
      name
    );
  }
}

Here is a working example: https://stackblitz.com/edit/angular-rkua7n?file=src%2Fapp%2Fapp.component.ts


问:
Azure app configuration throws exception & does not load the configuration when a disabled key vault secret is present as KV reference
I have an Azure app configuration with 2 keys. Both have key vault references as values. When one of the key-vault secrets is disabled for some reason (because expiration date has passed, not needed for now etc.,), entire configuration loading fails with KeyVault reference exception.
I tried using SetSecretResolver, but it looks like if the registered KV client encounters any exception, secret resolver fallback will not be called. Is there any solution for this issue? Basically, I don't want to stop loading the config, if any or some of the KV secrets are disabled.
BTW, I tried setting the "Options: true" to suppress the exception throwing, but that did not load the config.

app config Keys:-

```<code>abc:def:key1 - has a valid key vault secret
abc:def:key2 - has a disabled key vault secret.
</code>```

code:-

```<code>public IConfiguration AzureAppConfig { get; set; }
public IConfigurationRefresher AzureAppConfigRefresher { get; set; }

builder.AddAzureAppConfiguration(options =>
                {
                    options.Connect(new Uri("uri"), credential)
                        .Select("abc:def:*")
                        .ConfigureKeyVault(kvOptions =>
                        {
                            kvOptions.SetCredential(credential);
                        })
                    .ConfigureRefresh(refresh =>
                    {
                        refresh.Register("abc:def:key1")
                            .SetCacheExpiration(TimeSpan.FromMinutes(30));
                    });
                    AzureAppConfigRefresher = options.GetRefresher();
                });

AzureAppConfig = builder.Build();
</code>```

Thanks in advance for any help.

答:
Key Vault does not allow read operations on disabled/expired secrets and throws 403 error. This is by design. App Config provider never hides the exceptions thrown by KeyVault because that would leave the application configuration in an undefined state. But if you want more control over error handling, you can implement your own secret resolver by using the SetSecretResolver API.

I tried using SetSecretResolver, but it looks like if the registered KV client encounters any exception, secret resolver fallback will not be called.

That is correct. SetSecretResolver doesn't handle errors thrown by registered SecretClient(s). It will only be used when no SecretClient has been registered with the same vault URI. This GitHub issue has more details about setting up your own secret resolution code: https://github.com/Azure/AppConfiguration-DotnetProvider/issues/209#issuecomment-743427521

Link to the same discussion on GitHub: https://github.com/Azure/AppConfiguration-DotnetProvider/issues/309

Body:
I have an Azure app configuration with 2 keys. Both have key vault references as values. When one of the key-vault secrets is disabled for some reason (because expiration date has passed, not needed for now etc.,), entire configuration loading fails with KeyVault reference exception.
I tried using SetSecretResolver, but it looks like if the registered KV client encounters any exception, secret resolver fallback will not be called. Is there any solution for this issue? Basically, I don't want to stop loading the config, if any or some of the KV secrets are disabled.
BTW, I tried setting the "Options: true" to suppress the exception throwing, but that did not load the config.

app config Keys:-

abc:def:key1 - has a valid key vault secret
abc:def:key2 - has a disabled key vault secret.

code:-

public IConfiguration AzureAppConfig { get; set; }
public IConfigurationRefresher AzureAppConfigRefresher { get; set; }

builder.AddAzureAppConfiguration(options =>
                {
                    options.Connect(new Uri("uri"), credential)
                        .Select("abc:def:*")
                        .ConfigureKeyVault(kvOptions =>
                        {
                            kvOptions.SetCredential(credential);
                        })
                    .ConfigureRefresh(refresh =>
                    {
                        refresh.Register("abc:def:key1")
                            .SetCacheExpiration(TimeSpan.FromMinutes(30));
                    });
                    AzureAppConfigRefresher = options.GetRefresher();
                });

AzureAppConfig = builder.Build();

Thanks in advance for any help.


问:
Parse Apple Plist files in android
I have onle application in which i have to parse plist files. I dont found any usefull link for that I have following plist file.

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com
 /DTDs/PropertyList-1.0.dtd">

<plist version="1.0">

<dict>
<key>About The Firm</key>
<array>
    <string>Firm Details</string>
    <string>Verdicts</string>
    <string>Read Our Disclaimer</string>
</array>
<key>Attorneys</key>
<array>
    <string>Jerrold S. Parker</string>
    <string>Herbert L. Waichman</string>
    <string>Andres F. Alonso</string>
    <string>Jordan L. Chaikin</string>
    <string>Raymond C. Silverman</string>
    <string>Brett A. Zekowski</string>
    <string>Fred R. Rosenthal</string>
    <string>David B. Krangle</string>
    <string>Douglas A. Kugal</string>
    <string>Melanie H. Muhlstock</string>
    <string>Herman Badillo</string>
    <string>Jay L. T. Breakstone</string>
    <string>Michael R. Bluman</string>
    <string>Daniel C. Burke</string>
    <string>Peter J. Cambs</string>
    <string>Gary P. Falkowitz</string>
    <string>April S. Goodwin</string>
    <string>Michael Hugo</string>
    <string>James G. Kapralos</string>
    <string>Christina J. Kazepis</string>
    <string>Brett R. Leitner</string>
    <string>Matthew J. McCauley</string>
    <string>Allan M. Silverstein</string>
    <string>Lauren B. Sutton</string>
    <string>Justin Varughese</string>
</array>
<key>Disclaimer</key>
<array>
    <string>Read Our Disclaimer</string>
</array>
<key>Practice Areas</key>
<array>
    <string>Auto Accidents</string>
    <string>Defective Drugs</string>
    <string>Defective Medical Device</string>
    <string>Nursing Home Abuse</string>
</array>
</code>```

Please give me some solution for that

答: Use SAXParser to parse it as xml. You should be able to find good tutorials for that.</p>

ContentLicense: CC BY-SA 3.0

Title: Parse Apple Plist files in android

Body:
I have onle application in which i have to parse plist files. I dont found any usefull link for that I have following plist file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com
 /DTDs/PropertyList-1.0.dtd">

<plist version="1.0">

<dict>
<key>About The Firm</key>
<array>
    <string>Firm Details</string>
    <string>Verdicts</string>
    <string>Read Our Disclaimer</string>
</array>
<key>Attorneys</key>
<array>
    <string>Jerrold S. Parker</string>
    <string>Herbert L. Waichman</string>
    <string>Andres F. Alonso</string>
    <string>Jordan L. Chaikin</string>
    <string>Raymond C. Silverman</string>
    <string>Brett A. Zekowski</string>
    <string>Fred R. Rosenthal</string>
    <string>David B. Krangle</string>
    <string>Douglas A. Kugal</string>
    <string>Melanie H. Muhlstock</string>
    <string>Herman Badillo</string>
    <string>Jay L. T. Breakstone</string>
    <string>Michael R. Bluman</string>
    <string>Daniel C. Burke</string>
    <string>Peter J. Cambs</string>
    <string>Gary P. Falkowitz</string>
    <string>April S. Goodwin</string>
    <string>Michael Hugo</string>
    <string>James G. Kapralos</string>
    <string>Christina J. Kazepis</string>
    <string>Brett R. Leitner</string>
    <string>Matthew J. McCauley</string>
    <string>Allan M. Silverstein</string>
    <string>Lauren B. Sutton</string>
    <string>Justin Varughese</string>
</array>
<key>Disclaimer</key>
<array>
    <string>Read Our Disclaimer</string>
</array>
<key>Practice Areas</key>
<array>
    <string>Auto Accidents</string>
    <string>Defective Drugs</string>
    <string>Defective Medical Device</string>
    <string>Nursing Home Abuse</string>
</array>

Please give me some solution for that


问:
Detect current device with UI_USER_INTERFACE_IDIOM() in Swift
What is the equivalent of UI_USER_INTERFACE_IDIOM() in Swift to detect between iPhone and iPad?

I get an Use of unresolved identifier error when compiling in Swift.

答:
You can use the new way on Swift 5:</p>
```<code>switch traitCollection.userInterfaceIdiom {

    case .unspecified:
        // do something
    case .phone:
        // do something
    case .pad:
        // do something
    case .tv:
        // do something
    case .carPlay:
        // do something
    case .mac:
        // do something
    @unknown default:
        // do something
}
</code>```

Body:
You can use the new way on Swift 5:

switch traitCollection.userInterfaceIdiom {

    case .unspecified:
        // do something
    case .phone:
        // do something
    case .pad:
        // do something
    case .tv:
        // do something
    case .carPlay:
        // do something
    case .mac:
        // do something
    @unknown default:
        // do something
}


问:
An abstract DAO method must be annotated with one and only one of the following annotations: Insert,Delete,Query,Update,RawQuery
```<code>@Dao
interface ArticleDAO {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun upsert(article: Article) : Long

    @Query("SELECT * FROM articles")
    fun getAllArticles(): LiveData<List<Article>>

    @DELETE
    suspend fun deleteArticles(article: Article)
}
</code>```

Hi! On running this code, I get the following error:
An abstract DAO method must be annotated with one and only one of the following annotations: Insert,Delete,Query,Update,RawQuery
Please help me with this

答:
@JesúsBarrera from the comments is correct. check your imports. the annotation should be like this

```<code>@Delete
</code>```

android studio will probably import this

```<code>import androidx.room.*
</code>```

if not already present

Body:
@Dao
interface ArticleDAO {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun upsert(article: Article) : Long

    @Query("SELECT * FROM articles")
    fun getAllArticles(): LiveData<List
>

    @DELETE
    suspend fun deleteArticles(article: Article)
}

Hi! On running this code, I get the following error:
An abstract DAO method must be annotated with one and only one of the following annotations: Insert,Delete,Query,Update,RawQuery
Please help me with this

Body:
@JesúsBarrera from the comments is correct. check your imports. the annotation should be like this

@Delete

android studio will probably import this

import androidx.room.*

if not already present


问:
Dotnet CLI Hot Reload: always restart app on rude edits?
When using Hot Reload in the .NET CLI...

```<code>$ dotnet watch
watch : Hot reload enabled. For a list of supported edits, see https://aka.ms/dotnet/hot-reload. Press "Ctrl + R" to restart.
watch : Building...
  ...
watch : Started

</code>```

... any rude edit leads to the following prompt:

```<code>watch : Unable to apply hot reload because of a rude edit.
watch : Do you want to restart your app - Yes (y) / No (n) / Always (a) / Never (v)?
</code>```

Is there any way to tell the CLI to default to "Always"? Something like dotnet watch --always-restart?

(asking because I'd like to run dotnet watch in a container)

答:
As it turns out, yes!

```<code>$ export DOTNET_WATCH_RESTART_ON_RUDE_EDIT=1
$ dotnet watch
</code>```

(.NET 6.0.2+)

Body:
When using Hot Reload in the .NET CLI...

$ dotnet watch
watch : Hot reload enabled. For a list of supported edits, see https://aka.ms/dotnet/hot-reload. Press "Ctrl + R" to restart.
watch : Building...
  ...
watch : Started

... any rude edit leads to the following prompt:

watch : Unable to apply hot reload because of a rude edit.
watch : Do you want to restart your app - Yes (y) / No (n) / Always (a) / Never (v)?

Is there any way to tell the CLI to default to "Always"? Something like dotnet watch --always-restart?

(asking because I'd like to run dotnet watch in a container)

Body:
As it turns out, yes!

$ export DOTNET_WATCH_RESTART_ON_RUDE_EDIT=1
$ dotnet watch

(.NET 6.0.2+)


问:
Why SQL Sink TableName = "DefaultTableName" and not the value supplied in the parameter
I am moving data from the Dataverse/Data Lake into an Azure SQL Server.  I have a parameter defined for the TableName.

The Source uses the parameter to read data from the required table, but not the Sink.

Here my parameters are defined and are being passed down from the Pipeline.

This is the Sink

And the Sink Settings using the Dataset Parameter

I get a table created called [landing].[DefaultTableName] no matter what I set as my TableName parameter

答:
Here is a working example,

DataFlow with dynamic SQL sink:

Parameterized table name in sink Dataset:

Pipeline Setup and new parameter value input:

Execute:

Conclusions:

What you are trying to do is pass the Dataflow parameter value to Sink dataset parameter, which is not possible. You can only input values to Dataflow parameters from pipeline and not the other way around. And you cannot refer to DataFlow parameter in Dataset cause all are created in different scopes.

DataFlow Parameter:


问:
Generate a report using jasperReport contain no available data
I'am using JasperReport and ireport 4.0

I want to generate a report contain the word "no available data for this request" When the request do not return data.

How can I do that?

than you

答: Rym, you can set "When No Data" template property to "No Data Section" value (in IReport). And then add Static Text (to this new band) with "no available data for this request" text, for example</p>


问:
IOS swift5 UIController call uitableview function problem. Please assist
I have a UIController class and a Tableview class. I would like to include tableview inside uicontroller. But i cannot access tableview inside functions (even static or public). how can i access tableview function from uicontroller?

Million thanks. Struggling with this problem long

```<code>import Foundation
import UIKit

class UIController: UIViewController {
private var tableView: UITableView = RegDropdownMenu(identifier: RegStepTwoIndentifier.regStepTwoTable)

init(identifier: String) {

    super.init()

    view.addSubview(tableView)

    // Cannot call the func
    tableView.testingFunc()
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}

class TableView: UITableView {
private var identifier: String

init(identifier: String) {
    self.identifier = identifier
    super.init(frame: .zero, style: .plain)
    configTable()
}

private func configTable() {
    self.delegate = self
    self.dataSource = self
    self.translatesAutoresizingMaskIntoConstraints = false
    self.register(CellClass.self, forCellReuseIdentifier: identifier)
    self.allowsSelection = true
    self.separatorStyle = .none
    self.layer.masksToBounds = true
    self.backgroundColor = .white
    self.layer.borderColor = Styles.borderColor.cgColor
    self.layer.borderWidth = Styles.borderWidth
}

func testingFunc() {
    print("123")
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}
</code>```

答:
You have created a custom UITableView subclass called TableView

This is the line of code that does this class TableView: UITableView

However, in your ViewController you are creating a generic UITableView

private var tableView: UITableView

This should be changed to

private var tableView: TableView which is the name of the custom UITableView class you created.

After this, tableView.testingFunc() should work.

Body:
I have a UIController class and a Tableview class. I would like to include tableview inside uicontroller. But i cannot access tableview inside functions (even static or public). how can i access tableview function from uicontroller?

Million thanks. Struggling with this problem long

import Foundation
import UIKit

class UIController: UIViewController {
private var tableView: UITableView = RegDropdownMenu(identifier: RegStepTwoIndentifier.regStepTwoTable)

init(identifier: String) {

    super.init()

    view.addSubview(tableView)

    // Cannot call the func
    tableView.testingFunc()
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}

class TableView: UITableView {
private var identifier: String

init(identifier: String) {
    self.identifier = identifier
    super.init(frame: .zero, style: .plain)
    configTable()
}

private func configTable() {
    self.delegate = self
    self.dataSource = self
    self.translatesAutoresizingMaskIntoConstraints = false
    self.register(CellClass.self, forCellReuseIdentifier: identifier)
    self.allowsSelection = true
    self.separatorStyle = .none
    self.layer.masksToBounds = true
    self.backgroundColor = .white
    self.layer.borderColor = Styles.borderColor.cgColor
    self.layer.borderWidth = Styles.borderWidth
}

func testingFunc() {
    print("123")
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}


问:
Unnecessary re-renders on react-leaflet choropleth map
First of all, I'm new to React and the whole Frontend thing, so this is probably something obvious.

I'm writing a simple choropleth map in React using react-leaflet, but I'm facing some performance issues.

My case is very similar to the one you can see here:

https://codepen.io/hazmi/pen/JjoyONo

If you add a console.log statement to the style method and check the console you can see that the style method is called for every feature on the map on every mouseover or mouseout event.

In my case it is even worse, as style is called twice for every feature on the map.

Unfortunately, this is a huge performance issue on bigger maps and also causes all kinds of side effects.

I assume the style method is called because the <GeoJSON> layer is re-rendered all the time because of the state change caused by the 2 mouse event handlers setting the selected variable. My case is very similar, just the component structure is a bit more complex.

More components rely on the value of the selected variable, so I need that to be set on hover and reset on mouseout.

```<code>const colors = [ /* constant array */ ];

function Map() {

    const [hoveredCountry, setHoveredCountry] = useState(null);
    const [statsData, setStatsData] = useState(null);

...

    const highlightFeature = e => {
        let layer = e.target;
        setHoveredCountry({ stats: statsData[layer.feature.properties.iso_a3] });
    }

    const resetHighlight = e => {
        setHoveredCountry(null);
    }

    const onEachFeature = (feature, layer) => {
        layer.on({
            mouseover: highlightFeature,
            mouseout: resetHighlight
        });
    }

    const style = feature => { /* calculate and return style object */ }

...

    return (
        <MapContainer center={[40, 0]}>
            <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" attribution='© <a href="https://www.openstreetmap.org/copyright" target="blank">OpenStreetMap</a> contributors' />
            <ZoomControl position='bottomleft' />
            <GeoJSON data={countries} style={style} onEachFeature={onEachFeature} ref={geoJsonLayer}>
                <InfoTooltip scope={dataScope} hoveredCountry={hoveredCountry} />
            </GeoJSON>
            <InfoBox data={selectedCountry} scope={dataScope} open={infoBoxOpen} closeHandler={handleInfoBoxClosed} />
            <MapControls options={dataScopes} value={dataScope} changeHandler={handleDataScopeChange} />
           <Legend scope={dataScope} colors={colors} hoveredCountry={hoveredCountry} />
        </MapContainer>
    );
}
</code>```

In my case shown above, the Legend and InfoTooltip both depend on the hoveredCountry state variable similarly how the tooltip uses the selected state variable in the CodePen example.

How can I avoid these unnecessary re-renders? Is this the issue to begin with?

答:
I assume the style method is called because the <GeoJSON> layer is re-rendered all the time because of the state change caused by the 2 mouse event handlers setting the selected variable.

You are on the right track indeed.

What happens is that React thinks it has to rerender that component because one of its props has changed:

```<code><GeoJSON data={countries} style={style} onEachFeature={onEachFeature}>
</code>```

Your countries variable (actually data in your CodePen) and style function are defined outside of your App component, so they are fine.

On the other hand, your onEachFeature function is declared in the body of your component. So everytime React reevaluates the component, and in particular whenever one of its state is changed, it reruns the App function, which creates a new onEachFeature function (which does exactly the same thing, but is is a different reference). Hence the <GeoJSON> component is rerendered.

And you had to keep it in there because it uses your state setter function.

A solution is simply to use the useCallback hook, which is made for such purpose: avoid a reference change whenever the component is reevaluated:

This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders

In your case:

```<code>const onEachFeature = useCallback((feature, layer) => {
    layer.on({
        mouseover: highlightFeature,
        mouseout: resetHighlight
    });
}, []);
</code>```

Note: inlining highlightFeature and resetHighlight would also make it clearer that you need them only when building the callback.

Body:
First of all, I'm new to React and the whole Frontend thing, so this is probably something obvious.

I'm writing a simple choropleth map in React using react-leaflet, but I'm facing some performance issues.

My case is very similar to the one you can see here:

https://codepen.io/hazmi/pen/JjoyONo

If you add a console.log statement to the style method and check the console you can see that the style method is called for every feature on the map on every mouseover or mouseout event.

In my case it is even worse, as style is called twice for every feature on the map.

Unfortunately, this is a huge performance issue on bigger maps and also causes all kinds of side effects.

I assume the style method is called because the <GeoJSON> layer is re-rendered all the time because of the state change caused by the 2 mouse event handlers setting the selected variable. My case is very similar, just the component structure is a bit more complex.

More components rely on the value of the selected variable, so I need that to be set on hover and reset on mouseout.

const colors = [ /* constant array */ ];

function Map() {

    const [hoveredCountry, setHoveredCountry] = useState(null);
    const [statsData, setStatsData] = useState(null);

...

    const highlightFeature = e => {
        let layer = e.target;
        setHoveredCountry({ stats: statsData[layer.feature.properties.iso_a3] });
    }

    const resetHighlight = e => {
        setHoveredCountry(null);
    }

    const onEachFeature = (feature, layer) => {
        layer.on({
            mouseover: highlightFeature,
            mouseout: resetHighlight
        });
    }

    const style = feature => { /* calculate and return style object */ }

...

    return (
        <MapContainer center={[40, 0]}>
            <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" attribution='© OpenStreetMap contributors' />
            <ZoomControl position='bottomleft' />
            <GeoJSON data={countries} style={style} onEachFeature={onEachFeature} ref={geoJsonLayer}>
                <InfoTooltip scope={dataScope} hoveredCountry={hoveredCountry} />
            </GeoJSON>
            <InfoBox data={selectedCountry} scope={dataScope} open={infoBoxOpen} closeHandler={handleInfoBoxClosed} />
            <MapControls options={dataScopes} value={dataScope} changeHandler={handleDataScopeChange} />
           <Legend scope={dataScope} colors={colors} hoveredCountry={hoveredCountry} />
        </MapContainer>
    );
}

In my case shown above, the Legend and InfoTooltip both depend on the hoveredCountry state variable similarly how the tooltip uses the selected state variable in the CodePen example.

How can I avoid these unnecessary re-renders? Is this the issue to begin with?

Body:
I assume the style method is called because the <GeoJSON> layer is re-rendered all the time because of the state change caused by the 2 mouse event handlers setting the selected variable.

You are on the right track indeed.

What happens is that React thinks it has to rerender that component because one of its props has changed:

<GeoJSON data={countries} style={style} onEachFeature={onEachFeature}>

Your countries variable (actually data in your CodePen) and style function are defined outside of your App component, so they are fine.

On the other hand, your onEachFeature function is declared in the body of your component. So everytime React reevaluates the component, and in particular whenever one of its state is changed, it reruns the App function, which creates a new onEachFeature function (which does exactly the same thing, but is is a different reference). Hence the <GeoJSON> component is rerendered.

And you had to keep it in there because it uses your state setter function.

A solution is simply to use the useCallback hook, which is made for such purpose: avoid a reference change whenever the component is reevaluated:

This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders

In your case:

const onEachFeature = useCallback((feature, layer) => {
    layer.on({
        mouseover: highlightFeature,
        mouseout: resetHighlight
    });
}, []);

Note: inlining highlightFeature and resetHighlight would also make it clearer that you need them only when building the callback.


问:
Adding a new column next to each existing column that matches a certain column name pattern in R / tidyverse
In a dataframe I want to add a new column next each column whose name matches a certain pattern, for example whose name starts with "ip_" and is followed by a number. The name of the new columns should follow the pattern "newCol_" suffixed by that number again. The values of the new columns should be NA's.

So this dataframe:

should be transformed to that dataframe:

A tidiverse solution with use of regex is much appreciated!

Sample data:

```<code>df <- data.frame(
  ID = c("1", "2"),
  ip_1 = c(2,3),
  ip_9 = c(5,7),
  ip_39 = c(11,13),
  in_1 = c("B", "D"),
  in_2 = c("A", "H"),
  in_3 = c("D", "A")
)
</code>```

答:
To get the columns is easy with across -

```<code>library(dplyr)

df %>%
  mutate(across(starts_with('ip'), ~NA, .names = '{sub("ip", "newCol", .col)}'))

#  ID ip_1 ip_9 ip_39 in_1 in_2 in_3 newCol_1 newCol_9 newCol_39
#1  1    2    5    11    B    A    D       NA       NA        NA
#2  2    3    7    13    D    H    A       NA       NA        NA
</code>```

To get the columns in required order -

```<code>library(dplyr)

df %>%
  mutate(across(starts_with('ip'), ~NA, .names = '{sub("ip", "newCol", .col)}')) %>%
  select(ID, starts_with('in'),
        order(suppressWarnings(readr::parse_number(names(.))))) %>%
  select(ID, ip_1:newCol_39, everything())

#  ID ip_1 newCol_1 ip_9 newCol_9 ip_39 newCol_39 in_1 in_2 in_3
#1  1    2       NA    5       NA    11        NA    B    A    D
#2  2    3       NA    7       NA    13        NA    D    H    A
</code>```

Body:
In a dataframe I want to add a new column next each column whose name matches a certain pattern, for example whose name starts with "ip_" and is followed by a number. The name of the new columns should follow the pattern "newCol_" suffixed by that number again. The values of the new columns should be NA's.

So this dataframe:

should be transformed to that dataframe:

A tidiverse solution with use of regex is much appreciated!

Sample data:

df <- data.frame(
  ID = c("1", "2"),
  ip_1 = c(2,3),
  ip_9 = c(5,7),
  ip_39 = c(11,13),
  in_1 = c("B", "D"),
  in_2 = c("A", "H"),
  in_3 = c("D", "A")
)

Body:
To get the columns is easy with across -

library(dplyr)

df %>%
  mutate(across(starts_with('ip'), ~NA, .names = '{sub("ip", "newCol", .col)}'))

#  ID ip_1 ip_9 ip_39 in_1 in_2 in_3 newCol_1 newCol_9 newCol_39
#1  1    2    5    11    B    A    D       NA       NA        NA
#2  2    3    7    13    D    H    A       NA       NA        NA

To get the columns in required order -

library(dplyr)

df %>%
  mutate(across(starts_with('ip'), ~NA, .names = '{sub("ip", "newCol", .col)}')) %>%
  select(ID, starts_with('in'),
        order(suppressWarnings(readr::parse_number(names(.))))) %>%
  select(ID, ip_1:newCol_39, everything())

#  ID ip_1 newCol_1 ip_9 newCol_9 ip_39 newCol_39 in_1 in_2 in_3
#1  1    2       NA    5       NA    11        NA    B    A    D
#2  2    3       NA    7       NA    13        NA    D    H    A


问:
How do I pass my value in root of css in reactjs?
I have a problem wherein I can't pass my value of "seconds" for the animation...
Supposingly I have something like this in my css

```<code>:root {
  --speed: 1s;
}

animation: rotate var(--speed) ease-in-out infinite;
</code>```

And that I want to pass my inputs in reactjs so that it will change the value of duration

```<code>const handleChangeRevolution = e => {
    document.documentElement.style.setProperty("--speed",e.target.value)
}
</code>```

I did something like this wherein I input my numbers for duration of the speed

```<code><input
  type="text"
  name="revolve"
  value={revolve}
  onChange={e => handleChangeRevolution(e)} />
</code>```

Any idea guys? I don't wanna change the code here...I just wanna fix the problem how to pass it. Thank you for helping.

答:
Here is the answer, thank you guys. I just need to add the 's' I forgot.

```<code>const handleChangeRevolution = e => {
    document.documentElement.style.setProperty("--speed", e.target.value + 's')
}
</code>```

Body:
I have a problem wherein I can't pass my value of "seconds" for the animation...
Supposingly I have something like this in my css

:root {
  --speed: 1s;
}

animation: rotate var(--speed) ease-in-out infinite;

And that I want to pass my inputs in reactjs so that it will change the value of duration

const handleChangeRevolution = e => {
    document.documentElement.style.setProperty("--speed",e.target.value)
}

I did something like this wherein I input my numbers for duration of the speed

<input
  type="text"
  name="revolve"
  value={revolve}
  onChange={e => handleChangeRevolution(e)} />

Any idea guys? I don't wanna change the code here...I just wanna fix the problem how to pass it. Thank you for helping.

Body:
Here is the answer, thank you guys. I just need to add the 's' I forgot.

const handleChangeRevolution = e => {
    document.documentElement.style.setProperty("--speed", e.target.value + 's')
}


问:
Having trouble parsing the data recieved from requests.get() using requests in Python
Here's what i have, it's a very basic set of code

```<code>import requests
import json

response = requests.get("https://api.openbrewerydb.org/breweries?by_city=cincinnati")
data  = response.json()
</code>```

When i check the type of 'data' it says that it's a list, so i tried

```<code>for point in data:
    print(point.name)
</code>```

However, that gives me the error

```<code>AttributeError: 'dict' object has no attribute 'name'
</code>```

I thought it was a list? Not a dictionary. And when i directly do print(data), it does indeed show that each object within the list of data has a name attribute.

I'm sure this is some stupid mistake, but what am i doing wrong?

答:
data is a list of dicts.
The elements you're iterating over, thusly are dicts and you cannot access them by attribute access. You need to acces their keys by their respective names.

for point in data:
    print(point['name'])
```

Body:
Here's what i have, it's a very basic set of code

import requests
import json

response = requests.get("https://api.openbrewerydb.org/breweries?by_city=cincinnati")
data  = response.json()

When i check the type of 'data' it says that it's a list, so i tried

for point in data:
    print(point.name)

However, that gives me the error

AttributeError: 'dict' object has no attribute 'name'

I thought it was a list? Not a dictionary. And when i directly do print(data), it does indeed show that each object within the list of data has a name attribute.

I'm sure this is some stupid mistake, but what am i doing wrong?


问:
How do I binarize a numpy array to indicate the max value of each row?
If I have a numpy array, how do I convert so that the value of each element is zero, except for the max element of each row, which should be 1, without a brute-force looping solution? For example, given:

```<code>array([[1, 2, 3, 4],
       [2, 3, 4, 1],
       [3, 4, 1, 2],
       [4, 1, 2, 3]])
</code>```

How do I produce:

```<code>array([[0,0,0,1],
       [0,0,1,0],
       [0,1,0,0],
       [1,0,0,0]])
</code>```

Note: For my actual case, I won't know the actual values in the array. All I will know is that the values are non-negative.

Body:
If I have a numpy array, how do I convert so that the value of each element is zero, except for the max element of each row, which should be 1, without a brute-force looping solution? For example, given:

array([[1, 2, 3, 4],
       [2, 3, 4, 1],
       [3, 4, 1, 2],
       [4, 1, 2, 3]])

How do I produce:

array([[0,0,0,1],
       [0,0,1,0],
       [0,1,0,0],
       [1,0,0,0]])

Note: For my actual case, I won't know the actual values in the array. All I will know is that the values are non-negative.

Body:
Try the following code:

import numpy as np
ar = np.array([[1, 2, 3, 4],
               [2, 3, 4, 1],
               [3, 4, 1, 2],
               [4, 1, 2, 3]])
ar = (ar == ar.max()) * 1
print(ar)


问:
Python/Json:Expecting property name enclosed in double quotes
I've been trying to figure out a good way to load JSON objects in Python.
I send this json data:

```<code>{'http://example.org/about': {'http://purl.org/dc/terms/title': [{'type': 'literal', 'value': "Anna's Homepage"}]}}
</code>```

to the backend where it will be received as a string then I used json.loads(data) to parse it.

But each time I got the same exception :

```<code>ValueError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
</code>```

I googled it but nothing seems to work besides this solution json.loads(json.dumps(data)) which personally seems for me not that efficient since it accept any kind of data even the ones that are not in json format.

Any suggestions will be much appreciated.

答:
If you want to convert a json string with single quotes to python dict use ast.literaleval()

>>> import ast
>>> payload = "{'hello': 'world'}"
>>> ast.literal_eval(payload)
{'hello': 'world'}
>>> type(ast.literal_eval(payload))
<class 'dict'>
```

This will convert the payload to a python dict.

Body:
I've been trying to figure out a good way to load JSON objects in Python.
I send this json data:

{'http://example.org/about': {'http://purl.org/dc/terms/title': [{'type': 'literal', 'value': "Anna's Homepage"}]}}

to the backend where it will be received as a string then I used json.loads(data) to parse it.

But each time I got the same exception :

ValueError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

I googled it but nothing seems to work besides this solution json.loads(json.dumps(data)) which personally seems for me not that efficient since it accept any kind of data even the ones that are not in json format.

Any suggestions will be much appreciated.

Body:
If you want to convert a json string with single quotes to python dict use ast.literaleval()

>>> import ast
>>> payload = "{'hello': 'world'}"
>>> ast.literal_eval(payload)
{'hello': 'world'}
>>> type(ast.literal_eval(payload))
<class 'dict'>

This will convert the payload to a python dict.


问:
How does static field initialization work in C#?
Should static field initialization be completed before constructor is called?

The following program provides output that seems incorrect to me.

```<code>new A()
_A == null
static A()
new A()
_A == A
</code>```

The code:

```<code>public class A
{
    public static string _A = (new A()).I();

    public A()
    {
        Console.WriteLine("new A()");
        if (_A == null)
            Console.WriteLine("_A == null");
        else
            Console.WriteLine("_A == " + _A);
    }

    static A()
    {
        Console.WriteLine("static A()");
    }

    public string I()
    {
        return "A";
    }
}

class Program
{
    static void Main(string[] args)
    {
       var a = new A();
    }
}
</code>```

答:
It seems the compiler is doing the expected.

1st - All static code is executed (fields first, then static constructor) in the class:

```<code>public static string _A = (new A()).I();

// and

static A()
{
    Console.WriteLine("static A()");
}
</code>```

2nd - Class constructor is called:

```<code>public A()
{
    Console.WriteLine("new A()");
    if (_A == null)
        Console.WriteLine("_A == null");
    else
        Console.WriteLine("_A == " + _A);
}
</code>```

You ask why this is possible. Well, in my opinion, an instance doesn't absolutely require that all class variables are initialized upon creation. It just requires they must exist. I think this particular case supports this thought because an instance is created before all static initialization is done.

ContentLicense: CC BY-SA 2.5

Body:
Should static field initialization be completed before constructor is called?

The following program provides output that seems incorrect to me.

new A()
_A == null
static A()
new A()
_A == A

The code:

public class A
{
    public static string _A = (new A()).I();

    public A()
    {
        Console.WriteLine("new A()");
        if (_A == null)
            Console.WriteLine("_A == null");
        else
            Console.WriteLine("_A == " + _A);
    }

    static A()
    {
        Console.WriteLine("static A()");
    }

    public string I()
    {
        return "A";
    }
}

class Program
{
    static void Main(string[] args)
    {
       var a = new A();
    }
}

Body:
It seems the compiler is doing the expected.

1st - All static code is executed (fields first, then static constructor) in the class:

public static string _A = (new A()).I();

// and

static A()
{
    Console.WriteLine("static A()");
}

2nd - Class constructor is called:

public A()
{
    Console.WriteLine("new A()");
    if (_A == null)
        Console.WriteLine("_A == null");
    else
        Console.WriteLine("_A == " + _A);
}

You ask why this is possible. Well, in my opinion, an instance doesn't absolutely require that all class variables are initialized upon creation. It just requires they must exist. I think this particular case supports this thought because an instance is created before all static initialization is done.

OwnerDisplayName: bruno conde

LastEditorDisplayName: bruno conde


问:
Can I selectively (force) inline a function?
In the book Clean Code (and a couple of others I have come across and read) it is suggested to keep the functions small and break them up if they become large. It also suggests that functions should do one thing and one thing only.

In Optimizing software in C++ Agner Fog states that he does not like the rule of breaking up a function just because it crosses a certain threshold of a number of lines. He states that this results in unnecessary jumps which degrade performance.

First off, I understand that it will not matter if the code I am working on is not in a tight loop and that the functions are heavy so that the time it takes to call them is dwarfed by the time the code in the function takes to execute. But let's assume that I am working with functions that are, most of the time, used by other objects/functions and are performing relatively trivial tasks. These functions follow the suggestions listed in the first paragraph (that is, perform one single function and are small/comprehensible). Then I start programming a performance critical function that utilizes these other functions in a tight loop and is essentially a frame function. Lastly, assume that in-lining them has a benefit for the performance critical function but no benefit whatsoever to any other function (yes, I have profiled this, albeit with a lot of copying and pasting which I want to avoid).

Immediately, one can say that tag the function inline and let the compiler choose. But what if I don't want all those functions to be in a `.inl file or exposed in the header? In my current situation, the performance critical functions and the other functions it uses are all in the same source file.

To sum it up, can I selectively (force) inline a function(s) for a single function so that the end code behaves like it is one big function instead of several calls to other functions.

答: No, inline is a recommendation to the compiler ; it does not force it to do anything. Also, if you're working with MSVC++, note that __forceinline is a misnomer as well ; it's just a stronger recommendation than inline.


问:
Unable to copy docker image in JFrog Artifactory from one repo to a target repo
We have an Artifactory server to host our Docker images. I am trying to effectively re-tag one of my Docker images using the JFrog API. I know I could do this with a simple docker tag and docker push, but wanted to see how to do this more directly with the Artifactory API. Unfortunately I am running into a snag. Here's the API call I'm trying to make:

```<code>curl -X POST --user 'my@user.com:MyAPIKey' -H "Content-Type: application/json" --data \
  '{"targetRepo": "docker-local", "dockerRepository": "docker-local", "tag": "my/docker/image/original", "targetTag": "my/docker/image/new", "copy": true}' \
  https://www.myartifactoryserver.com/api/docker/docker-local/v2/promote
</code>```

But this call returns the following error:

```<code>{
  "errors" : [ {
    "status" : 400,
    "message" : "'targetTag' tag value is invalid."
  } ]
}
</code>```

I'm not sure what I'm doing wrong here, especially since I am able to perform this same copy using the UI. How do I do it with the API?

答:
Dror Bereznitsky's answer is spot on if you want to do simple re-tagging like

    demo-app:1.0.1  demo-app:latest

However, if your tag is path-like, you can, using Artifactory terminology, promote an Image into a different "Repository Path" within the same "Repository" and keep the same "Tag" (version) in both places:

    com.example/stage/demo-app:1.0.1  com.example/release/demo-app:1.0.1

To promote an Image from stage to release like this:

execute POST request with following body:

```<code>POST /api/docker/devops-docker-local/v2/promote

{
    "repository"             : "devops-docker-local",          // Source Repository
    "dockerRepository"       : "com.example/stage/demo-app",   // Source Path
    "tag"                    : "1.0.1",                        // Source Tag

    "targetRepo"             : "devops-docker-local",          // Target Repository
    "targetDockerRepository" : "com.example/release/demo-app", // Target Path
    "targetTag"              : "1.0.1",                        // Target Tag

    "copy": true
}
</code>```

The API was tested and screenshot taken on with Artifactory EnterpriseX license 7.33.8 rev 73308900

Body:
We have an Artifactory server to host our Docker images. I am trying to effectively re-tag one of my Docker images using the JFrog API. I know I could do this with a simple docker tag and docker push, but wanted to see how to do this more directly with the Artifactory API. Unfortunately I am running into a snag. Here's the API call I'm trying to make:

curl -X POST --user 'my@user.com:MyAPIKey' -H "Content-Type: application/json" --data \
  '{"targetRepo": "docker-local", "dockerRepository": "docker-local", "tag": "my/docker/image/original", "targetTag": "my/docker/image/new", "copy": true}' \
  https://www.myartifactoryserver.com/api/docker/docker-local/v2/promote

But this call returns the following error:

{
  "errors" : [ {
    "status" : 400,
    "message" : "'targetTag' tag value is invalid."
  } ]
}

I'm not sure what I'm doing wrong here, especially since I am able to perform this same copy using the UI. How do I do it with the API?

Body:
Dror Bereznitsky's answer is spot on if you want to do simple re-tagging like

    demo-app:1.0.1  demo-app:latest

However, if your tag is path-like, you can, using Artifactory terminology, promote an Image into a different "Repository Path" within the same "Repository" and keep the same "Tag" (version) in both places:

    com.example/stage/demo-app:1.0.1  com.example/release/demo-app:1.0.1

To promote an Image from stage to release like this:

execute POST request with following body:

POST /api/docker/devops-docker-local/v2/promote

{
    "repository"             : "devops-docker-local",          // Source Repository
    "dockerRepository"       : "com.example/stage/demo-app",   // Source Path
    "tag"                    : "1.0.1",                        // Source Tag

    "targetRepo"             : "devops-docker-local",          // Target Repository
    "targetDockerRepository" : "com.example/release/demo-app", // Target Path
    "targetTag"              : "1.0.1",                        // Target Tag

    "copy": true
}

The API was tested and screenshot taken on with Artifactory EnterpriseX license 7.33.8 rev 73308900


问:
Error on Login-Page "Warning: Trying to access array offset on value of type bool"
I am currently making a website for a school project and I am making a user registration system. Currently, the sign-up portion works perfectly with user data going into the MySQL database. However, my login-page seems to be broken. Every time I try to log-in I get the following error:

Warning: Trying to access array offset on value of type bool in D:\XAMPP\htdocs\hennorist\login.php on line 23

Attached is the PHP code in question:

```<code><?php

require_once "config.php";
require_once "session.php";

$error = '';
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {

    $email = trim($_POST['email']);
    $password = trim($_POST['password']);

    //validate if email is empty
    if (empty($email)) {
        $error .= '<p class="error">Please enter email.</p>';
    }

    if (empty($error)) {
        if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
            $query->bind_param('s', $email);
            $query->execute();
            $row = $query->fetch();
            if ($row) {
                if (password_verify($password, $row['password'])) {
                    $_SESSION["userid"] = $row['id'];
                    $_SESSION["user"] = $row;

                    //Redirect user to welcome page
                    header("location: exclusive.php");
                    exit;
                } else {
                    $error .= '<p class="error">The password is not valid.</p>';
                }
            } else {
                $error .= '<p class="error">No user exists with that email address.</p>';
            }
        }
        $query->close();
    }
    //Close connection
    mysqli_close($db);
}
?>
</code>```

答:
Are you forced to work with the PDO driver? as a beginner it will be a little tricky for you but I would suggest you to work with MySQLi instead,

In your included file for connexion (guess config.php) to database make sure your connexion is instancing the PDO class as
$query = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

Then to close connexion use $query = null; instead of mysqli_close($db);

Assume you understood try executing the following code

```<code> <?php

require_once "config.php";
require_once "session.php";

$error = '';
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {

    $email = trim($_POST['email']);
    $password = trim($_POST['password']);

    //validate if email is empty
    if (empty($email)) {
        $error .= '<p class="error">Please enter email.</p>';
    }

    if (empty($error)) {
        if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
            $query->bind_param('s', $email);
            $query->execute();
            $row = $query->fetch(PDO::FETCH_ASSOC);
            if ($row) {
                if (password_verify($password, $row['password'])) {
                    $_SESSION["userid"] = $row['id'];
                    $_SESSION["user"] = $row;

                    //Redirect user to welcome page
                    header("location: exclusive.php");
                    exit;
                } else {
                    $error .= '<p class="error">The password is not valid.</p>';
                }
            } else {
                $error .= '<p class="error">No user exists with that email address.</p>';
            }
        }
    }
    //Close connection
    $query=null;
}
?>
</code>```

Body:
I am currently making a website for a school project and I am making a user registration system. Currently, the sign-up portion works perfectly with user data going into the MySQL database. However, my login-page seems to be broken. Every time I try to log-in I get the following error:

Warning: Trying to access array offset on value of type bool in D:\XAMPP\htdocs\hennorist\login.php on line 23

Attached is the PHP code in question:

<?php

require_once "config.php";
require_once "session.php";

$error = '';
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {

    $email = trim($_POST['email']);
    $password = trim($_POST['password']);

    //validate if email is empty
    if (empty($email)) {
        $error .= '
Please enter email.
';
    }

    if (empty($error)) {
        if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
            $query->bind_param('s', $email);
            $query->execute();
            $row = $query->fetch();
            if ($row) {
                if (password_verify($password, $row['password'])) {
                    $_SESSION["userid"] = $row['id'];
                    $_SESSION["user"] = $row;

                    //Redirect user to welcome page
                    header("location: exclusive.php");
                    exit;
                } else {
                    $error .= '
The password is not valid.
';
                }
            } else {
                $error .= '
No user exists with that email address.
';
            }
        }
        $query->close();
    }
    //Close connection
    mysqli_close($db);
}
?>

Body:
Are you forced to work with the PDO driver? as a beginner it will be a little tricky for you but I would suggest you to work with MySQLi instead,

In your included file for connexion (guess config.php) to database make sure your connexion is instancing the PDO class as
$query = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

Then to close connexion use $query = null; instead of mysqli_close($db);

Assume you understood try executing the following code

 <?php

require_once "config.php";
require_once "session.php";

$error = '';
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {

    $email = trim($_POST['email']);
    $password = trim($_POST['password']);

    //validate if email is empty
    if (empty($email)) {
        $error .= '<p class="error">Please enter email.</p>';
    }

    if (empty($error)) {
        if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
            $query->bind_param('s', $email);
            $query->execute();
            $row = $query->fetch(PDO::FETCH_ASSOC);
            if ($row) {
                if (password_verify($password, $row['password'])) {
                    $_SESSION["userid"] = $row['id'];
                    $_SESSION["user"] = $row;

                    //Redirect user to welcome page
                    header("location: exclusive.php");
                    exit;
                } else {
                    $error .= '<p class="error">The password is not valid.</p>';
                }
            } else {
                $error .= '<p class="error">No user exists with that email address.</p>';
            }
        }
    }
    //Close connection
    $query=null;
}
?>


答:
You can use .max(), and then convert the resulting boolean matrix into a binary matrix using .astype():

import numpy as np

arr = np.array([[1, 2, 3, 4],
[2, 3, 4, 1],
[3, 4, 1, 2],
[4, 1, 2, 3]])

result = (arr == arr.max()).astype(int)

print(result)
```

Title: How do I binarize a numpy array to indicate the max value of each row?


问:
Convert roman number to arabic using javascript
Hi I am trying to convert roman numerals to arabic using javascript. I wrote a code but it is failing.
The rules I am trying to follow are :

if Larger number is before smaller number then addition and if smaller number is before larger number then subtraction.

Along with that I have few other rules as well like 'D','L' and 'V' can't be repeated at all and 'M' can be repeated only twice (Not sure how to implement this, can I use regex for it and how?)

Code :

    function romanToArabic(roman){
        if(roman == null)
            return -1;
            var value;
        for(var i=0;i<roman.length;i++){
            current = char_to_int(roman.charAt(i));
            next = char_to_int(roman.charAt(i+1));
            console.log("Current",current);
            console.log("Next",next);
            if(current >= next){
                value = current + next;
                console.log(value);
            }
            else {
                console.log(value);
                value = next - current;
            }
        }
        return value;
    }

    function char_to_int(character) {
        switch(character){
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
            default: return -1;
        }
    }

    console.log(romanToArabic('IIX'));```

Can somebody help? Would appreciate it!

Added screenshots :

答:
I resolved this exercise like this:</p>
```<code>function arabic(num) {
    let ch;
    let sum = 0;
    for (let i = 0; i < num.length; i++) {
        ch = num[i];
        switch (ch) {
            case 'I':
                if (num[i + 1] === 'V' || num[i + 1] === 'X') {
                    continue;
                }
                sum = sum + 1;
                break;
            case 'V':
                if (num[i - 1] === 'I') {
                    sum = sum + 4;
                    break;
                }
                sum = sum + 5;
                break;
            case 'X':
                if (num[i - 1] === 'I') {
                    sum = sum + 9;
                    break;
                }
                if (num[i + 1] === 'C') {
                    continue;
                }
                sum = sum + 10;
                break;
            case 'L':
                sum = sum + 50;
                break;
            case 'C':
                if (num[i + 1] === 'D' || num[i + 1] === 'M') {
                    continue;
                }
                if (num[i - 1] === 'X') {
                    sum = sum + 90;
                    break;
                }
                sum = sum + 100;
                break;
            case 'D':
                if (num[i - 1] === 'C') {
                    sum = sum + 400;
                    break;
                }
                sum = sum + 500;
                break;
            case 'M':
                if (num[i - 1] === 'C') {
                    sum = sum + 900;
                    break;
                }
                sum = sum + 1000;
                break;
        }
    }
    return sum;
}
</code>```

Body:
Hi I am trying to convert roman numerals to arabic using javascript. I wrote a code but it is failing.
The rules I am trying to follow are :

if Larger number is before smaller number then addition and if smaller number is before larger number then subtraction.

Along with that I have few other rules as well like 'D','L' and 'V' can't be repeated at all and 'M' can be repeated only twice (Not sure how to implement this, can I use regex for it and how?)

Code :

    function romanToArabic(roman){
        if(roman == null)
            return -1;
            var value;
        for(var i=0;i<roman.length;i++){
            current = char_to_int(roman.charAt(i));
            next = char_to_int(roman.charAt(i+1));
            console.log("Current",current);
            console.log("Next",next);
            if(current >= next){
                value = current + next;
                console.log(value);
            }
            else {
                console.log(value);
                value = next - current;
            }
        }
        return value;
    }

    function char_to_int(character) {
        switch(character){
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
            default: return -1;
        }
    }

    console.log(romanToArabic('IIX'));

Can somebody help? Would appreciate it!

Added screenshots :

Body:
I resolved this exercise like this:

function arabic(num) {
    let ch;
    let sum = 0;
    for (let i = 0; i < num.length; i++) {
        ch = num[i];
        switch (ch) {
            case 'I':
                if (num[i + 1] === 'V' || num[i + 1] === 'X') {
                    continue;
                }
                sum = sum + 1;
                break;
            case 'V':
                if (num[i - 1] === 'I') {
                    sum = sum + 4;
                    break;
                }
                sum = sum + 5;
                break;
            case 'X':
                if (num[i - 1] === 'I') {
                    sum = sum + 9;
                    break;
                }
                if (num[i + 1] === 'C') {
                    continue;
                }
                sum = sum + 10;
                break;
            case 'L':
                sum = sum + 50;
                break;
            case 'C':
                if (num[i + 1] === 'D' || num[i + 1] === 'M') {
                    continue;
                }
                if (num[i - 1] === 'X') {
                    sum = sum + 90;
                    break;
                }
                sum = sum + 100;
                break;
            case 'D':
                if (num[i - 1] === 'C') {
                    sum = sum + 400;
                    break;
                }
                sum = sum + 500;
                break;
            case 'M':
                if (num[i - 1] === 'C') {
                    sum = sum + 900;
                    break;
                }
                sum = sum + 1000;
                break;
        }
    }
    return sum;
}


问:
node js 'FILE_NOT_FOUND'
so I am learning node JS and trying to make a discord bot with it and I am having troubles.

module.exports = {
    name: "gabe",
    description: "gabe",
    execute(message, args) {
        var fs = require("fs");
        var files = fs.readdirSync("./gabe/");
        let chosenFile = files[Math.floor(Math.random() * files.length)];
        const fileDirectory = "./gabe/";
        const filePicture = fileDirectory.concat(chosenFile);
        message.channel.send({ files: filePicture });
    },
};
```

I am trying to select a random picture from a folder (./gabe/), but I am getting 'FILE_NOT_FOUND'

In my code I am randomly selecting a .png from the ./gabe/ folder and trying to concat it to make it './gabe/name.png' so that the discord bot can dipsplay it.

答: filePicture is a string. The files argument in message.channel.send requires an array of actual Buffers or such.

Title: node js 'FILE_NOT_FOUND'

Body:
so I am learning node JS and trying to make a discord bot with it and I am having troubles.

module.exports = {
    name: "gabe",
    description: "gabe",
    execute(message, args) {
        var fs = require("fs");
        var files = fs.readdirSync("./gabe/");
        let chosenFile = files[Math.floor(Math.random() * files.length)];
        const fileDirectory = "./gabe/";
        const filePicture = fileDirectory.concat(chosenFile);
        message.channel.send({ files: filePicture });
    },
};

I am trying to select a random picture from a folder (./gabe/), but I am getting 'FILE_NOT_FOUND'

In my code I am randomly selecting a .png from the ./gabe/ folder and trying to concat it to make it './gabe/name.png' so that the discord bot can dipsplay it.


问:
Python Error: DataFrame' object has no attribute 'presence'
I've tried accessing the values of presence but I just keep getting this error: DataFrame' object has no attribute 'presence
Im not exactly sure what im doing wrong.

1.Assign values of presence column to y, note you have to use .values method
2.Drop 'presence' column from data frame,
3.Assign df values to x

**Beginning of code **

```<code>import pandas as pd

columns =    (['age','sex','chestP','ResBP','SrChol','FBS','RestEC','maxHR','EIAng','  oldPeak','slopePeak','MVess','thal'])

 df = pd.read_csv('heart.dat',names=columns,sep = ' ')
 df.head()

import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier

\\ Assign values of ```presence``` column to y, note you have to use .values method

y = df.presence.values    **This is where the error is**

print(y)

\\ Drop 'presence' column from data frame,
df.??
\\ Assign df values to x
x = ??
\\ View shape of x and y
x.shape, y.shape

\\ Use stratify = y and test_size = 0.2 and random_state = 1
xtrain, xtest, ytrain, ytest = ??

\\ Create a KNN model using sklearn library, k=3
knn = ??

\\ Fit the model with the train data
knn.fit(?, ?)

**END**
</code>```

Heart.dat database

Attribute Information:

```<code>  -- 1. age
  -- 2. sex
  -- 3. chest pain type  (4 values)
  -- 4. resting blood pressure
  -- 5. serum cholestoral in mg/dl
  -- 6. fasting blood sugar > 120 mg/dl
  -- 7. resting electrocardiographic results  (values 0,1,2)
  -- 8. maximum heart rate achieved
  -- 9. exercise induced angina
  -- 10. oldpeak = ST depression induced by exercise relative to rest
  -- 11. the slope of the peak exercise ST segment
  -- 12. number of major vessels (0-3) colored by flourosopy
  -- 13.  thal: 3 = normal; 6 = fixed defect; 7 = reversable defect
</code>```

Attributes types

Real: 1,4,5,8,10,12
Ordered:11,
Binary: 2,6,9
Nominal:7,3,13

Variable to be predicted

Absence (1) or presence (2) of heart disease

Cost Matrix

```<code> abse  pres
</code>```

absence   0 1
presence  5 0

where the rows represent the true values and the columns the predicted.

No missing values.

270 observations

答:
Noted that your columns has no "presence" included. Is it possible df has indeed no df.presence attribute as a result ? What is the output of your df.head() ?</p>
```<code>columns =    (['age','sex','chestP','ResBP','SrChol','FBS','RestEC','maxHR','EIAng','  oldPeak','slopePeak','MVess','thal'])
</code>```

Body:
I've tried accessing the values of presence but I just keep getting this error: DataFrame' object has no attribute 'presence
Im not exactly sure what im doing wrong.

1.Assign values of presence column to y, note you have to use .values method
2.Drop 'presence' column from data frame,
3.Assign df values to x

**Beginning of code **

import pandas as pd

columns =    (['age','sex','chestP','ResBP','SrChol','FBS','RestEC','maxHR','EIAng','  oldPeak','slopePeak','MVess','thal'])

 df = pd.read_csv('heart.dat',names=columns,sep = ' ')
 df.head()

import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier

\\ Assign values of ```presence``` column to y, note you have to use .values method

y = df.presence.values    **This is where the error is**

print(y)

\\ Drop 'presence' column from data frame,
df.??
\\ Assign df values to x
x = ??
\\ View shape of x and y
x.shape, y.shape

\\ Use stratify = y and test_size = 0.2 and random_state = 1
xtrain, xtest, ytrain, ytest = ??

\\ Create a KNN model using sklearn library, k=3
knn = ??

\\ Fit the model with the train data
knn.fit(?, ?)

**END**

Heart.dat database

Attribute Information:

  -- 1. age
  -- 2. sex
  -- 3. chest pain type  (4 values)
  -- 4. resting blood pressure
  -- 5. serum cholestoral in mg/dl
  -- 6. fasting blood sugar > 120 mg/dl
  -- 7. resting electrocardiographic results  (values 0,1,2)
  -- 8. maximum heart rate achieved
  -- 9. exercise induced angina
  -- 10. oldpeak = ST depression induced by exercise relative to rest
  -- 11. the slope of the peak exercise ST segment
  -- 12. number of major vessels (0-3) colored by flourosopy
  -- 13.  thal: 3 = normal; 6 = fixed defect; 7 = reversable defect

Attributes types

Real: 1,4,5,8,10,12
Ordered:11,
Binary: 2,6,9
Nominal:7,3,13

Variable to be predicted

Absence (1) or presence (2) of heart disease

Cost Matrix

 abse  pres

absence   0 1
presence  5 0

where the rows represent the true values and the columns the predicted.

No missing values.

270 observations

Body:
Noted that your columns has no "presence" included. Is it possible df has indeed no df.presence attribute as a result ? What is the output of your df.head() ?

columns =    (['age','sex','chestP','ResBP','SrChol','FBS','RestEC','maxHR','EIAng','  oldPeak','slopePeak','MVess','thal'])


问:
How to properly fetch JSON data from an API GET endpoint within a CesiumJS client app
I'm scratching a vanilla CesiumJS demo application from the 1.73 branch.

I left untouched the server.cjs file, but I added one custom client implementation file as Apps/myproject/my.js

As I need to GET some JSON responses from an existing API within that demo application, I tried to import the 'https' module as follows:

const https = require('https');
```
<p>which conducted me to the <code>Uncaught ReferenceError: require is not defined</code> error.</p>
<p>Then I tried the <code>import</code> way:</p>
<pre class="lang-js prettyprint-override"><code>import https;
</code>```

which raised the Uncaught SyntaxError: missing keyword 'from' after import clause error.

(...)

I finally ended up with:

import * as https from 'https';
```

but => Uncaught TypeError: Error resolving module specifier “https”. Relative module specifiers must start with “./”, “../” or “/”. my.js:2:18

I'm running out of ideas for the moment.

How could I successfully and efficiently load and execute an http(s) request to actually get a JSON response from a given API within my custom Cesium app?

答:
You can't use the "require" statement in the Cesiumjs client app.

Use this code snippet.

```<code>// replace it with your api url
const url = "https://www.google.com";

const promise = Cesium.Resource.fetchJson({
    url: url,
    queryParameters: {
    }
});

promise.then((response) =>{
  console.log(response);
}).otherwise(error =>{
  console.log(error);
});

</code>```

Body:
I'm scratching a vanilla CesiumJS demo application from the 1.73 branch.

I left untouched the server.cjs file, but I added one custom client implementation file as Apps/myproject/my.js

As I need to GET some JSON responses from an existing API within that demo application, I tried to import the 'https' module as follows:

const https = require('https');

which conducted me to the Uncaught ReferenceError: require is not defined error.

Then I tried the import way:

import https;

which raised the Uncaught SyntaxError: missing keyword 'from' after import clause error.

(...)

I finally ended up with:

import * as https from 'https';

but => Uncaught TypeError: Error resolving module specifier “https”. Relative module specifiers must start with “./”, “../” or “/”. my.js:2:18

I'm running out of ideas for the moment.

How could I successfully and efficiently load and execute an http(s) request to actually get a JSON response from a given API within my custom Cesium app?

Body:
You can't use the "require" statement in the Cesiumjs client app.

Use this code snippet.

// replace it with your api url
const url = "https://www.google.com";

const promise = Cesium.Resource.fetchJson({
    url: url,
    queryParameters: {
    }
});

promise.then((response) =>{
  console.log(response);
}).otherwise(error =>{
  console.log(error);
});


问:
what are ".js.map" files?
I cloned a repo with a build command that runs webpack and it generates an index.js and index.map.js file. I assume index.js is a minified version of all the code, but what is index.map.js?

答:
The config devtool: 'source-map' in webpack.config.js generated this file when you built it.

Why it is needed?

You can run minified Javascript or transpiled Javascript which is good for performance, but not particularly helpful when debugging. Source maps are a way for modern browsers to take the minified code (js, css) and allow us to read the code in its unminified state in the debugger.

Further reading,

Introduction to JavaScript Source Maps

What is the purpose of source maps?

Title: what are ".js.map" files?


问:
I can't sign in to microsoft using a public Wi-Fi
I have connected to public Wi-Fi that probably blocks me from some sites. I installed a vpn that enables me access those blocked website but I still can't sign in to Microsoft.

I recently installed a new Windows 10, when I downloaded Visual Studio web Installer, it wasn't installing because it couldn't download the files using the public wifi, while with the same wifi, I downloaded and installed Visual Studio onthe previous Windows 10 that I was using.

I dont know if the problem is from the new Windows 10 or the WiFi's firewall rules have been elavated.

答:
You can try installing it with open DNS.
For that, open your CMD, type ipconfig/all
there, look for your ipv4 address, default gateway and subnet and note it.

Now go to your Control Panel -> Network and Sharing -> Select the network/wifi you're connected to,
enter image description here

Click on properties, look for the ipv4 checkbox and click on it, then advance.
There you need to select the option to manually enter ip address. Now add that IP address, default gateway, and subnet mask you noted before.

Add DNS manually and set values to : 8.8.8.8 and 8.8.4.4.

Enjoy surfing the net!


问:
Extract data from an xml attribute with multiple data
I have this XML data with a tag with an attribute that is filled with informations

```<code><Start>
<TestCase>
    <GenericItem html="<table border="1" width="100%"><tr><th rowspan="2">Environment<br/>(Linux)</th><th>Check Execution Time [sec]</th><th>Memory consumption [Mb]</th></tr><tr><th>Baseline - M4A4b<br/>(mean of #run(s))</td><th>Baseline - M4A4b<br/>init / mean / max</td></tr><tr><th>MATLAB</th><td align="center">2.4 (10)</td><td align="center">557 / 573 / 575</td></tr><tr><th>MCR</th><td align="center">2.3699 (10)</td><td align="center">249 / 295 / 297</td></tr></table><font color="green">No numerical differences between 'MATLAB - M4A4b' and 'MCR - M4B2b' found.</font>">
       Results for 'A3 Item - CT07':
      </GenericItem>
</testcase>
</Start>
</code>```

I need help on how to parse in Python and get only the Text Results for 'A3 Item - CT07': and No numerical differences between 'MATLAB - M4A4b' and 'MCR - M4B2b' found. which is inside the HTML attribute.

答:
You have a strange situation where a whole html table is embedded within an attribute of an element in a parent html document....

Having said that, you can try this:

```<code>import lxml.html as lh
generic = """your html above""""

doc = lh.fromstring(generic)

#to get your "results", try either

print(doc.xpath('normalize-space(//genericitem/text())'))

#or

print(doc.xpath('//genericitem/text()')[0].strip())
</code>```

In either case, the output should be

```<code>Results for 'A3 Item - CT07':
</code>```

The other one requires a little more work: first extract the embedded html, then parse it and look for your target:

```<code>table = lh.fromstring(doc.xpath('//genericitem/@html')[0])
</code>```

Then either

```<code>print(table.xpath('normalize-space(//font/text())'))
</code>```

or

```<code>print(table.xpath('//font/text()')[0].strip())
</code>```

The output should be

```<code>No numerical differences between 'MATLAB - M4A4b' and 'MCR - M4B2b' found.
</code>```

Body:
I have this XML data with a tag with an attribute that is filled with informations

<Start>
<TestCase>
    <GenericItem html="

Environment
(Linux)	Check Execution Time [sec]	Memory consumption [Mb]

Baseline - M4A4b
(mean of #run(s))	Baseline - M4A4b
init / mean / max

MATLAB	2.4 (10)	557 / 573 / 575

MCR	2.3699 (10)	249 / 295 / 297

No numerical differences between 'MATLAB - M4A4b' and 'MCR - M4B2b' found.">
       Results for 'A3 Item - CT07':
      </GenericItem>
</testcase>
</Start>

I need help on how to parse in Python and get only the Text Results for 'A3 Item - CT07': and No numerical differences between 'MATLAB - M4A4b' and 'MCR - M4B2b' found. which is inside the HTML attribute.

Body:
You have a strange situation where a whole html table is embedded within an attribute of an element in a parent html document....

Having said that, you can try this:

import lxml.html as lh
generic = """your html above""""

doc = lh.fromstring(generic)

#to get your "results", try either

print(doc.xpath('normalize-space(//genericitem/text())'))

#or

print(doc.xpath('//genericitem/text()')[0].strip())

In either case, the output should be

Results for 'A3 Item - CT07':

The other one requires a little more work: first extract the embedded html, then parse it and look for your target:

table = lh.fromstring(doc.xpath('//genericitem/@html')[0])

Then either

print(table.xpath('normalize-space(//font/text())'))

or

print(table.xpath('//font/text()')[0].strip())

The output should be

No numerical differences between 'MATLAB - M4A4b' and 'MCR - M4B2b' found.


Title: formatting a dataframe with coordinate points

Body:
This is a beginner question, but I have a set of coordinate points formatted like

[ [ -75.526844, 39.655713 ], [ -75.526344, 39.656413 ], [ -75.522343, 39.660813 ], [ -75.518343, 39.663913 ], [ -75.514643, 39.668613 ], [ -75.511743, 39.674313 ], [ -75.509342, 39.685313 ], [ -75.509742, 39.686113 ], [ -75.509042, 39.694513 ], [ -75.507162, 39.696961 ], [ -75.504042, 39.698313 ], [ -75.496241, 39.701413 ], [ -75.491341, 39.711113 ], [ -75.488553, 39.714833 ], [ -75.485241, 39.715813 ], [ -75.483141, 39.715513 ], [ -75.481741, 39.714546 ], [ -75.478940, 39.713813 ], [ -75.477640, 39.715013 ], [ -75.476888, 39.718337 ], [ -75.477432, 39.720561 ], [ -75.477240, 39.724713 ], [ -75.475440, 39.728713 ], [ -75.475384, 39.731057 ], [ -75.474168, 39.735473 ], [ -75.469239, 39.743613 ], [ -75.466263, 39.750737 ], [ -75.466249, 39.750769 ], [ -75.463039, 39.758313 ], [ -75.463339, 39.761213 ]]

I want to make a dataframe that has one column for longitude and one for latitude for this data. How should I go about doing this?

Body:
Well, using the basics of R, you can make use of the following implementation. I read the coordinates as a string. You can use R's readChar()

text = "[
[ -75.526844, 39.655713 ], [ -75.526344, 39.656413 ],
[ -75.522343, 39.660813 ], [ -75.518343, 39.663913 ],
[ -75.514643, 39.668613 ], [ -75.511743, 39.674313 ],
[ -75.509342, 39.685313 ], [ -75.509742, 39.686113 ],
[ -75.509042, 39.694513 ], [ -75.507162, 39.696961 ],
[ -75.504042, 39.698313 ], [ -75.496241, 39.701413 ],
[ -75.491341, 39.711113 ], [ -75.488553, 39.714833 ],
[ -75.485241, 39.715813 ], [ -75.483141, 39.715513 ],
[ -75.481741, 39.714546 ], [ -75.478940, 39.713813 ],
[ -75.477640, 39.715013 ], [ -75.476888, 39.718337 ],
[ -75.477432, 39.720561 ], [ -75.477240, 39.724713 ],
[ -75.475440, 39.728713 ], [ -75.475384, 39.731057 ],
[ -75.474168, 39.735473 ], [ -75.469239, 39.743613 ],
[ -75.466263, 39.750737 ], [ -75.466249, 39.750769 ],
[ -75.463039, 39.758313 ], [ -75.463339, 39.761213 ]]"

library(stringr)
s = str_split(gsub('\n', ' ', text), ', ')[[1]]
s = gsub('\\[|\\]', '', s)
s = str_trim(s)
df = data.frame(matrix(s, nc = 2, byrow = T))
colnames(df) = c('longitude', 'latitude')
head(df)


问:
Entity Framework DateTime and UTC
Is it possible to have Entity Framework (I am using the Code First Approach with CTP5 currently) store all DateTime values as UTC in the database?

Or is there maybe a way to specify it in the mapping, for example in this one for the last_login column:

```<code>modelBuilder.Entity<User>().Property(x => x.Id).HasColumnName("id");
modelBuilder.Entity<User>().Property(x => x.IsAdmin).HasColumnName("admin");
modelBuilder.Entity<User>().Property(x => x.IsEnabled).HasColumnName("enabled");
modelBuilder.Entity<User>().Property(x => x.PasswordHash).HasColumnName("password_hash");
modelBuilder.Entity<User>().Property(x => x.LastLogin).HasColumnName("last_login");
</code>```

答: Another approach would be to create an interface with the datetime properties, implement them on the partial entity classes. And then use the SavingChanges event to check if the object is of the interface type, set those datetime values to whatever you want. In fact, if these are createdon/modifiedon kind of dates, you can use that event to populate them.</p>

Title: Entity Framework DateTime and UTC

Body:
Is it possible to have Entity Framework (I am using the Code First Approach with CTP5 currently) store all DateTime values as UTC in the database?

Or is there maybe a way to specify it in the mapping, for example in this one for the last_login column:

modelBuilder.Entity<User>().Property(x => x.Id).HasColumnName("id");
modelBuilder.Entity<User>().Property(x => x.IsAdmin).HasColumnName("admin");
modelBuilder.Entity<User>().Property(x => x.IsEnabled).HasColumnName("enabled");
modelBuilder.Entity<User>().Property(x => x.PasswordHash).HasColumnName("password_hash");
modelBuilder.Entity<User>().Property(x => x.LastLogin).HasColumnName("last_login");


答:
You have devtool: 'source-map' in the webpack.config.js file.

.map files are sourcemaps for debugging purposes. I suggest you read what a source map is.

Title: what are ".js.map" files?

Body: I cloned a repo with a build command that runs webpack and it generates an index.js and index.map.js file. I assume index.js is a minified version of all the code, but what is index.map.js?


问:
Ldap simple user search return LDAP: error code 53 - Unwilling to process the unindexed search operation
I am not a LDAP expert, all I try to do is to run some filters on users, like get user starting with some prefix. I am getting an error every time i use * in filter [LDAP: error code 53 - Unwilling to process the unindexed search operation]; remaining name 'ou=internal,o=XXX,c=us'

It doesn't make any since, not sure what is that error message even means.
Passing in filter exact match of user name works fine

```<code>String filter = "uid=exactMatchuserName";
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
constraints.setReturningAttributes(attrIdsToSearch);
NamingEnumeration users = ldapConnection().search("ou=internal,o=XXX,c=us", filter, constraints);
</code>```

but with i use * in search String filter = "uid=*ma"; then i am getting an error

答:
The server is telling you that it's not willing to perform a search that cannot use an index. If you don't know what an index is, you can read the Wikipedia article on database indexes, but in short:

Indexes are used to quickly locate data without having to search every row in a database table every time a database table is accessed.

An index is built by sorting one of the columns in a way specified in the index (usually alphabetically, for a string column). So, for example, if I searched for uid=gabriel, it doesn't need to look at every user in the directory. It can just skip to the G's and find it quickly.

However, that means that the index can only be used when you know at least the first letter. When you use a wildcard at the beginning of the search, you don't know the first letter, so it's impossible to use the index and it will need to check every user in the directory for a match.

You have 3 options:

Don't put a wildcard at the beginning.

Add another criteria to the query that uses an indexed attribute, then you'll be able to use the wildcard in uid. You just need at least one indexed criteria.

Enable unindexed searches on your server. You tagged active-directory, but I suspect that's not what you're using since AD doesn't use the uid attribute. So search online for the directory server you're using and see if it possible to enable. Just keep in mind that disabling unindexed searches is the default for a reason.

Body:
I am not a LDAP expert, all I try to do is to run some filters on users, like get user starting with some prefix. I am getting an error every time i use * in filter [LDAP: error code 53 - Unwilling to process the unindexed search operation]; remaining name 'ou=internal,o=XXX,c=us'

It doesn't make any since, not sure what is that error message even means.
Passing in filter exact match of user name works fine

String filter = "uid=exactMatchuserName";
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
constraints.setReturningAttributes(attrIdsToSearch);
NamingEnumeration users = ldapConnection().search("ou=internal,o=XXX,c=us", filter, constraints);

but with i use * in search String filter = "uid=*ma"; then i am getting an error