问:
Access to Keycloak admin REST API by admin-cli client only?
I'm trying to do some request by administration REST API through custom client. Client has proper scopes. I get 403. Same issue when authenticate by user (with proper roles). Everything works fine when I change client to 'admin-cli' and use user authentication. I can not see any difference in configuration.
Is it possible to use admin REST API only through client 'admin-cli' and user authentication?</p>

答: See this answer to learn how to authorize your client to use the admin rest api : Keycloak Get Users returns 403 forbidden</p>


来源: stackexchange

问:
jupyter run produces invalid JSON with single quotes
I have a simple jupyter notebook file (Untitled.ipynb) that starts:

```<code>{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
</code>```

and I want to run it and convert the runned version to PDF. Step 1, run:

```<code>jupyter run Untitled.ipynb > U-Run.ipynb
</code>```

and that gets me something that uses single quotes everywhere which jupyter nbconvert barfs on:

```<code>$ head U-Run.ipynb
{'cells': [{'cell_type': 'code',
   'execution_count': 1,
   'metadata': {},
   'outputs': [{'name': 'stdout', 'output_type': 'stream', 'text': ['3\n']}],
</code>```

and when I try and convert to PDF:

```<code>$ jupyter nbconvert --to pdf U-Run.ipynb
[NbConvertApp] Converting notebook U-Run.ipynb to pdf
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/nbformat/reader.py", line 14, in parse_json
    nb_dict = json.loads(s, **kwargs)
  File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.8/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
</code>```

then a traceback that ends:

```<code>nbformat.reader.NotJSONError: Notebook does not appear to be JSON: '{\'cells\': [{\'cell_type\': \'code\',\...
</code>```

If I import json from a plain python session and try a simple test I get double quotes:

```<code>>>> json.dumps(dict(a=1))
'{"a": 1}'
</code>```

so I don't understand why jupyter run is outputting single-quoted "json".

Versions of all the things are:

```<code>$ jupyter --version
jupyter core     : 4.6.3
jupyter-notebook : 6.3.0
qtconsole        : 5.0.3
ipython          : 7.29.0
ipykernel        : 6.5.0
jupyter client   : 6.1.12
jupyter lab      : 3.0.0
nbconvert        : 6.0.7
ipywidgets       : 7.6.3
nbformat         : 5.0.4
traitlets        : 5.1.1

Python: 3.8.10
Ubuntu 20.04
</code>```

答:
Apparently, you can also tell nbconvert to --execute:

```<code>jupyter nbconvert --to pdf --execute U-Run.ipynb
</code>```

You can also use papermill to execute an ipynb file, then convert the output to PDF:

```<code>papermill U-Run.ipynb U-Run-2.ipynb
jupyter nbconvert --to pdf U-Run-2.ipynb
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a simple jupyter notebook file (Untitled.ipynb) that starts:

{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},

and I want to run it and convert the runned version to PDF. Step 1, run:

jupyter run Untitled.ipynb > U-Run.ipynb

and that gets me something that uses single quotes everywhere which jupyter nbconvert barfs on:

$ head U-Run.ipynb
{'cells': [{'cell_type': 'code',
   'execution_count': 1,
   'metadata': {},
   'outputs': [{'name': 'stdout', 'output_type': 'stream', 'text': ['3\n']}],

and when I try and convert to PDF:

$ jupyter nbconvert --to pdf U-Run.ipynb
[NbConvertApp] Converting notebook U-Run.ipynb to pdf
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/nbformat/reader.py", line 14, in parse_json
    nb_dict = json.loads(s, **kwargs)
  File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.8/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

then a traceback that ends:

nbformat.reader.NotJSONError: Notebook does not appear to be JSON: '{\'cells\': [{\'cell_type\': \'code\',\...

If I import json from a plain python session and try a simple test I get double quotes:

>>> json.dumps(dict(a=1))
'{"a": 1}'

so I don't understand why jupyter run is outputting single-quoted "json".

Versions of all the things are:

$ jupyter --version
jupyter core     : 4.6.3
jupyter-notebook : 6.3.0
qtconsole        : 5.0.3
ipython          : 7.29.0
ipykernel        : 6.5.0
jupyter client   : 6.1.12
jupyter lab      : 3.0.0
nbconvert        : 6.0.7
ipywidgets       : 7.6.3
nbformat         : 5.0.4
traitlets        : 5.1.1

Python: 3.8.10
Ubuntu 20.04

Body:
Apparently, you can also tell nbconvert to --execute:

jupyter nbconvert --to pdf --execute U-Run.ipynb

You can also use papermill to execute an ipynb file, then convert the output to PDF:

papermill U-Run.ipynb U-Run-2.ipynb
jupyter nbconvert --to pdf U-Run-2.ipynb


问:
Binance Api Python setup
I created a Bot to trade BTC with Binance and am currently trying to set my Raspberry Pi 3 B+ up. With every pip install python-binance I get

```<code>  Using cached backports.zoneinfo-0.2.1.tar.gz (74 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... done
Building wheels for collected packages: backports.zoneinfo
  Building wheel for backports.zoneinfo (PEP 517) ... error
  ERROR: Command errored out with exit status 1:
   command: /home/ubuntu/test/venv/bin/python3 /tmp/tmp6c7k6imv build_wheel /tmp/tmpuge_0m5b
       cwd: /tmp/pip-install-cje139s6/backports.zoneinfo
  Complete output (39 lines):
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib.linux-aarch64-3.8
  creating build/lib.linux-aarch64-3.8/backports
  copying src/backports/__init__.py -> build/lib.linux-aarch64-3.8/backports
  creating build/lib.linux-aarch64-3.8/backports/zoneinfo
  copying src/backports/zoneinfo/_tzpath.py -> build/lib.linux-aarch64-3.8/backports/zoneinfo
  copying src/backports/zoneinfo/_common.py -> build/lib.linux-aarch64-3.8/backports/zoneinfo
  copying src/backports/zoneinfo/__init__.py -> build/lib.linux-aarch64-3.8/backports/zoneinfo
  copying src/backports/zoneinfo/_version.py -> build/lib.linux-aarch64-3.8/backports/zoneinfo
  copying src/backports/zoneinfo/_zoneinfo.py -> build/lib.linux-aarch64-3.8/backports/zoneinfo
  running egg_info
  writing src/backports.zoneinfo.egg-info/PKG-INFO
  writing dependency_links to src/backports.zoneinfo.egg-info/dependency_links.txt
  writing requirements to src/backports.zoneinfo.egg-info/requires.txt
  writing top-level names to src/backports.zoneinfo.egg-info/top_level.txt
  reading manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt'
  reading manifest template 'MANIFEST.in'
  warning: no files found matching '*.png' under directory 'docs'
  warning: no files found matching '*.svg' under directory 'docs'
  no previously-included directories found matching 'docs/_build'
  no previously-included directories found matching 'docs/_output'
  adding license file 'LICENSE'
  adding license file 'licenses/LICENSE_APACHE'
  writing manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt'
  copying src/backports/zoneinfo/__init__.pyi -> build/lib.linux-aarch64-3.8/backports/zoneinfo
  copying src/backports/zoneinfo/py.typed -> build/lib.linux-aarch64-3.8/backports/zoneinfo
  running build_ext
  building 'backports.zoneinfo._czoneinfo' extension
  creating build/temp.linux-aarch64-3.8
  creating build/temp.linux-aarch64-3.8/lib
  aarch64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/home/ubuntu/test/venv/include -I/usr/include/python3.8 -c lib/zoneinfo_module.c -o build/temp.linux-aarch64-3.8/lib/zoneinfo_module.o -std=c99
  lib/zoneinfo_module.c:1:10: fatal error: Python.h: No such file or directory
      1 | #include "Python.h"
        |          ^~~~~~~~~~
  compilation terminated.
  error: command 'aarch64-linux-gnu-gcc' failed with exit status 1
  ----------------------------------------
  ERROR: Failed building wheel for backports.zoneinfo
Failed to build backports.zoneinfo
ERROR: Could not build wheels for backports.zoneinfo which use PEP 517 and cannot be installed directly
</code>```

I tried to update pip, wheel, setuptools to the newest version, ran the same command on my desktop computer, where it worked without problem.
The systeminformation for my Raspberry Pi are:

OS: Ubuntu 20.04.3 LTS

Python: 3.8.10

pip: 20.0.2

wheel: 0.37.0

setuptools: 58.0.4

答: I faced the same issue on my Raspberry Pi. Use pip3  install python-binance instead of pip install python-binance

Title: Binance Api Python setup

Body:
I created a Bot to trade BTC with Binance and am currently trying to set my Raspberry Pi 3 B+ up. With every pip install python-binance I get

  Using cached backports.zoneinfo-0.2.1.tar.gz (74 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... done
Building wheels for collected packages: backports.zoneinfo
  Building wheel for backports.zoneinfo (PEP 517) ... error
  ERROR: Command errored out with exit status 1:
   command: /home/ubuntu/test/venv/bin/python3 /tmp/tmp6c7k6imv build_wheel /tmp/tmpuge_0m5b
       cwd: /tmp/pip-install-cje139s6/backports.zoneinfo
  Complete output (39 lines):
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib.linux-aarch64-3.8
  creating build/lib.linux-aarch64-3.8/backports
  copying src/backports/__init__.py -> build/lib.linux-aarch64-3.8/backports
  creating build/lib.linux-aarch64-3.8/backports/zoneinfo
  copying src/backports/zoneinfo/_tzpath.py -> build/lib.linux-aarch64-3.8/backports/zoneinfo
  copying src/backports/zoneinfo/_common.py -> build/lib.linux-aarch64-3.8/backports/zoneinfo
  copying src/backports/zoneinfo/__init__.py -> build/lib.linux-aarch64-3.8/backports/zoneinfo
  copying src/backports/zoneinfo/_version.py -> build/lib.linux-aarch64-3.8/backports/zoneinfo
  copying src/backports/zoneinfo/_zoneinfo.py -> build/lib.linux-aarch64-3.8/backports/zoneinfo
  running egg_info
  writing src/backports.zoneinfo.egg-info/PKG-INFO
  writing dependency_links to src/backports.zoneinfo.egg-info/dependency_links.txt
  writing requirements to src/backports.zoneinfo.egg-info/requires.txt
  writing top-level names to src/backports.zoneinfo.egg-info/top_level.txt
  reading manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt'
  reading manifest template 'MANIFEST.in'
  warning: no files found matching '*.png' under directory 'docs'
  warning: no files found matching '*.svg' under directory 'docs'
  no previously-included directories found matching 'docs/_build'
  no previously-included directories found matching 'docs/_output'
  adding license file 'LICENSE'
  adding license file 'licenses/LICENSE_APACHE'
  writing manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt'
  copying src/backports/zoneinfo/__init__.pyi -> build/lib.linux-aarch64-3.8/backports/zoneinfo
  copying src/backports/zoneinfo/py.typed -> build/lib.linux-aarch64-3.8/backports/zoneinfo
  running build_ext
  building 'backports.zoneinfo._czoneinfo' extension
  creating build/temp.linux-aarch64-3.8
  creating build/temp.linux-aarch64-3.8/lib
  aarch64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/home/ubuntu/test/venv/include -I/usr/include/python3.8 -c lib/zoneinfo_module.c -o build/temp.linux-aarch64-3.8/lib/zoneinfo_module.o -std=c99
  lib/zoneinfo_module.c:1:10: fatal error: Python.h: No such file or directory
      1 | #include "Python.h"
        |          ^~~~~~~~~~
  compilation terminated.
  error: command 'aarch64-linux-gnu-gcc' failed with exit status 1
  ----------------------------------------
  ERROR: Failed building wheel for backports.zoneinfo
Failed to build backports.zoneinfo
ERROR: Could not build wheels for backports.zoneinfo which use PEP 517 and cannot be installed directly

I tried to update pip, wheel, setuptools to the newest version, ran the same command on my desktop computer, where it worked without problem.
The systeminformation for my Raspberry Pi are:

OS: Ubuntu 20.04.3 LTS

Python: 3.8.10

pip: 20.0.2

wheel: 0.37.0

setuptools: 58.0.4


问:
Spring Security oauth2 client - How does one obtain a JWT token
I am trying to use spring-security-oauth2-client and spring-security-oauth2-jose to authenticate against Azure AD and get JWT tokens.
The login part works but the token that I receive is not a JWT. Here's my configuration :

```<code>@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .authorizeRequests()
    .anyRequest()
    .authenticated()
    .and()
    .oauth2Login()
    .loginPage("/oauth2/authorization/azure")
    .userInfoEndpoint()
    .oidcUserService(oidcUserService);
}

}
</code>```

After authentication, I retrieve the token from the security context as follows :

```<code>OAuth2AuthenticationToken authentication = (OAuth2AuthenticationToken)
SecurityContextHolder.getContext().getAuthentication();
OAuth2AccessToken accessToken = authorizedClientService.loadAuthorizedClient(
            authentication.getAuthorizedClientRegistrationId()
            ,authentication.getName()
            ).getAccessToken();
</code>```

I get a Bearer token that looks like:

"AQABAAAAAADXzZ3ifr-GRbDT45zNSEFElTInSJQ19I2zONWkrBPgoKf8MCYL_z_IzU2lmF_ZadgBMdCr337faL0bpqHAzmFhsxq8peWUX7iYeTLbmcHDIdCR617VSKKHISLn_AiXhNr9rF6AMSrQTzdV2mKhEVlycTXlHUsZkA-gMA4z4FQFQMYkFNcLKqr7b-NewnV07lbG55joRIkcCMDrM1s4X8mRcJpRF6ek1yNSpveFmlbkrt3cXPUqtDe5EWI_5gfuGEVIon57LFLos_JtcQWSL6CTrUlY8EuF8MVuwJpTNG3OR80ikK7ycH_dXFCYmYDRrtTbFkf3R61aDSnqEUe2IIl2T8QdqWqH65ykSVooG6uIi5KsRK9zXPRuRuC_XC5w6SCcGionQYIgSEp-kCtIzlfHIBRK2o_CpjYVMBdmbfIkCvFoTGGGAvpOP1_MkgVeBiQzYFg8m_dn_roXFF17oBhCdYrZ2Y41_-GngLU3VJj4ltFIxzRziH6CZ2aFl1N3MwzIUcTiN6Ci0oyODTsSNDPc2zvxg609SjEqrO-6Xp0LMEwiOgY5L5rrcLA5d4LN-Xq9NiG0KqybZPU7wW0AHNA2Nw7bSg1Cle0ReaBU4ANbkjHxYeQJf65-ONNMGdfkV8xlKtRXZoiOBFip87Z72cS4NjLjM3x9_Qk9MQ5eGQTNj4fHCzJp9ukcjQ1MSUol_VIgAA
"

Which is then rejected by the Microsoft Graph API. Any help or suggestion is greatly appreciated.

答:
Based on @govind's answer, this is the way to get an OIDC token in modern functional Java:</p>
```<code>public Optional<String> getCurrentToken() {
    return Optional.ofNullable(SecurityContextHolder.getContext())
        .map(SecurityContext::getAuthentication)
        .map(Authentication::getPrincipal)
        .filter(OidcUser.class::isInstance)
        .map(OidcUser.class::cast)
        .map(OidcUser::getIdToken)
        .map(OidcIdToken::getTokenValue);
}
</code>```

Body:
I am trying to use spring-security-oauth2-client and spring-security-oauth2-jose to authenticate against Azure AD and get JWT tokens.
The login part works but the token that I receive is not a JWT. Here's my configuration :

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .authorizeRequests()
    .anyRequest()
    .authenticated()
    .and()
    .oauth2Login()
    .loginPage("/oauth2/authorization/azure")
    .userInfoEndpoint()
    .oidcUserService(oidcUserService);
}

}

After authentication, I retrieve the token from the security context as follows :

OAuth2AuthenticationToken authentication = (OAuth2AuthenticationToken)
SecurityContextHolder.getContext().getAuthentication();
OAuth2AccessToken accessToken = authorizedClientService.loadAuthorizedClient(
            authentication.getAuthorizedClientRegistrationId()
            ,authentication.getName()
            ).getAccessToken();

I get a Bearer token that looks like:

"AQABAAAAAADXzZ3ifr-GRbDT45zNSEFElTInSJQ19I2zONWkrBPgoKf8MCYL_z_IzU2lmF_ZadgBMdCr337faL0bpqHAzmFhsxq8peWUX7iYeTLbmcHDIdCR617VSKKHISLn_AiXhNr9rF6AMSrQTzdV2mKhEVlycTXlHUsZkA-gMA4z4FQFQMYkFNcLKqr7b-NewnV07lbG55joRIkcCMDrM1s4X8mRcJpRF6ek1yNSpveFmlbkrt3cXPUqtDe5EWI_5gfuGEVIon57LFLos_JtcQWSL6CTrUlY8EuF8MVuwJpTNG3OR80ikK7ycH_dXFCYmYDRrtTbFkf3R61aDSnqEUe2IIl2T8QdqWqH65ykSVooG6uIi5KsRK9zXPRuRuC_XC5w6SCcGionQYIgSEp-kCtIzlfHIBRK2o_CpjYVMBdmbfIkCvFoTGGGAvpOP1_MkgVeBiQzYFg8m_dn_roXFF17oBhCdYrZ2Y41_-GngLU3VJj4ltFIxzRziH6CZ2aFl1N3MwzIUcTiN6Ci0oyODTsSNDPc2zvxg609SjEqrO-6Xp0LMEwiOgY5L5rrcLA5d4LN-Xq9NiG0KqybZPU7wW0AHNA2Nw7bSg1Cle0ReaBU4ANbkjHxYeQJf65-ONNMGdfkV8xlKtRXZoiOBFip87Z72cS4NjLjM3x9_Qk9MQ5eGQTNj4fHCzJp9ukcjQ1MSUol_VIgAA
"

Which is then rejected by the Microsoft Graph API. Any help or suggestion is greatly appreciated.

Body:
Based on @govind's answer, this is the way to get an OIDC token in modern functional Java:

public Optional<String> getCurrentToken() {
    return Optional.ofNullable(SecurityContextHolder.getContext())
        .map(SecurityContext::getAuthentication)
        .map(Authentication::getPrincipal)
        .filter(OidcUser.class::isInstance)
        .map(OidcUser.class::cast)
        .map(OidcUser::getIdToken)
        .map(OidcIdToken::getTokenValue);
}


问:
AWS CodeBuild BUILD_CONTAINER_UNABLE_TO_PULL_IMAGE error
I'm trying to use a custom image in my CodeBuild definition, but it fails with the following error:

BUILD_CONTAINER_UNABLE_TO_PULL_IMAGE: Unable to pull customer's
container image. Asm fetching username: AuthorizationData is
malformed, empty field

The terraform definition is the following:

```<code>resource "aws_codebuild_project" "apply" {
  name          = local.names.apply_codebuild
  description   = "Responsible for 'apply' of CodeBuild '${local.names.apply_codebuild}'"
  build_timeout = "120"
  service_role  = aws_iam_role.apply.arn

  artifacts {
    type = "CODEPIPELINE"
  }

  environment {
    compute_type                = "BUILD_GENERAL1_SMALL"
    image                       = "docker.cloudsmith.io/myorg/devops/amazonlinux2-custom:latest"
    type                        = "LINUX_CONTAINER"
    image_pull_credentials_type = "SERVICE_ROLE"

    registry_credential {
      credential  = "CLOUDSMITH_API_KEY"
      credential_provider = "SECRETS_MANAGER"
    }
  }

  source {
    type = "CODEPIPELINE"
    buildspec = templatefile("${path.module}/buildspecs/apply.yml", {
      SCRIPT           = local.apply_script
      NAME             = var.name
      RUNTIME_VERSIONS = var.runtime_versions
    })
  }
}
</code>```

Any ideas on what might be the issue?

答: Issue was that Cloudsmith asks for both the username and the API-key, not only the API-Key. The CLOUDSMITH_API_KEY secret only contained the API-key. After adding the username and the API-key as password, it worked.

Body:
I'm trying to use a custom image in my CodeBuild definition, but it fails with the following error:

BUILD_CONTAINER_UNABLE_TO_PULL_IMAGE: Unable to pull customer's
container image. Asm fetching username: AuthorizationData is
malformed, empty field

The terraform definition is the following:

resource "aws_codebuild_project" "apply" {
  name          = local.names.apply_codebuild
  description   = "Responsible for 'apply' of CodeBuild '${local.names.apply_codebuild}'"
  build_timeout = "120"
  service_role  = aws_iam_role.apply.arn

  artifacts {
    type = "CODEPIPELINE"
  }

  environment {
    compute_type                = "BUILD_GENERAL1_SMALL"
    image                       = "docker.cloudsmith.io/myorg/devops/amazonlinux2-custom:latest"
    type                        = "LINUX_CONTAINER"
    image_pull_credentials_type = "SERVICE_ROLE"

    registry_credential {
      credential  = "CLOUDSMITH_API_KEY"
      credential_provider = "SECRETS_MANAGER"
    }
  }

  source {
    type = "CODEPIPELINE"
    buildspec = templatefile("${path.module}/buildspecs/apply.yml", {
      SCRIPT           = local.apply_script
      NAME             = var.name
      RUNTIME_VERSIONS = var.runtime_versions
    })
  }
}

Any ideas on what might be the issue?


问:
import CSV in another language to SAS
I am attempting to import a CSV file which is in French to my US based analysis. I have noticed several issues in the import related to the use of accents. I put the csv file into a text reader and found that the data look like this

I am unsure how to get rid of the [sub] pieces and format this properly.

I am on SAS 9.3 and am unable to edit the CSV as it is a shared CSV with French researchers. I am also limited to what I can do in terms of additional languages within SAS because of admin rights.

I have tried the following fixes:

```<code>data want(encoding=asciiany);
set have;
comment= Compress(comment,'0D0A'x);
comment= TRANWRD(comment,'0D0A'x,'');
comment= TRANWRD(comment,'0D'x,'');
comment= TRANWRD(comment,"\u001a",'');
</code>```

How can I resolve these issues?

答:
While this would have been a major issue a few decades ago, nowadays, it's very simple to determine the encoding and then run your SAS in the right mode.

First, open the CSV in a text editor, not the basic Notepad but almost any other; Notepad++ is free, for example, or Ultraedit or Textpad, on Windows, or on the Mac, BBEdit, or several others will do.  I'll assume Notepad++ for the rest of this answer, but all of them have some way of doing this.  If you're in a restricted no-admin-rights environment, good news: Notepad++ can be installed in your user folder with no admin rights (or even on a USB!). (Also, an advanced text editor is a vital data science tool, so you should have one anyway.)

In Notepad++, once you open the file there will be an encoding in the bottom right: "UTF-8", "WLATIN1", "ASCII", etc., depending on the encoding of the file.  Look and see what that is, and write it down.

Once you have that, you can try starting SAS in that encoding.  For the rest of this, I assume it is in UTF-8 as that is fairly standard, but replace UTF-8 with whatever the encoding you determined. earlier.

See this article for more details; the instructions are for 9.4, but they have been the same for years.  If this doesn't work, you'll need to talk to your SAS administrator, and they may need to modify your SAS installation.

You can either:

Make a new shortcut (a copy of the one you run SAS with) and add -encoding UTF-8 to the command line

Create a new configuration file, point SAS to it, and include ENCODING=UTF-8 in the configuration file.

Note that this will have some other impacts - the datasets you create will be encoded in UTF-8, and while SAS is capable of handling that, it will add some extra notes to the log and some extra time if you later do work in non-UTF8 SAS with this, or if you use non-UTF8 SAS datasets in this mode.

Title: import CSV in another language to SAS

Body:
I am attempting to import a CSV file which is in French to my US based analysis. I have noticed several issues in the import related to the use of accents. I put the csv file into a text reader and found that the data look like this

I am unsure how to get rid of the [sub] pieces and format this properly.

I am on SAS 9.3 and am unable to edit the CSV as it is a shared CSV with French researchers. I am also limited to what I can do in terms of additional languages within SAS because of admin rights.

I have tried the following fixes:

data want(encoding=asciiany);
set have;
comment= Compress(comment,'0D0A'x);
comment= TRANWRD(comment,'0D0A'x,'');
comment= TRANWRD(comment,'0D'x,'');
comment= TRANWRD(comment,"\u001a",'');

How can I resolve these issues?


问:
HikariPool-1 - Connection marked as broken because of SQLSTATE(08006), ErrorCode(0)
After we setup PostgreSQL server with SSL certificates we get this error very often.
This happens on the flows with a lot of interaction with the database(update a lot of entries/insert)   </p>

```<code>HikariPool-1 - Connection marked as broken because of SQLSTATE(08006), ErrorCode(0)
j.n.SocketException: Connection reset by peer (Write failed)
    at j.n.SocketOutputStream.socketWrite0(SocketOutputStream.java)
    at j.n.SocketOutputStream.socketWrite(SocketOutputStream.java:110)
    at j.n.SocketOutputStream.write(SocketOutpu`enter code here`tStream.java:150)
    at s.s.s.SSLSocketOutputRecord.deliver(SSLSocketOutputRecord.java:320)
    at s.s.s.SSLSocketImpl$AppOutputStream.write(SSLSocketImpl.java:983)
    ... 63 common frames omitted
Wrapped by: j.n.s.SSLProtocolException: Connection reset by peer (Write failed)
    at s.security.ssl.Alert.createSSLException(Alert.java:126)
    at s.s.s.TransportContext.fatal(TransportContext.java:321)
    at s.s.s.TransportContext.fatal(TransportContext.java:264)
    at s.s.s.TransportContext.fatal(TransportContext.java:259)
    at s.s.s.SSLSocketImpl$AppOutputStream.write(SSLSocketImpl.java:988)
    at j.i.BufferedOutputStream.write(BufferedOutputStream.java:123)
    at j.i.FilterOutputStream.write(FilterOutputStream.java:108)
    at o.p.core.PGStream.send(PGStream.java:252)
    at o.p.c.v.QueryExecutorImpl.sendParse(QueryExecutorImpl.java:1440)
    at o.p.c.v.QueryExecutorImpl.sendOneQuery(QueryExecutorImpl.java:1767)
    at o.p.c.v.QueryExecutorImpl.sendQuery(QueryExecutorImpl.java:1328)
    at o.p.c.v.QueryExecutorImpl.execute(QueryExecutorImpl.java:300)
    ... 56 common frames omitted
Wrapped by: o.p.u.PSQLException: An I/O error occurred while sending to the backend
</code>```

答:
I was able to solve this issue by adding below properties:</p>
```<code>spring.datasource.test-while-idle=true
spring.datasource.validation-query=SELECT 1;
spring.datasource.time-between-eviction-runs-millis=60000
spring.datasource.hikari.idle-timeout=600000
spring.datasource.hikari.validationTimeout=300000

spring.datasource.remove-abandoned=true
spring.datasource.remove-abandoned-timeout=60

spring.datasource.hikari.connectionTimeout=30000
spring.datasource.hikari.idleTimeout=600000
spring.datasource.hikari.maxLifetime=1800000
</code>```

Body:
After we setup PostgreSQL server with SSL certificates we get this error very often.
This happens on the flows with a lot of interaction with the database(update a lot of entries/insert)

HikariPool-1 - Connection marked as broken because of SQLSTATE(08006), ErrorCode(0)
j.n.SocketException: Connection reset by peer (Write failed)
    at j.n.SocketOutputStream.socketWrite0(SocketOutputStream.java)
    at j.n.SocketOutputStream.socketWrite(SocketOutputStream.java:110)
    at j.n.SocketOutputStream.write(SocketOutpu`enter code here`tStream.java:150)
    at s.s.s.SSLSocketOutputRecord.deliver(SSLSocketOutputRecord.java:320)
    at s.s.s.SSLSocketImpl$AppOutputStream.write(SSLSocketImpl.java:983)
    ... 63 common frames omitted
Wrapped by: j.n.s.SSLProtocolException: Connection reset by peer (Write failed)
    at s.security.ssl.Alert.createSSLException(Alert.java:126)
    at s.s.s.TransportContext.fatal(TransportContext.java:321)
    at s.s.s.TransportContext.fatal(TransportContext.java:264)
    at s.s.s.TransportContext.fatal(TransportContext.java:259)
    at s.s.s.SSLSocketImpl$AppOutputStream.write(SSLSocketImpl.java:988)
    at j.i.BufferedOutputStream.write(BufferedOutputStream.java:123)
    at j.i.FilterOutputStream.write(FilterOutputStream.java:108)
    at o.p.core.PGStream.send(PGStream.java:252)
    at o.p.c.v.QueryExecutorImpl.sendParse(QueryExecutorImpl.java:1440)
    at o.p.c.v.QueryExecutorImpl.sendOneQuery(QueryExecutorImpl.java:1767)
    at o.p.c.v.QueryExecutorImpl.sendQuery(QueryExecutorImpl.java:1328)
    at o.p.c.v.QueryExecutorImpl.execute(QueryExecutorImpl.java:300)
    ... 56 common frames omitted
Wrapped by: o.p.u.PSQLException: An I/O error occurred while sending to the backend

Body:
I was able to solve this issue by adding below properties:

spring.datasource.test-while-idle=true
spring.datasource.validation-query=SELECT 1;
spring.datasource.time-between-eviction-runs-millis=60000
spring.datasource.hikari.idle-timeout=600000
spring.datasource.hikari.validationTimeout=300000

spring.datasource.remove-abandoned=true
spring.datasource.remove-abandoned-timeout=60

spring.datasource.hikari.connectionTimeout=30000
spring.datasource.hikari.idleTimeout=600000
spring.datasource.hikari.maxLifetime=1800000


问:
Classifying graph with DGL GNN without nodes attributes
I'm following this guide to create the dataset for graph classification from my own data: https://docs.dgl.ai/en/0.6.x/new-tutorial/6_load_data.html

There they don't create any node's feature as it is not necessary if you are going to predict the graph class. In my case it is the same, I don't want to use any node feature (yet) for my classification.

To train the GNN I'm following this tutorial: https://docs.dgl.ai/tutorials/blitz/5_graph_classification.html#sphx-glr-tutorials-blitz-5-graph-classification-py

Both are from the official documentation but they seem to be incompatible because when I tried to use them together I received this error:

```<code>KeyError                                  Traceback (most recent call last) <ipython-input-39-8a94f1fa250d> in <module>
      4 for epoch in range(20):
      5     for batched_graph, labels in train_dataloader:
----> 6         pred = model(batched_graph, batched_graph.ndata['attr'].float())
      7         loss = F.cross_entropy(pred, labels)
      8         optimizer.zero_grad()

~/anaconda3/lib/python3.8/site-packages/dgl/view.py in
__getitem__(self, key)
     64             return ret
     65         else:
---> 66             return self._graph._get_n_repr(self._ntid, self._nodes)[key]
     67
     68     def __setitem__(self, key, val):

~/anaconda3/lib/python3.8/site-packages/dgl/frame.py in
__getitem__(self, name)
    391             Column data.
    392         """
--> 393         return self._columns[name].data
    394
    395     def __setitem__(self, name, data):

KeyError: 'attr'
</code>```

and I don't find another example to train a GNN with DGl without using the node's feature. Is it possible? Do I have to create fake attributes?

Thanks!

答:
DGL model always needs to have at least one feature. SO I resolve it by using the degree feature in the classifier:</p>
```<code>class Classifier(nn.Module):
    def __init__(self, in_dim, hidden_dim, n_classes):
        super(Classifier, self).__init__()
        self.conv1 = GraphConv(in_dim, hidden_dim)
        self.conv2 = GraphConv(hidden_dim, hidden_dim)
        self.classify = nn.Linear(hidden_dim, n_classes)

    def forward(self, g):
        # Use node degree as the initial node feature. For undirected graphs, the in-degree
        # is the same as the out_degree.
        h = g.in_degrees().view(-1, 1).float()
        # Perform graph convolution and activation function.
        h = F.relu(self.conv1(g, h))
        h = F.relu(self.conv2(g, h))
        g.ndata['h'] = h
        # Calculate graph representation by averaging all the node representations.
        hg = dgl.mean_nodes(g, 'h')
        return self.classify(hg)
</code>```

Body:
I'm following this guide to create the dataset for graph classification from my own data: https://docs.dgl.ai/en/0.6.x/new-tutorial/6_load_data.html

There they don't create any node's feature as it is not necessary if you are going to predict the graph class. In my case it is the same, I don't want to use any node feature (yet) for my classification.

To train the GNN I'm following this tutorial: https://docs.dgl.ai/tutorials/blitz/5_graph_classification.html#sphx-glr-tutorials-blitz-5-graph-classification-py

Both are from the official documentation but they seem to be incompatible because when I tried to use them together I received this error:

KeyError                                  Traceback (most recent call last) <ipython-input-39-8a94f1fa250d> in <module>
      4 for epoch in range(20):
      5     for batched_graph, labels in train_dataloader:
----> 6         pred = model(batched_graph, batched_graph.ndata['attr'].float())
      7         loss = F.cross_entropy(pred, labels)
      8         optimizer.zero_grad()

~/anaconda3/lib/python3.8/site-packages/dgl/view.py in
__getitem__(self, key)
     64             return ret
     65         else:
---> 66             return self._graph._get_n_repr(self._ntid, self._nodes)[key]
     67
     68     def __setitem__(self, key, val):

~/anaconda3/lib/python3.8/site-packages/dgl/frame.py in
__getitem__(self, name)
    391             Column data.
    392         """
--> 393         return self._columns[name].data
    394
    395     def __setitem__(self, name, data):

KeyError: 'attr'

and I don't find another example to train a GNN with DGl without using the node's feature. Is it possible? Do I have to create fake attributes?

Thanks!

Body:
DGL model always needs to have at least one feature. SO I resolve it by using the degree feature in the classifier:

class Classifier(nn.Module):
    def __init__(self, in_dim, hidden_dim, n_classes):
        super(Classifier, self).__init__()
        self.conv1 = GraphConv(in_dim, hidden_dim)
        self.conv2 = GraphConv(hidden_dim, hidden_dim)
        self.classify = nn.Linear(hidden_dim, n_classes)

    def forward(self, g):
        # Use node degree as the initial node feature. For undirected graphs, the in-degree
        # is the same as the out_degree.
        h = g.in_degrees().view(-1, 1).float()
        # Perform graph convolution and activation function.
        h = F.relu(self.conv1(g, h))
        h = F.relu(self.conv2(g, h))
        g.ndata['h'] = h
        # Calculate graph representation by averaging all the node representations.
        hg = dgl.mean_nodes(g, 'h')
        return self.classify(hg)


问:
How do I edit the existing file in fortran and export it to the same file
I am trying to exchange some characters in my input file.
My code is working properly if I export the data to a new file.
However, I can not export my changes to the same file. After first 2 line, it does not export the data correctly. Do you have any suggestions for me?

This is my data that I need to change (I need to remove the % symbols)

test.su2:

```<code>%file
%
%
%
4 4
4 5
3 5
%
%
3 4
4 2
</code>```

Here is my code that ignores the lines start with % and write it to the another .su2 file:

program update_su2_file

```<code>  IMPLICIT NONE
  INTEGER :: I
  CHARACTER(80) :: LINE

  OPEN(10,FILE='2DCRM.su2',FORM='FORMATTED')
  OPEN(20,FILE='2DCRM_updated.su2',FORM='FORMATTED')

  DO 100 WHILE (.TRUE.)
  READ (10,'(A)',END=999) LINE  !Read line from input file

  IF(LINE(1:1).EQ.'%') GOTO 100 !Skip line starts with %
  WRITE(20,'(A)') TRIM(LINE)    !Write line to output file   100 END DO   999 CONTINUE

  CLOSE (10)
  CLOSE (20)

  END PROGRAM update_su2_file
</code>```

Basically I need to write my updated data to the test.su2 file instead of a new file.

I have tried to update my code as below, but as I mentioned above it does not write my data properly.

program update_su2_file

```<code>  IMPLICIT NONE
  INTEGER :: I
  CHARACTER(80) :: LINE

  OPEN(10,FILE='test.su2',FORM='FORMATTED')

  DO 100 WHILE (.TRUE.)
  READ (10,'(A)',END=999) LINE  !Read line from input file

  IF(LINE(1:1).EQ.'%') GOTO 100 !Skip line starts with %
  WRITE(10,'(A)') TRIM(LINE)    !Write line to output file   100 END DO   999 CONTINUE

  CLOSE (10)

  END PROGRAM update_su2_file
</code>```

This is the output file which is not correct:

```<code>%file
%file
</code>```

答:
Editing the file in-place is the wrong way to solve your problem. You should write your desired output to a second file and, if desired, replace the original file with this second.

Rather than showing how to edit the file in place, I'll explain why this isn't what you should be doing.

A connected external file has a single position. For this task you need to maintain two positions: where you're about to write, and the read progress you've made so far. You can do this, but you'll have to manually track and reposition.

Your file has records of differing length. If you want to replace the first record with content %file with the record with content 4 4, or the content % with 2 4 you need to shift the location in the file of anything else that follows. This will dwarf any filesystem access cost that creating a second file has.

Even with just these two issues, it's already become a Herculean task.  One you will get wrong, trashing your only copy of the file. Much easier to write to a second file.

You also have to think about reproducibility and usability. For this task your program is idempotent (so won't matter if you run the program again on your new file), but not all similar programs will be.

Just like when testing your dangerous overwriting program, you'll want the original available in the future: tomorrow, your supervisor says "I'd like the input data you got so I can share with my other student", or a journal reviewer asks "What did the original source look like?". You want to keep the original research artifact safely stored away so "in place" makes little sense.

Body:
I am trying to exchange some characters in my input file.
My code is working properly if I export the data to a new file.
However, I can not export my changes to the same file. After first 2 line, it does not export the data correctly. Do you have any suggestions for me?

This is my data that I need to change (I need to remove the % symbols)

test.su2:

%file
%
%
%
4 4
4 5
3 5
%
%
3 4
4 2

Here is my code that ignores the lines start with % and write it to the another .su2 file:

program update_su2_file

  IMPLICIT NONE
  INTEGER :: I
  CHARACTER(80) :: LINE

  OPEN(10,FILE='2DCRM.su2',FORM='FORMATTED')
  OPEN(20,FILE='2DCRM_updated.su2',FORM='FORMATTED')

  DO 100 WHILE (.TRUE.)
  READ (10,'(A)',END=999) LINE  !Read line from input file

  IF(LINE(1:1).EQ.'%') GOTO 100 !Skip line starts with %
  WRITE(20,'(A)') TRIM(LINE)    !Write line to output file   100 END DO   999 CONTINUE

  CLOSE (10)
  CLOSE (20)

  END PROGRAM update_su2_file

Basically I need to write my updated data to the test.su2 file instead of a new file.

I have tried to update my code as below, but as I mentioned above it does not write my data properly.

program update_su2_file

  IMPLICIT NONE
  INTEGER :: I
  CHARACTER(80) :: LINE

  OPEN(10,FILE='test.su2',FORM='FORMATTED')

  DO 100 WHILE (.TRUE.)
  READ (10,'(A)',END=999) LINE  !Read line from input file

  IF(LINE(1:1).EQ.'%') GOTO 100 !Skip line starts with %
  WRITE(10,'(A)') TRIM(LINE)    !Write line to output file   100 END DO   999 CONTINUE

  CLOSE (10)

  END PROGRAM update_su2_file

This is the output file which is not correct:

%file
%file


问:
Creating a unique random 5 character slug
Hi I have a function that will generate a random string which works fine. What I would like to do is store that string as the primary key in my database. The problem is that I first need to make sure that the string is unique before storing it. Here is what I have so far. I'm sure I need a loop until result = <0 but not sure how to go about that any help would be much appriciated. I'm also open to a better solution as I think this may be a slow solution. </p>

```<code>//generate random slug
function genRandomString($length=10,$characters = '0123456789abcdefghijklmnopqrstuvwxyz',$string = '') {
    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }

    return $string; }

 //store slug into variable
 $slug = genRandomString('5');

 //select the slug that is equal to our slug
 $qry = "SELECT `slug` FROM `drink_data` WHERE `slug` = '$slug'";
 $result = mysql_query($qry);
    //if reslut make a new slug (this dosen't recheck the new slug which is a problem)
        if($result >= 0){
             $slug = genRandomString('5');

        }
</code>```

答:
First, instead of $result >= 0, use mysql_num_rows($result) >= 0). Next, you'll likely want to wrap this whole thing in a while:

```<code>do{
  $slug = genRandomString(5);
  //select the slug that is equal to our slug
  $qry = "SELECT `slug` FROM `drink_data` WHERE `slug` = '$slug'";
  $result = mysql_query($qry);
}while(mysql_num_rows($result) > 0);
</code>```

This will keep generating new slugs (and checking their uniqueness) until it finds something. You'll probably want to add code to bail on saturation (5 numbers isn't that long, you'll fill up quickly and this loop will run exponentially slower).

ContentLicense: CC BY-SA 3.0

Body:
Hi I have a function that will generate a random string which works fine. What I would like to do is store that string as the primary key in my database. The problem is that I first need to make sure that the string is unique before storing it. Here is what I have so far. I'm sure I need a loop until result = <0 but not sure how to go about that any help would be much appriciated. I'm also open to a better solution as I think this may be a slow solution.

//generate random slug
function genRandomString($length=10,$characters = '0123456789abcdefghijklmnopqrstuvwxyz',$string = '') {
    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }

    return $string; }

 //store slug into variable
 $slug = genRandomString('5');

 //select the slug that is equal to our slug
 $qry = "SELECT `slug` FROM `drink_data` WHERE `slug` = '$slug'";
 $result = mysql_query($qry);
    //if reslut make a new slug (this dosen't recheck the new slug which is a problem)
        if($result >= 0){
             $slug = genRandomString('5');

        }

Body:
First, instead of $result >= 0, use mysql_num_rows($result) >= 0). Next, you'll likely want to wrap this whole thing in a while:

do{
  $slug = genRandomString(5);
  //select the slug that is equal to our slug
  $qry = "SELECT `slug` FROM `drink_data` WHERE `slug` = '$slug'";
  $result = mysql_query($qry);
}while(mysql_num_rows($result) > 0);

This will keep generating new slugs (and checking their uniqueness) until it finds something. You'll probably want to add code to bail on saturation (5 numbers isn't that long, you'll fill up quickly and this loop will run exponentially slower).


问:
How can I use iteration to find value that will balance equation in MS Excel 2016
I've got a spreadsheet with a complex series of formulas based on a value x. Currently, the user has to enter a guess at x and adjust it until the difference between the result of all the calculations (using x) equals a pre-set value y.  The way the spreadsheet is set up now, x and y are in two cells and a third cell shows the difference between them (let's call it z). So the user just adjusts their guess at x up and down until the z is as close to zero as possible.

Is there any way I can automate that last step, so Excel will just iterate through possible values of x until z = 0?

答:
Excel has a "Solver" feature, which you can use for finding a value, based on the result of formulae. It's an add-in, you need to activate it.

Hereby a screenshot of what it looks like: B1 = A1^2, I would like to know the square root of 5:

More information can be found here.


问:
NavLink returns active to all links and no solution in SO seems to work
It seems none of the solutions presented elsewhere works, so I decided to ask. No matter what I do, I can't get the NavLinks to be rendered differently if they are active or not. I took the ternary operator straight from the part about NavLinks in react-router-dom's documentation and I'd try to create a function to avoid having all this code written three times, but before that I'd like to at least have the correct rendering working.

(side question: why does it break if I remove the Router tags from the return statement? They're there because, before I needed the NavLinks for different styling, I was using regular routes, but if I take them out it breaks with a message about useHref, something like that)

Here's my return statement and the styled-components below it:

```<code>return (
        <>
            <GlobalStyles />
            <Router>
                <Header />
                <Wrapper>
                    <NavBar>
                        <NavLink
                            to="/search"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Search song
                        </NavLink>
                        <NavLink
                            to="/weekly-thread"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Weekly thread
                        </NavLink>
                        <NavLink
                            to="/game"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Game
                        </NavLink>
                    </NavBar>
                </Wrapper>
            </Router>
        </>
    );
};

const Wrapper = styled.div`
    width: 100vw;
    height: 100vh;
    position: absolute;
    z-index: -1;
`;
const NavBar = styled.div`
    display: flex;
    padding: 20px 20px;
    position: relative;
    gap: 20px;
    font-size: 18px;
    a {
        text-decoration: none;
    }
    .nav-link {
        color: blue;
        &:inactive {
            color: black;
        }
    }
`;

</code>```

EDIT: it's getting weirder. After even simply pasting the code from the answer below and not getting any results, I tried to mess with the font size for the active NavLink. To my surprise, now something changed, but in totally bizarre way, as it made the first element stay as it were before and second and third got transformed just in terms of font size, but nothing else. When I click on the other NavLinks, the URL changes, but they remain the same: the first in the original size, the other two altered.

SECOND EDIT: Trying to debug this a little further, I've done this to one of my NavLinks and the result is very weird:

```<code><NavLink to="/search" exact className={(isActive) => {
    console.log(isActive);
    isActive === false ? console.log(isActive) : console.log("foo");
}}>Search song</NavLink>
</code>```

Now, the first console.log returns the actual value of isActive, but the second and third console.logs always return, "foo", which is the second value in the ternary operator, even if I change "isActive === false" to "isActive === true", which should swap them. I have no idea what is going on here.

答:
After console.logs here, there and everywhere, something struck my attention: isActive appears as an object on the console. That's why I was always getting the same result.

When I changed the condition on the ternary operator to isActive.isActive ? I started getting the expected results.

Body:
It seems none of the solutions presented elsewhere works, so I decided to ask. No matter what I do, I can't get the NavLinks to be rendered differently if they are active or not. I took the ternary operator straight from the part about NavLinks in react-router-dom's documentation and I'd try to create a function to avoid having all this code written three times, but before that I'd like to at least have the correct rendering working.

(side question: why does it break if I remove the Router tags from the return statement? They're there because, before I needed the NavLinks for different styling, I was using regular routes, but if I take them out it breaks with a message about useHref, something like that)

Here's my return statement and the styled-components below it:

return (
        <>
            <GlobalStyles />
            <Router>

                <Wrapper>
                    <NavBar>
                        <NavLink
                            to="/search"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Search song
                        </NavLink>
                        <NavLink
                            to="/weekly-thread"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Weekly thread
                        </NavLink>
                        <NavLink
                            to="/game"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Game
                        </NavLink>
                    </NavBar>
                </Wrapper>
            </Router>
        </>
    );
};

const Wrapper = styled.div`
    width: 100vw;
    height: 100vh;
    position: absolute;
    z-index: -1;
`;
const NavBar = styled.div`
    display: flex;
    padding: 20px 20px;
    position: relative;
    gap: 20px;
    font-size: 18px;
    a {
        text-decoration: none;
    }
    .nav-link {
        color: blue;
        &:inactive {
            color: black;
        }
    }
`;

EDIT: it's getting weirder. After even simply pasting the code from the answer below and not getting any results, I tried to mess with the font size for the active NavLink. To my surprise, now something changed, but in totally bizarre way, as it made the first element stay as it were before and second and third got transformed just in terms of font size, but nothing else. When I click on the other NavLinks, the URL changes, but they remain the same: the first in the original size, the other two altered.

SECOND EDIT: Trying to debug this a little further, I've done this to one of my NavLinks and the result is very weird:

<NavLink to="/search" exact className={(isActive) => {
    console.log(isActive);
    isActive === false ? console.log(isActive) : console.log("foo");
}}>Search song</NavLink>

Now, the first console.log returns the actual value of isActive, but the second and third console.logs always return, "foo", which is the second value in the ternary operator, even if I change "isActive === false" to "isActive === true", which should swap them. I have no idea what is going on here.


问:
use_frameworks! for only some pods or swift pods
I have both Objective C and Swift Pods in my project.

```<code>pod 'WBWebViewConsole', '~> 1.0.1'
use_frameworks!
pod 'XWebView', '~>0.9.5’
pod 'Starscream', '~> 1.1.3'
</code>```

As swift PODs(XWebView, Starscream) can only be added as frameworks I have to use
use_frameworks!

But this makes all the PODs as framework including Objective-C PODs(WBWebViewConsole) as well.

But it causes problem with Objective-C POD but I don't intend to make Objective-C POD as framework.

So is there anyway I can ignore couple of PODs from being converted as framework ?

Thanks.

Update:

How to reproduce the problem ?

The problem is with the POD WBWebViewConsole

Run the attached project in any iOS 8+ devices that has internet connection as it loads a html doc from google drive.

in the html doc … click General/Info/Warning/Debug/Error Log

you will some text appearing on the html page whenever u click any of the above buttons….

The library is about capturing the logs that’s generated in html page…

Whenever u click the button apart from showing some text in html page I am writing some log in background.

Now click on the button get logs … and see the logs in Xcode IDE… you will see the all the console logs that’s generated in html

Get logs-> is a native button super imposed on webview..the library lets us read the console logs from wkwebview
..

Now in the POD
u uncomment the following lines

```<code>use_frameworks!
pod 'PLCrashReporter'
pod 'XWebView', '~> 0.9.5’
</code>```

and do pod install

then paste the following code on top of ViewController

```<code>import WBWebViewConsole
</code>```

Here is the project with which has all this uncommented with all the changes required to reproduce the problem

now u run the project on device and click some buttons in html page and click get logs you can't see comments that's generated in the html page

To be specific below delegate methods implemented in WBWKWebView are not getting fired.

```<code>- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
- (void)wb_evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(NSString *, NSError *))completionHandler
</code>```

But while creating the instance of WBWKWebView and loading a URL all the necessary delegates of this class are getting fired.

The above delegates are supposed to fire when a log is written while clicking the button in html page

答:
From the answer of @MujtabaFR , i had errors says file not found in my pod global import header file and i can't resolve those. So in already working static libraries i tried inserting my dynamic framework, so i tried his solution with backward compatibility and so reversing his solution works fine for me, here it is for reference

```<code>dynamic_frameworks = ['aaa','bbb'] # <- swift libraries names

# Make all the other frameworks into dynamic frameworks by overriding the dynamic_framework? function to return true
pre_install do |installer|
  installer.pod_targets.each do |pod|
    if dynamic_frameworks.include?(pod.name)
      puts "Overriding the dynamic_framework? method for #{pod.name}"
      def pod.dynamic_framework?;
        true
      end
      def pod.build_type;
        Pod::BuildType.dynamic_framework
      end
    end
  end
end
</code>```

So this remains my existing code as it is and inserted my new swift pod as dynamic framework.

Thank you @MujtabaFR

Body:
I have both Objective C and Swift Pods in my project.

pod 'WBWebViewConsole', '~> 1.0.1'
use_frameworks!
pod 'XWebView', '~>0.9.5’
pod 'Starscream', '~> 1.1.3'

As swift PODs(XWebView, Starscream) can only be added as frameworks I have to use
use_frameworks!

But this makes all the PODs as framework including Objective-C PODs(WBWebViewConsole) as well.

But it causes problem with Objective-C POD but I don't intend to make Objective-C POD as framework.

So is there anyway I can ignore couple of PODs from being converted as framework ?

Thanks.

Update:

How to reproduce the problem ?

The problem is with the POD WBWebViewConsole

Run the attached project in any iOS 8+ devices that has internet connection as it loads a html doc from google drive.

in the html doc … click General/Info/Warning/Debug/Error Log

you will some text appearing on the html page whenever u click any of the above buttons….

The library is about capturing the logs that’s generated in html page…

Whenever u click the button apart from showing some text in html page I am writing some log in background.

Now click on the button get logs … and see the logs in Xcode IDE… you will see the all the console logs that’s generated in html

Get logs-> is a native button super imposed on webview..the library lets us read the console logs from wkwebview
..

Now in the POD
u uncomment the following lines

use_frameworks!
pod 'PLCrashReporter'
pod 'XWebView', '~> 0.9.5’

and do pod install

then paste the following code on top of ViewController

import WBWebViewConsole

Here is the project with which has all this uncommented with all the changes required to reproduce the problem

now u run the project on device and click some buttons in html page and click get logs you can't see comments that's generated in the html page

To be specific below delegate methods implemented in WBWKWebView are not getting fired.

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
- (void)wb_evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(NSString *, NSError *))completionHandler

But while creating the instance of WBWKWebView and loading a URL all the necessary delegates of this class are getting fired.

The above delegates are supposed to fire when a log is written while clicking the button in html page

Body:
From the answer of @MujtabaFR , i had errors says file not found in my pod global import header file and i can't resolve those. So in already working static libraries i tried inserting my dynamic framework, so i tried his solution with backward compatibility and so reversing his solution works fine for me, here it is for reference

dynamic_frameworks = ['aaa','bbb'] # <- swift libraries names

# Make all the other frameworks into dynamic frameworks by overriding the dynamic_framework? function to return true
pre_install do |installer|
  installer.pod_targets.each do |pod|
    if dynamic_frameworks.include?(pod.name)
      puts "Overriding the dynamic_framework? method for #{pod.name}"
      def pod.dynamic_framework?;
        true
      end
      def pod.build_type;
        Pod::BuildType.dynamic_framework
      end
    end
  end
end

So this remains my existing code as it is and inserted my new swift pod as dynamic framework.

Thank you @MujtabaFR


问:
Page not found(404),Current path didn't match any of these
Views.py

```<code>From django.http import HttpResponse

def home(request):
    Return HttpResponse('Hello World')
</code>```

urls.py(my_app)

```<code>From Django.urls import path
From . Import views

Urlspatterns=[
    Path(' ',views.home)
]
</code>```

Main urls

```<code>From django.urls import path, include
From Django.contrib import adim

Urlspatterns=[
    Path('admim/',.....)
    Path(' ',include('my_app.urls))
</code>```

Settings.py

```<code>Installed apps=[
     " ",
     " ",
     'my_app',
]
</code>```

Why I run the server it tells me page not found, ....... current empty path didn't match any of these, my Django has been working fine until recently, even if I start a new project from scratch it ends up with same result, I'm actually at the edge of giving up on Django ,I really need help please.... thanks in advance

答:
Your empty url has space in path inside main urls.py.

```<code>from django.urls import path, include
from django.contrib import admin

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('my_app.urls'))
]
</code>```

Also in your app urls.py remove space from url path

```<code>from django.urls import path
from . import views

urlpatterns = [
    path('', views.home)
]
</code>```

Also you have typo error there is no Urlspatterns use urlpatterns instead and in case of Installed apps use INSTALLED_APPS.

Also in views.py return instead of Return

```<code>from django.http import HttpResponse

def home(request):
    return HttpResponse('Hello World')
</code>```

And lastly in all files use from instead of From

Body:
Views.py

From django.http import HttpResponse

def home(request):
    Return HttpResponse('Hello World')

urls.py(my_app)

From Django.urls import path
From . Import views

Urlspatterns=[
    Path(' ',views.home)
]

Main urls

From django.urls import path, include
From Django.contrib import adim

Urlspatterns=[
    Path('admim/',.....)
    Path(' ',include('my_app.urls))

Settings.py

Installed apps=[
     " ",
     " ",
     'my_app',
]

Why I run the server it tells me page not found, ....... current empty path didn't match any of these, my Django has been working fine until recently, even if I start a new project from scratch it ends up with same result, I'm actually at the edge of giving up on Django ,I really need help please.... thanks in advance

Body:
Your empty url has space in path inside main urls.py.

from django.urls import path, include
from django.contrib import admin

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('my_app.urls'))
]

Also in your app urls.py remove space from url path

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home)
]

Also you have typo error there is no Urlspatterns use urlpatterns instead and in case of Installed apps use INSTALLED_APPS.

Also in views.py return instead of Return

from django.http import HttpResponse

def home(request):
    return HttpResponse('Hello World')

And lastly in all files use from instead of From


问:
Using inheritance to provide one class by another in Python
I'm trying to become a self taught developer, so I have nobody to ask when I do not understand the task in a course. The question is about inheritance.
Given structure

I have to implement some classes as a piece of program to monitor news.
I was given the base abstract class Trigger

```<code>class Trigger(object):
    def evaluate(self, story):
        """
        Returns True if an alert should be generated
        for the given news item, or False otherwise.
        """
        # DO NOT CHANGE THIS!
        raise NotImplementedError
</code>```

And then I have to implement other classes accordingly the scheme. I did it like that:

```<code>class PhraseTrigger(Trigger):

    def __init__(self, trigger, story):
        self._trigger = trigger
        self._story = story

    def is_phrase_in(self):

        phrase_to_match = r"((\W)+|^)"
        for i in self._trigger.split():
            phrase_to_match += i
            if (i != self._trigger.split()[-1]):
                phrase_to_match += r"(\W)+"
            else:
                phrase_to_match += r"((\W)+|$)"

        # print(phrase_to_match) # delete after debugging
        scheme_to_match = re.compile(phrase_to_match, re.IGNORECASE)
        mo = scheme_to_match.search(self._story)

        if (mo != None):
            return True
        else:
            return False

    def evaluate(self, story):
        """
        Returns True if an alert should be generated
        for the given news item, or False otherwise.
        """

        if is_phrase_in(self):
            return True
        else:
            return False
</code>```

I've done all of them except Not-, And- and OrTrigger.
Next I was said "The NotTrigger should produce its output by inverting the output of another trigger. The NOT trigger should take this other trigger as an argument to its constructor". How can I add another class to init method of NotTrigger? Or I did not catch the idea completely. Any advice will be appreciated.
P.S. Sorry for long text and my poor English(it's my second language).

答:
Let's start with a simple implementation of NotTrigger. Here is how you would define an initializer (technically not the constructor) that accepts another trigger:

```<code>class NotTrigger:
    def __init__(self, trigger):
        self.trigger = trigger
</code>```

Now the evaluate method should be trivial:

```<code>def evaluate(self, story):
    return not self.trigger.evaluate(story)
</code>```

Hopefully you now see some of the problems with your implementation of PhraseTrigger:

PhraseTrigger should not accept neither another trigger as an argument to __init__, nor the story.

PhraseTrigger should not directly implement evaluate: that's up to the child classes.

PhraseTrigger should accept a phrase to search for.

PhraseTrigger should provide a method is_phrase_in(self, text) to search for self.phrase in text. Child classes will determine what to pass in for text.

Body:
I'm trying to become a self taught developer, so I have nobody to ask when I do not understand the task in a course. The question is about inheritance.
Given structure

I have to implement some classes as a piece of program to monitor news.
I was given the base abstract class Trigger

class Trigger(object):
    def evaluate(self, story):
        """
        Returns True if an alert should be generated
        for the given news item, or False otherwise.
        """
        # DO NOT CHANGE THIS!
        raise NotImplementedError

And then I have to implement other classes accordingly the scheme. I did it like that:

class PhraseTrigger(Trigger):

    def __init__(self, trigger, story):
        self._trigger = trigger
        self._story = story

    def is_phrase_in(self):

        phrase_to_match = r"((\W)+|^)"
        for i in self._trigger.split():
            phrase_to_match += i
            if (i != self._trigger.split()[-1]):
                phrase_to_match += r"(\W)+"
            else:
                phrase_to_match += r"((\W)+|$)"

        # print(phrase_to_match) # delete after debugging
        scheme_to_match = re.compile(phrase_to_match, re.IGNORECASE)
        mo = scheme_to_match.search(self._story)

        if (mo != None):
            return True
        else:
            return False

    def evaluate(self, story):
        """
        Returns True if an alert should be generated
        for the given news item, or False otherwise.
        """

        if is_phrase_in(self):
            return True
        else:
            return False

I've done all of them except Not-, And- and OrTrigger.
Next I was said "The NotTrigger should produce its output by inverting the output of another trigger. The NOT trigger should take this other trigger as an argument to its constructor". How can I add another class to init method of NotTrigger? Or I did not catch the idea completely. Any advice will be appreciated.
P.S. Sorry for long text and my poor English(it's my second language).

Body:
Let's start with a simple implementation of NotTrigger. Here is how you would define an initializer (technically not the constructor) that accepts another trigger:

class NotTrigger:
    def __init__(self, trigger):
        self.trigger = trigger

Now the evaluate method should be trivial:

def evaluate(self, story):
    return not self.trigger.evaluate(story)

Hopefully you now see some of the problems with your implementation of PhraseTrigger:

PhraseTrigger should not accept neither another trigger as an argument to __init__, nor the story.

PhraseTrigger should not directly implement evaluate: that's up to the child classes.

PhraseTrigger should accept a phrase to search for.

PhraseTrigger should provide a method is_phrase_in(self, text) to search for self.phrase in text. Child classes will determine what to pass in for text.


问:
Confusion in type conversion
i have confusion in type conversion please help me on below things.

```<code><%# int.Parse(Eval("VendorId").ToString()) %>,
<%# Eval("ListId").ToString()%>
</code>```

what these two returns?
Please suggest me on conversion.

答:
The Page.Eval method returns a object (System.Object). So:

int.Parse(Eval("VendorId").ToString()) is first evaluating the property expression VendorId (via DataBindiner.Eval), and then calling ToString(). The string conversion is required, because Int32.Parse accepts a string argument. You run the risk of having a null value returned here and passed to Int32.Parse though.

Eval("ListId").ToString() is doing the same as above, but rendering the result of ToString() for the property expression Listid, instead of parsing it as an integer.

Title: Confusion in type conversion

Body:
i have confusion in type conversion please help me on below things.

<%# int.Parse(Eval("VendorId").ToString()) %>,
<%# Eval("ListId").ToString()%>

what these two returns?
Please suggest me on conversion.


问:
How to change routing as component: lazy() to simple routes
I have a template, they are using this method of routing the components ,

```<code>import { lazy } from 'react'

// ** Document title
const TemplateTitle = '%s - Title'

// ** Default Route
const DefaultRoute = '/dashboard'

// ** Merge Routes
const Routes = [
  {
    path: '/dashboard',
    component: lazy(() => import('../../views/dashboard'))
  },
  {
    path: '/home',
    component: lazy(() => import('../../views/Home'))
  }
]

export { DefaultRoute, TemplateTitle, Routes }
</code>```

But I like to to use function components ;

like this one

```<code>import React from 'react'

function Profile() {
    return <div>Profile</div>
}

export default Profile
</code>```

So when I added a route as they template was created

```<code> {
    path: '/profile',
    component: lazy(() => import('../../views/Profile'))
  },

</code>```

I'm unable to access to it, So how could that be achieved and If switch to simple routing using hash router then is that possible to change that with few lines of code as all of template is made with lazy() routing method

答:
Try this

const Component = lazy(() => import('../../views/Profile'));

{
  path: '/profile',
  component: <Component />
},```

Body:
I have a template, they are using this method of routing the components ,

import { lazy } from 'react'

// ** Document title
const TemplateTitle = '%s - Title'

// ** Default Route
const DefaultRoute = '/dashboard'

// ** Merge Routes
const Routes = [
  {
    path: '/dashboard',
    component: lazy(() => import('../../views/dashboard'))
  },
  {
    path: '/home',
    component: lazy(() => import('../../views/Home'))
  }
]

export { DefaultRoute, TemplateTitle, Routes }

But I like to to use function components ;

like this one

import React from 'react'

function Profile() {
    return
Profile

}

export default Profile

So when I added a route as they template was created

 {
    path: '/profile',
    component: lazy(() => import('../../views/Profile'))
  },

I'm unable to access to it, So how could that be achieved and If switch to simple routing using hash router then is that possible to change that with few lines of code as all of template is made with lazy() routing method


问:
Hosting interactive jupyter notebook on private website
I currently run a personal website using Wordpress (but hosted on siteground) that is a set of engineering study guides. I would like to move towards making these study guides interactive (i.e. refreshing graphics based on sliders, doing basic calculations to indicate if a design works or not, so I need numpy). A friend recommended that I utilize Jupyter notebooks for this purpose, as you can both render LaTeX (which I'm currently using Mathjax with Wordpress to do), as well as have the types of interactive graphics I want using either Bokeh or Plotly.

While I've seen tutorials for sharing notebooks on specific servers, what I'm after is being able for others to run my notebook in their browser (read-only), where the notebook is privately hosted.

I'm still not sure if Jupyter is the correct avenue to accomplish what I want, so I'm open to other suggestions (someone also recommended using Julia, but I've seen fewer examples of this).

答:
You can try to use Mercury framework. It allows you to transform notebooks into web applications (with interactive widgets). You need to add YAML header to the beginning of the notebook. Based on YAML the widgets will be generated. Your users can change widgets values and click Run button to execute the notebook with new inputs. You can decide whether to show or hide code for your users. You can serve multiple notebooks with Mercury on single server. It is based on Django so can be easily deployed on any server/cloud.

The example notebook:

The generated application for the above notebook:

The screenshot of app/notebooks gallery in the Mercury:


问:
Is any way to add 2 arrays into one?
Is there any simple univesal way to add 2 arrays into one? In the case below it is not possible simply use C := A + B statement...
I would like to avoid making algorhytm for it everytime .

```<code>TPerson = record
    Birthday: Tdate;
    Name, Surname:string;
end;

Tpeople = array of TPerson;

var A, B, C:Tpeople;

C:=A+B; // it is not possible
</code>```

thanx

答:
There is nothing built in that allows dynamic arrays to be concatenated.

You may consider using one of the generic container classes found in Generics.Collections, TList.

In your case you would have 3 instances of TList, say A, B and C. Then you could write

```<code>A.Clear;
A.AddRange(B);
A.AddRange(C);
</code>```

I think this is as close as you can get to what you want with what is delivered out of the box.

If you are prepared to do a bit of coding yourself then you could make use of operator overloading to use the exact syntax you requires. Declare a record containing an array of TPerson with private visibility. You then need to implement an Add operator, a Count property and a default Items[] property. This could be made generic too so you only need write it once.

```<code>TTurboArray = record<T>
private
  FItems: array of T;
  //property accessors here
 public
   class operator Add(a, b: TTurboArray<T>): TTurboArray<T>;
   property Count: Integer read GetCount write SetCount;
   property Items[Index: Integer]: T read GetItem write SetItem; default;
end;
</code>```

This idea can be extended into a very powerful data structure as you see fit.

Title: Is any way to add 2 arrays into one?

Body:
Is there any simple univesal way to add 2 arrays into one? In the case below it is not possible simply use C := A + B statement...
I would like to avoid making algorhytm for it everytime .

TPerson = record
    Birthday: Tdate;
    Name, Surname:string;
end;

Tpeople = array of TPerson;

var A, B, C:Tpeople;

C:=A+B; // it is not possible

thanx

Body:
There is nothing built in that allows dynamic arrays to be concatenated.

You may consider using one of the generic container classes found in Generics.Collections, TList.

In your case you would have 3 instances of TList, say A, B and C. Then you could write

A.Clear;
A.AddRange(B);
A.AddRange(C);

I think this is as close as you can get to what you want with what is delivered out of the box.

If you are prepared to do a bit of coding yourself then you could make use of operator overloading to use the exact syntax you requires. Declare a record containing an array of TPerson with private visibility. You then need to implement an Add operator, a Count property and a default Items[] property. This could be made generic too so you only need write it once.

TTurboArray = record<T>
private
  FItems: array of T;
  //property accessors here
 public
   class operator Add(a, b: TTurboArray<T>): TTurboArray<T>;
   property Count: Integer read GetCount write SetCount;
   property Items[Index: Integer]: T read GetItem write SetItem; default;
end;

This idea can be extended into a very powerful data structure as you see fit.


问:
Set Enter on keypress to start search asp.net c#
I've a page with a GridView and a search textbox with his button near to it and i want to set that when the user press "ENTER" start the search and only that.
I don't know how to set this thing in ASP.NET C#.

And how can I do to modify the style of:

Messaggio_Ricerca.Text = " I caratteri inseriti nella barra di ricerca non sono validi. "

when it comes out ?

ASP Code:

```<code>     Ricerca :
            <asp:TextBox ID="CampoRicerca" runat="server" CssClass="textbox" Width="300px" Height="25px" Placeholder="Inserisci qui i dati che vuoi cercare" ></asp:TextBox>
            <asp:Button ID="BTN_Ricerca" OnClick="Ricerca_NomeInserito" runat="server" Text="" Width="35" Height="35" CssClass="ricerca"></asp:Button>
            <asp:Label ID="Messaggio_Ricerca" runat="server"></asp:Label>
</code>```

C# Code:

```<code>protected void Ricerca_NomeInserito(object sender, EventArgs e)
        {
            this.RicercaCliente();
        }

private void RicercaCliente()
        {
            //String query code

            if (String.IsNullOrWhiteSpace(CampoRicerca.Text))
            {
                Messaggio_Ricerca.Text = " I caratteri inseriti nella barra di ricerca non sono validi. ";
            }

            else
            {
                //SqlCommand code
            }
       }
</code>```

答:
ok, so say we have this markup:

A simple grid and a search:

```<code><asp:Label ID="Label1" runat="server" Text="Search for Fighter jet" Font-Size="Large"></asp:Label>
<asp:TextBox ID="txtSearch" runat="server" Style="margin-left:15px" Font-Size="Large"></asp:TextBox>
<asp:Button ID="cmdSearch" runat="server" Text="search"
    style="margin-left:15px" CssClass="btn" OnClick="cmdSearch_Click"
    />
<br />
<br />

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        DataKeyNames="ID" CssClass="table"  >
        <Columns>
            <asp:BoundField DataField="Fighter" HeaderText="Fighter"  />
            <asp:BoundField DataField="Engine" HeaderText="Engine"  />
            <asp:BoundField DataField="Thrust" HeaderText="Thrust"  />
            <asp:BoundField DataField="Description" HeaderText="Description" />

            <asp:TemplateField HeaderText="View">
                <ItemTemplate>
                <asp:ImageButton ID="btnImage" runat="server" Height="68px" Width="149px"
                    OnClientClick ="popimage(this);return false"
                    ImageUrl = '<%# Eval("ImagePath") %>' />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</code>```

Our code to load is thus this:

```<code>   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadGrid("");
    }

    void LoadGrid(string MySearch)
    {
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Fighters ", conn))
            {
                if (MySearch != "")
                {
                    cmdSQL.CommandText += @" WHERE Fighter LIKE @Fighter + '%'";
                    cmdSQL.Parameters.Add("Fighter", SqlDbType.NVarChar).Value = MySearch;
                }
                conn.Open();
                DataTable rstData = new DataTable();
                rstData.Load(cmdSQL.ExecuteReader());
                GridView1.DataSource = rstData;
                GridView1.DataBind();
            }
        }
    }

    protected void cmdSearch_Click(object sender, EventArgs e)
    {
        LoadGrid(txtSearch.Text);
    }
</code>```

And now we have this:

So, in place of typing in the search text and THEN hitting the search button?

Sure, lets drop (remove) the search button. Now we use the text changed event of the text box, and we set auto postback = true.

So, we now have this markup:

```<code><asp:Label ID="Label1" runat="server" Text="Search for Fighter jet" Font-Size="Large"></asp:Label>
<asp:TextBox ID="txtSearch" runat="server" Style="margin-left:15px" Font-Size="Large"
    AutoPostBack="true" OnTextChanged="txtSearch_TextChanged" >
</asp:TextBox>

<br />
<br />

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
</code>```

So, with the text box set as auto postback = true, then all of its events will trigger - and fire the events.

And the code behind? We grab the button code and move it over to the text changed event like this:

```<code>    protected void txtSearch_TextChanged(object sender, EventArgs e)
    {
        LoadGrid(txtSearch.Text);
    }
</code>```

So now we just type some text, and hit enter key, we get this:

Body:
I've a page with a GridView and a search textbox with his button near to it and i want to set that when the user press "ENTER" start the search and only that.
I don't know how to set this thing in ASP.NET C#.

And how can I do to modify the style of:

Messaggio_Ricerca.Text = " I caratteri inseriti nella barra di ricerca non sono validi. "

when it comes out ?

ASP Code:

     Ricerca :
            <asp:TextBox ID="CampoRicerca" runat="server" CssClass="textbox" Width="300px" Height="25px" Placeholder="Inserisci qui i dati che vuoi cercare" ></asp:TextBox>
            <asp:Button ID="BTN_Ricerca" OnClick="Ricerca_NomeInserito" runat="server" Text="" Width="35" Height="35" CssClass="ricerca"></asp:Button>
            <asp:Label ID="Messaggio_Ricerca" runat="server"></asp:Label>

C# Code:

protected void Ricerca_NomeInserito(object sender, EventArgs e)
        {
            this.RicercaCliente();
        }

private void RicercaCliente()
        {
            //String query code

            if (String.IsNullOrWhiteSpace(CampoRicerca.Text))
            {
                Messaggio_Ricerca.Text = " I caratteri inseriti nella barra di ricerca non sono validi. ";
            }

            else
            {
                //SqlCommand code
            }
       }

Body:
ok, so say we have this markup:

A simple grid and a search:

<asp:Label ID="Label1" runat="server" Text="Search for Fighter jet" Font-Size="Large"></asp:Label>
<asp:TextBox ID="txtSearch" runat="server" Style="margin-left:15px" Font-Size="Large"></asp:TextBox>
<asp:Button ID="cmdSearch" runat="server" Text="search"
    style="margin-left:15px" CssClass="btn" OnClick="cmdSearch_Click"
    />
<br />
<br />

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        DataKeyNames="ID" CssClass="table"  >
        <Columns>
            <asp:BoundField DataField="Fighter" HeaderText="Fighter"  />
            <asp:BoundField DataField="Engine" HeaderText="Engine"  />
            <asp:BoundField DataField="Thrust" HeaderText="Thrust"  />
            <asp:BoundField DataField="Description" HeaderText="Description" />

            <asp:TemplateField HeaderText="View">
                <ItemTemplate>
                <asp:ImageButton ID="btnImage" runat="server" Height="68px" Width="149px"
                    OnClientClick ="popimage(this);return false"
                    ImageUrl = '<%# Eval("ImagePath") %>' />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

Our code to load is thus this:

   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadGrid("");
    }

    void LoadGrid(string MySearch)
    {
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Fighters ", conn))
            {
                if (MySearch != "")
                {
                    cmdSQL.CommandText += @" WHERE Fighter LIKE @Fighter + '%'";
                    cmdSQL.Parameters.Add("Fighter", SqlDbType.NVarChar).Value = MySearch;
                }
                conn.Open();
                DataTable rstData = new DataTable();
                rstData.Load(cmdSQL.ExecuteReader());
                GridView1.DataSource = rstData;
                GridView1.DataBind();
            }
        }
    }

    protected void cmdSearch_Click(object sender, EventArgs e)
    {
        LoadGrid(txtSearch.Text);
    }

And now we have this:

So, in place of typing in the search text and THEN hitting the search button?

Sure, lets drop (remove) the search button. Now we use the text changed event of the text box, and we set auto postback = true.

So, we now have this markup:

<asp:Label ID="Label1" runat="server" Text="Search for Fighter jet" Font-Size="Large"></asp:Label>
<asp:TextBox ID="txtSearch" runat="server" Style="margin-left:15px" Font-Size="Large"
    AutoPostBack="true" OnTextChanged="txtSearch_TextChanged" >
</asp:TextBox>

<br />
<br />

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"

So, with the text box set as auto postback = true, then all of its events will trigger - and fire the events.

And the code behind? We grab the button code and move it over to the text changed event like this:

    protected void txtSearch_TextChanged(object sender, EventArgs e)
    {
        LoadGrid(txtSearch.Text);
    }

So now we just type some text, and hit enter key, we get this:


问:
Why React-router doesn't re-render the page and doesn't update the data when the url changes?
I'm building a project in React that retrieves data from an API through a custom hook, as soon as the data is retrieved, it shows cards that by clicking on them open the descriptive page. Up to here everything is ok.

```<code>// App.js
<Routes>
   <Route path="/" element={<Home />} /> // cards list
   <Route path="/:eleId" element={<Details />} /> // description page
</Routes>

// Home.jsx with single card
<div className="container">
   <Link to={`/${eleId}`}>
      <Card />
   </Link>
</div>
</code>```

My problem comes here:
inside the description page I have related links that open the same page when clicked but changing the data:

```<code>// Details.jsx description page
import { useParams, Link } from 'react-router-dom';
import useData from '../hooks/useData';

const Details = () => {
   const { eleId } = useParams(),
         [data] = useData(`alpha/${eleId}`); // call API with url of eleId

   return(
      <div className="description">
         <p>BLa bla bla</p>
         <Link to={`/${data.id}`}> Related </Link>
      </div>
   );
}

export default Details;
</code>```
```<code>// useData.jsx custom hook
import { useState, useEffect } from 'react';

const useData = (param = 'all') => {
   const [data, setData] = useState([]),
         [error, setError] = useState(null),
         [isLoading, setIsLoading] = useState(true);

    const url = 'https://restcountries.com/v2/'+param;

    useEffect(() => {
        const fetchAPI = async () => {
            setIsLoading(true);
            try {
                const response = await fetch(url),
                        json = await response.json();
                setData(json);
                setError(false);
            } catch(err) {
                setError(err.message);
                setData(null);
                console.log(err);
            }
            setIsLoading(false);
        };
        fetchAPI();
    }, []);

   return [data, error, isLoading];
}

export default useData;
</code>```

the url changes correctly but the data does not update ... but if I refesh it updates.

I don't understand why React can't re-render the page. Can anyone give me some suggestions?

Thank you :)

答:
```<code>// Details.jsx description page
<div className="description">
  <p>BLa bla bla</p>
  <Link to={`/${eleId}`}>Related</Link>
<div>
</code>```

If Details component is linking to itself, i.e. the route rendering it, this means the route path is already matched and rendering Details. Details may need to "listen" for changes on the eleId route match param. Use the useParams React hook to access the eleId param and an useEffect hook with eleId as a dependency to run any side-effect necessary when the param updates.

Example:

```<code>import { useParams } from 'react-router-dom';

...

const Details = () => {

  const { eleId } = useParams();
  const [data] = useData(`alpha/${eleId}`);

  ...

  useEffect(() => {
    // Business logic to run when eleId updates
  }, [eleId]);

  ...
</code>```

For the useData hook, move the url declaration into the useEffect hook and add the param argument as a dependency for the effect. When the param changes this will retrigger the useEffect and refetch data.

```<code>const useData = (param = 'all') => {
  const [data, setData] = useState([]);
  const [error, setError] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const url = 'https://restcountries.com/v2/' + param;

    const fetchAPI = async () => {
      setIsLoading(true);
      try {
        const response = await fetch(url);
        const json = await response.json();
        setData(json);
        setError(false);
      } catch(err) {
        setError(err.message);
        setData(null);
        console.log(err);
      }
      setIsLoading(false);
    };
    fetchAPI();
  }, [param]);

  return [data, error, isLoading];
}
</code>```

Body:
I'm building a project in React that retrieves data from an API through a custom hook, as soon as the data is retrieved, it shows cards that by clicking on them open the descriptive page. Up to here everything is ok.

// App.js
<Routes>
   <Route path="/" element={<Home />} /> // cards list
   <Route path="/:eleId" element={} /> // description page
</Routes>

// Home.jsx with single card

   <Link to={`/${eleId}`}>
      <Card />
   </Link>

My problem comes here:
inside the description page I have related links that open the same page when clicked but changing the data:

// Details.jsx description page
import { useParams, Link } from 'react-router-dom';
import useData from '../hooks/useData';

const Details = () => {
   const { eleId } = useParams(),
         [data] = useData(`alpha/${eleId}`); // call API with url of eleId

   return(

BLa bla bla

         <Link to={`/${data.id}`}> Related </Link>

   );
}

export default Details;

// useData.jsx custom hook
import { useState, useEffect } from 'react';

const useData = (param = 'all') => {
   const [data, setData] = useState([]),
         [error, setError] = useState(null),
         [isLoading, setIsLoading] = useState(true);

    const url = 'https://restcountries.com/v2/'+param;

    useEffect(() => {
        const fetchAPI = async () => {
            setIsLoading(true);
            try {
                const response = await fetch(url),
                        json = await response.json();
                setData(json);
                setError(false);
            } catch(err) {
                setError(err.message);
                setData(null);
                console.log(err);
            }
            setIsLoading(false);
        };
        fetchAPI();
    }, []);

   return [data, error, isLoading];
}

export default useData;

the url changes correctly but the data does not update ... but if I refesh it updates.

I don't understand why React can't re-render the page. Can anyone give me some suggestions?

Thank you :)

Body:
// Details.jsx description page
<div className="description">
  <p>BLa bla bla</p>
  <Link to={`/${eleId}`}>Related</Link>
<div>

If Details component is linking to itself, i.e. the route rendering it, this means the route path is already matched and rendering Details. Details may need to "listen" for changes on the eleId route match param. Use the useParams React hook to access the eleId param and an useEffect hook with eleId as a dependency to run any side-effect necessary when the param updates.

Example:

import { useParams } from 'react-router-dom';

...

const Details = () => {

  const { eleId } = useParams();
  const [data] = useData(`alpha/${eleId}`);

  ...

  useEffect(() => {
    // Business logic to run when eleId updates
  }, [eleId]);

  ...

For the useData hook, move the url declaration into the useEffect hook and add the param argument as a dependency for the effect. When the param changes this will retrigger the useEffect and refetch data.

const useData = (param = 'all') => {
  const [data, setData] = useState([]);
  const [error, setError] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const url = 'https://restcountries.com/v2/' + param;

    const fetchAPI = async () => {
      setIsLoading(true);
      try {
        const response = await fetch(url);
        const json = await response.json();
        setData(json);
        setError(false);
      } catch(err) {
        setError(err.message);
        setData(null);
        console.log(err);
      }
      setIsLoading(false);
    };
    fetchAPI();
  }, [param]);

  return [data, error, isLoading];
}


问:
package Build does not exist "Build.VERSION.SDK_INT"
I want use this repository for create react native app than can run in foreground and background but when I download this repo and want to use this I get this error :

Task :app:compileDebugJavaWithJavac FAILED
C:\Users\PC\Desktop\shem\rn-heartbeat-master\android\app\src\main\java\com\rnheartbeat\BootUpReceiver.java:11: error: package Build does not exist
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

this is my infrastructure :

Operating system:  Windows 10 10.0
Max Gradle workers: 12 workers

Java runtime:   Oracle Java(TM) SE Runtime Environment 12.0.2+10

Java VM:    Oracle Java HotSpot(TM) 64-Bit Server VM 12.0.2+10 (mixed mode, sharing)

my build.gradle :

```<code>ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
    }
</code>```

my package.json:

```<code>"dependencies": {
    "react": "16.9.0",
    "react-native": "0.61.0",
    "react-redux": "^7.0.3",
    "redux": "^4.0.1",
    "redux-actions": "^2.6.5"
  }
</code>```

答: Add import android.os.Build; to your BootUpReceiver.java

Body:
I want use this repository for create react native app than can run in foreground and background but when I download this repo and want to use this I get this error :

Task :app:compileDebugJavaWithJavac FAILED
C:\Users\PC\Desktop\shem\rn-heartbeat-master\android\app\src\main\java\com\rnheartbeat\BootUpReceiver.java:11: error: package Build does not exist
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

this is my infrastructure :

Operating system:  Windows 10 10.0
Max Gradle workers: 12 workers

Java runtime:   Oracle Java(TM) SE Runtime Environment 12.0.2+10

Java VM:    Oracle Java HotSpot(TM) 64-Bit Server VM 12.0.2+10 (mixed mode, sharing)

my build.gradle :

ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
    }

my package.json:

"dependencies": {
    "react": "16.9.0",
    "react-native": "0.61.0",
    "react-redux": "^7.0.3",
    "redux": "^4.0.1",
    "redux-actions": "^2.6.5"
  }


问:
Maven dependencies for web service client using axis1
Inside a maven project, I would like to use some classes that were already generated by eclipse from a working web service wsdl. These are the proxy classes that make all the web service client connections.

The problem is to find out what are the maven dependecies I need to set in order to get it to work.

Adding:

```<code><dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-web-api</artifactId>
    <version>6.0</version>
</dependency>
</code>```

There are no eclipse errors, but when I run it I get:

Absent Code attribute in method that is not native or abstract in
class file javax/xml/rpc/ServiceException

I think the problem is I got the api but not the implementation of the web services. Which are the maven dependencies or how can I find them?

答:
The problem got solved by using the following dependencies:</p>

```<code><dependency>
    <groupId>axis</groupId>
    <artifactId>axis</artifactId>
    <version>1.4</version>
</dependency>

<dependency>
    <groupId>org.apache.axis</groupId>
    <artifactId>axis-jaxrpc</artifactId>
    <version>1.4</version>
</dependency>
</code>```

Body:
Inside a maven project, I would like to use some classes that were already generated by eclipse from a working web service wsdl. These are the proxy classes that make all the web service client connections.

The problem is to find out what are the maven dependecies I need to set in order to get it to work.

Adding:

<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-web-api</artifactId>
    <version>6.0</version>
</dependency>

There are no eclipse errors, but when I run it I get:

Absent Code attribute in method that is not native or abstract in
class file javax/xml/rpc/ServiceException

I think the problem is I got the api but not the implementation of the web services. Which are the maven dependencies or how can I find them?

Body:
The problem got solved by using the following dependencies:

<dependency>
    <groupId>axis</groupId>
    <artifactId>axis</artifactId>
    <version>1.4</version>
</dependency>

<dependency>
    <groupId>org.apache.axis</groupId>
    <artifactId>axis-jaxrpc</artifactId>
    <version>1.4</version>
</dependency>


答:
There is a quick-and-dirty way to do this. It is a terrible hack, but it should work and even take care of reference counting:

```<code>function ConcatPeople(const A, B: TPeople): TPeople;
var
  Temp: TPeople;
  ALen, BLen: Integer;
begin
  Result := Copy(A);
  BLen := Length(B);
  if BLen = 0 then
    Exit;
  ALen := Length(A);
  Temp := Copy(B);
  SetLength(Result, ALen + BLen);
  Move(Temp[0], Result[ALen], BLen * SizeOf(B[0]));
  FillChar(Temp[0], BLen * SizeOf(B[0]), 0);
end;
</code>```

In effect, the data in Temp are "swapped" with the empty records in Result, so the balance is maintained and refcounting will keep on working.

Update

For what it is worth: This is aparently the same technique as used in this accepted SO answer and in, e.g. TList<T>.Insert. I had deleted this answer, but I still think it is valid, so I undeleted it again. It could do with a lock around the Move/FillChar block, so no one accesses the items when they are being "swapped". I'll add that.

Title: Is any way to add 2 arrays into one?

Body:
There is a quick-and-dirty way to do this. It is a terrible hack, but it should work and even take care of reference counting:

function ConcatPeople(const A, B: TPeople): TPeople;
var
  Temp: TPeople;
  ALen, BLen: Integer;
begin
  Result := Copy(A);
  BLen := Length(B);
  if BLen = 0 then
    Exit;
  ALen := Length(A);
  Temp := Copy(B);
  SetLength(Result, ALen + BLen);
  Move(Temp[0], Result[ALen], BLen * SizeOf(B[0]));
  FillChar(Temp[0], BLen * SizeOf(B[0]), 0);
end;

In effect, the data in Temp are "swapped" with the empty records in Result, so the balance is maintained and refcounting will keep on working.

Update

For what it is worth: This is aparently the same technique as used in this accepted SO answer and in, e.g. TList<T>.Insert. I had deleted this answer, but I still think it is valid, so I undeleted it again. It could do with a lock around the Move/FillChar block, so no one accesses the items when they are being "swapped". I'll add that.