问:
"p=NaN" at symple slopes analysis of GLMM
I analyzed a simple slope of the GLMM cross-level interaction terms for which significant associations were found. I used "reghelper" package in R.

```<code>if (require(lme4, quietly=TRUE)) {
    model <- glmer(Y ~ X * W + (1|Com_ID), data=dat, family='binomial')
    print(summary(model))
    print(simple_slopes(model))
    graph_model(model, y=Y, x=X, lines=W)
}
</code>```

The outputs of summary and simple_slopes were as follows:

```<code>Generalized linear mixed model fit by maximum likelihood (Laplace Approximation) ['glmerMod']
 Family: binomial  ( logit )
Formula: Y ~ X * W + (1 | Com_ID)
   Data: dat

     AIC      BIC   logLik deviance df.resid
  1441.5   1468.0   -715.7   1431.5     1473

Scaled residuals:
    Min      1Q  Median      3Q     Max
-0.6387 -0.6055 -0.3888 -0.3147  3.1778

Random effects:
 Groups Name        Variance Std.Dev.
 Com_ID (Intercept) 0.007915 0.08897
Number of obs: 1478, groups:  Com_ID, 11

Fixed effects:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)  -1.3638     0.1117 -12.204  < 2e-16 ***
X            -0.4381     0.1095  -3.999 6.37e-05 ***
Wurban       -0.1526     0.1562  -0.977    0.329
X:Wurban     -0.1977     0.1489  -1.328    0.184
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Correlation of Fixed Effects:
         (Intr) X      Wurban
X         0.258
Wurban   -0.722 -0.185
X:Wurban -0.187 -0.736  0.289
       X                  W Test Estimate Std. Error t value
1     -1 0.0451892102738553        0.1820     0.2483  0.8039
2      0 -0.152553682044491        0.1562    -0.9766  0.3288
3      1 -0.350285976436759        0.2450    -1.4298  0.1528
4 sstest -0.438054016500106        0.1095    -3.9987  0.0001
5 sstest -0.635779394026394        0.1009    -6.3039  0.0000
</code>```

The p-value of the simple slope cannot be identified in that package, so I found some articles introducing to a website(http://www.quantpsy.org/interact/hlm2.htm) and used the calculator. However, SE, z and p were "NaN" at simple intercepts and slopes at conditional values of w at w1(2).
I don't know what caused this. Can I ask for help?

Y and X are binary data and X is scaled. W is a two-level factor type.

```<code>    CASE 3 TWO-WAY INTERACTION SIMPLE SLOPES OUTPUT

Your Input
========================================================
  w1(1)       = 0
  w1(2)       = 1
  x1(1)       = -1
  x1(2)       = 1
  Intercept   = -1.07691
  x1 Slope    = -0.71724
  w1 Slope    = -0.03432
  w1x1 Slope  = -0.56498
  alpha       = 0.05

Asymptotic (Co)variances
========================================================
  var(g00) 0.01709818
  var(g10) 0.05253264
  var(g01) 0.03291322
  var(g11) 0.10903864
  cov(g00,g01) -0.726
  cov(g10,g11) -0.694
  cov(g00,g10) -0.458
  cov(g01,g11) -0.378

Region of Significance on w (level-2 predictor)
========================================================
  w1 at lower bound of region = -0.0508
  w1 at upper bound of region = 61.634
  (simple slopes are significant *inside* this region.)

Simple Intercepts and Slopes at Conditional Values of w
========================================================
  At w1(1)...
    simple intercept = -1.0769(0.1308), z=-8.2358, p=0
    simple slope     = -0.7172(0.2292), z=-3.1293, p=0.0018
  At w1(2)...
    simple intercept = -1.1112(NaN), z=NaN, p=NaN            # <--- Here
    simple slope     = -1.2822(NaN), z=NaN, p=NaN            # <--- Here

Simple Intercepts and Slopes at Region Boundaries for w
========================================================
  Lower Bound...
    simple intercept = -1.0752(0.3016), z=-3.5652, p=0.0004
    simple slope     = -0.6885(0.3512), z=-1.9607, p=0.0499
  Upper Bound...
    simple intercept = -3.1922(5.9627), z=-0.5354, p=0.5924
    simple slope     = -35.5392(18.1305), z=-1.9602, p=0.05

Region of Significance on x (level-1 predictor)
========================================================
  x1 at lower bound of region = 0.0426
  x1 at upper bound of region = 29.4637
  (simple slopes are significant *inside* this region.)

Simple Intercepts and Slopes at Conditional Values of x
========================================================
  At x1(1)...
    simple intercept = -0.3597(0.9928), z=-0.3623, p=0.7171
    simple slope     = 0.5307(0.9476), z=0.56, p=0.5755
  At x1(2)...
    simple intercept = -1.7941(NaN), z=NaN, p=NaN
    simple slope     = -0.5993(NaN), z=NaN, p=NaN

Simple Intercepts and Slopes at Region Boundaries for x
========================================================
  Lower Bound...
    simple intercept = -1.1075(NaN), z=NaN, p=NaN
    simple slope     = -0.0584(0.0301), z=-1.9404, p=0.0524
  Upper Bound...
    simple intercept = -22.2095(4.3165), z=-5.1452, p=0
    simple slope     = -16.6807(8.5098), z=-1.9602, p=0.05

Points to Plot
=======================================================
  Line for w1(1):  From {x1=-1, Y=-0.3597} to {x1=1, Y=-1.7941}
  Line for w1(2):  From {x1=-1, Y=0.171} to {x1=1, Y=-2.3934}

</code>```

I found this website(https://groups.google.com/g/lavaan/c/lyjF4JZAgBk) and set 100000 at df_int and df_slp. But the result of "simple intercepts and slopes at conditional values of w at w1(2)" didn't change.

Body:
I analyzed a simple slope of the GLMM cross-level interaction terms for which significant associations were found. I used "reghelper" package in R.

if (require(lme4, quietly=TRUE)) {
    model <- glmer(Y ~ X * W + (1|Com_ID), data=dat, family='binomial')
    print(summary(model))
    print(simple_slopes(model))
    graph_model(model, y=Y, x=X, lines=W)
}

The outputs of summary and simple_slopes were as follows:

Generalized linear mixed model fit by maximum likelihood (Laplace Approximation) ['glmerMod']
 Family: binomial  ( logit )
Formula: Y ~ X * W + (1 | Com_ID)
   Data: dat

     AIC      BIC   logLik deviance df.resid
  1441.5   1468.0   -715.7   1431.5     1473

Scaled residuals:
    Min      1Q  Median      3Q     Max
-0.6387 -0.6055 -0.3888 -0.3147  3.1778

Random effects:
 Groups Name        Variance Std.Dev.
 Com_ID (Intercept) 0.007915 0.08897
Number of obs: 1478, groups:  Com_ID, 11

Fixed effects:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)  -1.3638     0.1117 -12.204  < 2e-16 ***
X            -0.4381     0.1095  -3.999 6.37e-05 ***
Wurban       -0.1526     0.1562  -0.977    0.329
X:Wurban     -0.1977     0.1489  -1.328    0.184
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Correlation of Fixed Effects:
         (Intr) X      Wurban
X         0.258
Wurban   -0.722 -0.185
X:Wurban -0.187 -0.736  0.289
       X                  W Test Estimate Std. Error t value
1     -1 0.0451892102738553        0.1820     0.2483  0.8039
2      0 -0.152553682044491        0.1562    -0.9766  0.3288
3      1 -0.350285976436759        0.2450    -1.4298  0.1528
4 sstest -0.438054016500106        0.1095    -3.9987  0.0001
5 sstest -0.635779394026394        0.1009    -6.3039  0.0000

The p-value of the simple slope cannot be identified in that package, so I found some articles introducing to a website(http://www.quantpsy.org/interact/hlm2.htm) and used the calculator. However, SE, z and p were "NaN" at simple intercepts and slopes at conditional values of w at w1(2).
I don't know what caused this. Can I ask for help?

Y and X are binary data and X is scaled. W is a two-level factor type.

    CASE 3 TWO-WAY INTERACTION SIMPLE SLOPES OUTPUT

Your Input
========================================================
  w1(1)       = 0
  w1(2)       = 1
  x1(1)       = -1
  x1(2)       = 1
  Intercept   = -1.07691
  x1 Slope    = -0.71724
  w1 Slope    = -0.03432
  w1x1 Slope  = -0.56498
  alpha       = 0.05

Asymptotic (Co)variances
========================================================
  var(g00) 0.01709818
  var(g10) 0.05253264
  var(g01) 0.03291322
  var(g11) 0.10903864
  cov(g00,g01) -0.726
  cov(g10,g11) -0.694
  cov(g00,g10) -0.458
  cov(g01,g11) -0.378

Region of Significance on w (level-2 predictor)
========================================================
  w1 at lower bound of region = -0.0508
  w1 at upper bound of region = 61.634
  (simple slopes are significant *inside* this region.)

Simple Intercepts and Slopes at Conditional Values of w
========================================================
  At w1(1)...
    simple intercept = -1.0769(0.1308), z=-8.2358, p=0
    simple slope     = -0.7172(0.2292), z=-3.1293, p=0.0018
  At w1(2)...
    simple intercept = -1.1112(NaN), z=NaN, p=NaN            # <--- Here
    simple slope     = -1.2822(NaN), z=NaN, p=NaN            # <--- Here

Simple Intercepts and Slopes at Region Boundaries for w
========================================================
  Lower Bound...
    simple intercept = -1.0752(0.3016), z=-3.5652, p=0.0004
    simple slope     = -0.6885(0.3512), z=-1.9607, p=0.0499
  Upper Bound...
    simple intercept = -3.1922(5.9627), z=-0.5354, p=0.5924
    simple slope     = -35.5392(18.1305), z=-1.9602, p=0.05

Region of Significance on x (level-1 predictor)
========================================================
  x1 at lower bound of region = 0.0426
  x1 at upper bound of region = 29.4637
  (simple slopes are significant *inside* this region.)

Simple Intercepts and Slopes at Conditional Values of x
========================================================
  At x1(1)...
    simple intercept = -0.3597(0.9928), z=-0.3623, p=0.7171
    simple slope     = 0.5307(0.9476), z=0.56, p=0.5755
  At x1(2)...
    simple intercept = -1.7941(NaN), z=NaN, p=NaN
    simple slope     = -0.5993(NaN), z=NaN, p=NaN

Simple Intercepts and Slopes at Region Boundaries for x
========================================================
  Lower Bound...
    simple intercept = -1.1075(NaN), z=NaN, p=NaN
    simple slope     = -0.0584(0.0301), z=-1.9404, p=0.0524
  Upper Bound...
    simple intercept = -22.2095(4.3165), z=-5.1452, p=0
    simple slope     = -16.6807(8.5098), z=-1.9602, p=0.05

Points to Plot
=======================================================
  Line for w1(1):  From {x1=-1, Y=-0.3597} to {x1=1, Y=-1.7941}
  Line for w1(2):  From {x1=-1, Y=0.171} to {x1=1, Y=-2.3934}

I found this website(https://groups.google.com/g/lavaan/c/lyjF4JZAgBk) and set 100000 at df_int and df_slp. But the result of "simple intercepts and slopes at conditional values of w at w1(2)" didn't change.


来源: stackexchange

问:
Getting error when trying to map entity class to database
Getting error to 'tbl_employees','id','name','age','location','email',department' (Cannot resolve column 'location' ). I don't understanding why I am getting this error.

ContentLicense: CC BY-SA 4.0


问:
How is Argo resourceDuration for CPU and memory calculated
I have an argo workflow with a single step where the following resources defined:

```<code>        resources:
          limits:
            cpu: "6"
          requests:
            cpu: "3"
            memory: 120Mi
</code>```

After the workflow is executed and has completed successfully, I retrieved the run specifications, where the time duration for each pod and resource usage for CPU and memory  can be found:

```<code>status:
  artifactRepositoryRef:
    artifactRepository:
      archiveLogs: true
    configMap: artifact-repositories
    key: default-v1
    namespace: argo
  conditions:
  - status: "False"
    type: PodRunning
  - status: "True"
    type: Completed
  finishedAt: "2022-12-18T11:13:25Z"
  nodes:
    test-cpu-usageszprm:
      children:
      - test-cpu-usageszprm-4131026553
      displayName: test-cpu-usageszprm
      finishedAt: "2022-12-18T11:13:25Z"
      id: test-cpu-usageszprm
      name: test-cpu-usageszprm
      phase: Succeeded
      progress: 1/1
      resourcesDuration:
        cpu: 173
        memory: 79
      startedAt: "2022-12-18T11:12:30Z"
      templateName: main
      templateScope: local/test-cpu-usageszprm
      type: Retry
    test-cpu-usageszprm-1944147306:
      boundaryID: test-cpu-usageszprm-4131026553
      children:
      - test-cpu-usageszprm-2680509841
      displayName: step1
      finishedAt: "2022-12-18T11:13:25Z"
      id: test-cpu-usageszprm-1944147306
      name: test-cpu-usageszprm(0).step1
      outputs:
        artifacts:
        - name: main-logs
          s3:
            key: test-cpu-usageszprm/test-cpu-usageszprm-2680509841/main.log
        exitCode: "0"
      phase: Succeeded
      progress: 1/1
      resourcesDuration:
        cpu: 173
        memory: 79
      startedAt: "2022-12-18T11:12:30Z"
      templateName: step1
      templateScope: local/test-cpu-usageszprm
      type: Retry
    test-cpu-usageszprm-2680509841:
      boundaryID: test-cpu-usageszprm-4131026553
      displayName: step1(0)
      finishedAt: "2022-12-18T11:13:15Z"
      hostNodeName: center03-blade06
      id: test-cpu-usageszprm-2680509841
      name: test-cpu-usageszprm(0).step1(0)
      outputs:
        artifacts:
        - name: main-logs
          s3:
            key: test-cpu-usageszprm/test-cpu-usageszprm-2680509841/main.log
        exitCode: "0"
      phase: Succeeded
      progress: 1/1
      resourcesDuration:
        cpu: 173
        memory: 79
      startedAt: "2022-12-18T11:12:30Z"
      templateName: step1
      templateScope: local/test-cpu-usageszprm
      type: Pod
    test-cpu-usageszprm-4131026553:
      children:
      - test-cpu-usageszprm-1944147306
      displayName: test-cpu-usageszprm(0)
      finishedAt: "2022-12-18T11:13:25Z"
      id: test-cpu-usageszprm-4131026553
      name: test-cpu-usageszprm(0)
      outboundNodes:
      - test-cpu-usageszprm-2680509841
      phase: Succeeded
      progress: 1/1
      resourcesDuration:
        cpu: 173
        memory: 79
      startedAt: "2022-12-18T11:12:30Z"
      templateName: main
      templateScope: local/test-cpu-usageszprm
      type: DAG
  phase: Succeeded
  progress: 1/1
  resourcesDuration:
    cpu: 173
    memory: 79
  startedAt: "2022-12-18T11:12:30Z"
</code>```

Knowing that resources for CPU and memory are set for each pod, I would like to know how resourceDuration CPU (173) and memory (79) are calculated.

I found this document (https://argoproj.github.io/argo-workflows/resource-duration/#example) which describes the calculation for the resourceDuration for CPU and memory however I am not able to get 173, and 79 for cpu and memory reosurce duration respectively based on the pods time duration and resource limits and requests.

Does anyone know how resourceDuration is calculated?

Body:
I have an argo workflow with a single step where the following resources defined:

        resources:
          limits:
            cpu: "6"
          requests:
            cpu: "3"
            memory: 120Mi

After the workflow is executed and has completed successfully, I retrieved the run specifications, where the time duration for each pod and resource usage for CPU and memory  can be found:

status:
  artifactRepositoryRef:
    artifactRepository:
      archiveLogs: true
    configMap: artifact-repositories
    key: default-v1
    namespace: argo
  conditions:
  - status: "False"
    type: PodRunning
  - status: "True"
    type: Completed
  finishedAt: "2022-12-18T11:13:25Z"
  nodes:
    test-cpu-usageszprm:
      children:
      - test-cpu-usageszprm-4131026553
      displayName: test-cpu-usageszprm
      finishedAt: "2022-12-18T11:13:25Z"
      id: test-cpu-usageszprm
      name: test-cpu-usageszprm
      phase: Succeeded
      progress: 1/1
      resourcesDuration:
        cpu: 173
        memory: 79
      startedAt: "2022-12-18T11:12:30Z"
      templateName: main
      templateScope: local/test-cpu-usageszprm
      type: Retry
    test-cpu-usageszprm-1944147306:
      boundaryID: test-cpu-usageszprm-4131026553
      children:
      - test-cpu-usageszprm-2680509841
      displayName: step1
      finishedAt: "2022-12-18T11:13:25Z"
      id: test-cpu-usageszprm-1944147306
      name: test-cpu-usageszprm(0).step1
      outputs:
        artifacts:
        - name: main-logs
          s3:
            key: test-cpu-usageszprm/test-cpu-usageszprm-2680509841/main.log
        exitCode: "0"
      phase: Succeeded
      progress: 1/1
      resourcesDuration:
        cpu: 173
        memory: 79
      startedAt: "2022-12-18T11:12:30Z"
      templateName: step1
      templateScope: local/test-cpu-usageszprm
      type: Retry
    test-cpu-usageszprm-2680509841:
      boundaryID: test-cpu-usageszprm-4131026553
      displayName: step1(0)
      finishedAt: "2022-12-18T11:13:15Z"
      hostNodeName: center03-blade06
      id: test-cpu-usageszprm-2680509841
      name: test-cpu-usageszprm(0).step1(0)
      outputs:
        artifacts:
        - name: main-logs
          s3:
            key: test-cpu-usageszprm/test-cpu-usageszprm-2680509841/main.log
        exitCode: "0"
      phase: Succeeded
      progress: 1/1
      resourcesDuration:
        cpu: 173
        memory: 79
      startedAt: "2022-12-18T11:12:30Z"
      templateName: step1
      templateScope: local/test-cpu-usageszprm
      type: Pod
    test-cpu-usageszprm-4131026553:
      children:
      - test-cpu-usageszprm-1944147306
      displayName: test-cpu-usageszprm(0)
      finishedAt: "2022-12-18T11:13:25Z"
      id: test-cpu-usageszprm-4131026553
      name: test-cpu-usageszprm(0)
      outboundNodes:
      - test-cpu-usageszprm-2680509841
      phase: Succeeded
      progress: 1/1
      resourcesDuration:
        cpu: 173
        memory: 79
      startedAt: "2022-12-18T11:12:30Z"
      templateName: main
      templateScope: local/test-cpu-usageszprm
      type: DAG
  phase: Succeeded
  progress: 1/1
  resourcesDuration:
    cpu: 173
    memory: 79
  startedAt: "2022-12-18T11:12:30Z"

Knowing that resources for CPU and memory are set for each pod, I would like to know how resourceDuration CPU (173) and memory (79) are calculated.

I found this document (https://argoproj.github.io/argo-workflows/resource-duration/#example) which describes the calculation for the resourceDuration for CPU and memory however I am not able to get 173, and 79 for cpu and memory reosurce duration respectively based on the pods time duration and resource limits and requests.

Does anyone know how resourceDuration is calculated?


问:
IdentityServer4.Validation.TokenRequestValidator: Invalid authorization code
I am using Identity Server 4 With Microsoft Blazor application. Authentication process works fine in local. But after deploying changes in azure it was working fine before one week. Suddenly it's started giving some errors and stuck on https://websiteurl.com/signin-oidc page. After checking identity server log I found this error

IdentityServer4.Validation.TokenRequestValidator: Invalid authorization code

Some times it's working and some times getting above error. More than 50% of time i am getting above error.

I tried following code generate custom codeVerifier and add before redirecting to identity server.

```<code>if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)

{
    // generate code_verifier
    var codeVerifier = CryptoRandom.CreateUniqueId(32);

    // store codeVerifier for later use
    context.Properties.Items.Remove(CODE_VERIFIER_KEY);
    context.Properties.Items.Add(CODE_VERIFIER_KEY, codeVerifier);

    Logger.Log(LogLevel.Information, CODE_VERIFIER_KEY + ": " + codeVerifier);

    // create code_challenge
    string codeChallenge;
    using (var sha256 = SHA256.Create())
    {
        var challengeBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(codeVerifier));
        codeChallenge = Base64Url.Encode(challengeBytes);
    }

    // add code_challenge and code_challenge_method to request
    context.ProtocolMessage.Parameters.Remove(CODE_CHALLENGE_KEY);
    context.ProtocolMessage.Parameters.Remove(CODE_CHALLENGE_METHOD_KEY);
    Logger.Log(LogLevel.Information, CODE_CHALLENGE_KEY + ": " + codeChallenge);
    context.ProtocolMessage.Parameters.Add(CODE_CHALLENGE_KEY, codeChallenge);
    context.ProtocolMessage.Parameters.Add(CODE_CHALLENGE_METHOD_KEY, "S256");
}
</code>```
```<code>OnAuthorizationCodeReceived = (context) =>
{
    // context.Options.
    //Add claim if they are
    //var claims = new List<Claim> {   new Claim(ClaimTypes.Role, "Provider")  };
    //var appIdentity = new ClaimsIdentity(claims);

    //context.Principal.AddIdentity(appIdentity);

    // only when authorization code is being swapped for tokens
    // only when authorization code is being swapped for tokens

    Logger.Log(LogLevel.Information, "OnAuthorizationCodeReceived - " + context.TokenEndpointRequest.Parameters);

    if (context.TokenEndpointRequest?.GrantType == OpenIdConnectGrantTypes.AuthorizationCode)
    {

        // get stored code_verifier, This if condition is never gets executed
        if (context.Properties.Items.TryGetValue(CODE_VERIFIER_KEY, out var codeVerifier))
        {
            // add code_verifier to token request
            context.TokenEndpointRequest.Parameters.Add(CODE_VERIFIER_KEY, codeVerifier);
        }
    }

    return Task.CompletedTask;
},
</code>```

Body:
I am using Identity Server 4 With Microsoft Blazor application. Authentication process works fine in local. But after deploying changes in azure it was working fine before one week. Suddenly it's started giving some errors and stuck on https://websiteurl.com/signin-oidc page. After checking identity server log I found this error

IdentityServer4.Validation.TokenRequestValidator: Invalid authorization code

Some times it's working and some times getting above error. More than 50% of time i am getting above error.

I tried following code generate custom codeVerifier and add before redirecting to identity server.

if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)

{
    // generate code_verifier
    var codeVerifier = CryptoRandom.CreateUniqueId(32);

    // store codeVerifier for later use
    context.Properties.Items.Remove(CODE_VERIFIER_KEY);
    context.Properties.Items.Add(CODE_VERIFIER_KEY, codeVerifier);

    Logger.Log(LogLevel.Information, CODE_VERIFIER_KEY + ": " + codeVerifier);

    // create code_challenge
    string codeChallenge;
    using (var sha256 = SHA256.Create())
    {
        var challengeBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(codeVerifier));
        codeChallenge = Base64Url.Encode(challengeBytes);
    }

    // add code_challenge and code_challenge_method to request
    context.ProtocolMessage.Parameters.Remove(CODE_CHALLENGE_KEY);
    context.ProtocolMessage.Parameters.Remove(CODE_CHALLENGE_METHOD_KEY);
    Logger.Log(LogLevel.Information, CODE_CHALLENGE_KEY + ": " + codeChallenge);
    context.ProtocolMessage.Parameters.Add(CODE_CHALLENGE_KEY, codeChallenge);
    context.ProtocolMessage.Parameters.Add(CODE_CHALLENGE_METHOD_KEY, "S256");
}

OnAuthorizationCodeReceived = (context) =>
{
    // context.Options.
    //Add claim if they are
    //var claims = new List<Claim> {   new Claim(ClaimTypes.Role, "Provider")  };
    //var appIdentity = new ClaimsIdentity(claims);

    //context.Principal.AddIdentity(appIdentity);

    // only when authorization code is being swapped for tokens
    // only when authorization code is being swapped for tokens

    Logger.Log(LogLevel.Information, "OnAuthorizationCodeReceived - " + context.TokenEndpointRequest.Parameters);

    if (context.TokenEndpointRequest?.GrantType == OpenIdConnectGrantTypes.AuthorizationCode)
    {

        // get stored code_verifier, This if condition is never gets executed
        if (context.Properties.Items.TryGetValue(CODE_VERIFIER_KEY, out var codeVerifier))
        {
            // add code_verifier to token request
            context.TokenEndpointRequest.Parameters.Add(CODE_VERIFIER_KEY, codeVerifier);
        }
    }

    return Task.CompletedTask;
},


问:
Unreal Engine 4.1.2 character starts again when he touches the floor with Blueprints
I want that when my character(actor) touches the floor, he will start from the starting point of the appearance using Blueprints in Unreal Engine 4.1.2

I tried to connect them(what is marked in the picture) but it was impossible

Picture


问:
On form submition websites css shows up on the page
Here is the image

i made this while following https://kit.svelte.dev/docs/form-actions. I don't know what could be wrong. I have searched far and wide even as far as going into svelte discord.. nothing i hope someone can help me

+page.svelte

<form method="POST" action="?/login">

      Email
      <input name="email" type="email">

      Password
      <input name="password" type="password">

    <button>Log in</button>
  </form>

```
<p>+page.server.js</p>
<pre class="lang-js prettyprint-override"><code>import { fail } from '@sveltejs/kit';

/** @type {import('./$types').Actions} */
export const actions = {
    login: async ({ cookies, request }) => {
        const data = await request.formData();
        const email = data.get("email"); // Either username or an email
        const password = data.get("password");

        if (!email) {
            return fail(400, { email, missing: true });
        }
        if (!password) {
            return fail(400, { password, missing: true });
        }

        return { success: true }
    }
  };
</code>```

Body:
Here is the image

i made this while following https://kit.svelte.dev/docs/form-actions. I don't know what could be wrong. I have searched far and wide even as far as going into svelte discord.. nothing i hope someone can help me

+page.svelte

<form method="POST" action="?/login">

      Email
      <input name="email" type="email">

      Password
      <input name="password" type="password">

    <button>Log in</button>
  </form>

+page.server.js

import { fail } from '@sveltejs/kit';

/** @type {import('./$types').Actions} */
export const actions = {
    login: async ({ cookies, request }) => {
        const data = await request.formData();
        const email = data.get("email"); // Either username or an email
        const password = data.get("password");

        if (!email) {
            return fail(400, { email, missing: true });
        }
        if (!password) {
            return fail(400, { password, missing: true });
        }

        return { success: true }
    }
  };


问:
Which huggingface transformer pretrained model is suitable for zeroshot classification
I am trying to train a pre-trained NLP model using a HuggingFace NLP model on my data and then use it for predictions. Both my predict variable, 'status' and predictor variable, 'review' (one column) are strings. While I have about 20000 samples, the number of classes for 'status' are about 1000. These labels are specific sentences with about 1 to 10 word sentences. I have two problems specifically.

Which pre-trained model shall I select for fine training on my data for such a large zero-shot classification.

Even if I build a typical classifier like a BERT (ex:model="facebook/bart-large-mnli"), for each sample it tried to predict probabilities across 1000 classes, which is a huge task for a Windows laptop to handle.

Appreciate inputs.


问:
How to keep the original data size for data links accessed via R
I now need to download the vnp46a2 product and so far I have obtained the link to each piece of data, here is the sample, which can be downloaded by directly clicking on the data. I now want to download these thousand data in bulk via R, but I have a problem that accessing the data link via R returns a data size smaller than the value directly under the browser.

Here is my code:

```<code>library(data.table)
f <- fread("data/LAADS_query.2022-12-18T08_55.csv")
file <- as.character(f$`fileUrls for custom selected`)
links <- as.character(
         paste0("https://ladsweb.modaps.eosdis.nasa.gov",
                 file))
httr::RETRY("GET", links[2])
</code>```

This is the size of the data running in R (red box):

This is the size of the download on the website:

Body:
I now need to download the vnp46a2 product and so far I have obtained the link to each piece of data, here is the sample, which can be downloaded by directly clicking on the data. I now want to download these thousand data in bulk via R, but I have a problem that accessing the data link via R returns a data size smaller than the value directly under the browser.

Here is my code:

library(data.table)
f <- fread("data/LAADS_query.2022-12-18T08_55.csv")
file <- as.character(f$`fileUrls for custom selected`)
links <- as.character(
         paste0("https://ladsweb.modaps.eosdis.nasa.gov",
                 file))
httr::RETRY("GET", links[2])

This is the size of the data running in R (red box):

This is the size of the download on the website:


问:
Calling results out of the defined function in order to show in GUI
I have made a search engine that fetches results from google.com and opens them in the web browser but the thing is that I want the results to be shown in the GUI and then be able to open the specific result .There are some edits that I tried to make but they ended in vain so I have commented them out .Here is the code -->

```<code>import requests,webbrowser
from bs4 import BeautifulSoup
from tkinter import  *

structure=Tk()
structure.geometry("1920x1080")
structure.title("The Cgo Search Engine")
structure.config(background="dark green")
label=Label(structure,text="Cgo Engine",bg="dark green",fg="gold",font=("ComicSans",60,"italic"))
label.pack(side=TOP)
label.place(x=600,y=350)
text=StringVar()

def searches():
        data=requests.get('https://www.google.com/search?q='+text.get())
        soup=BeautifulSoup(data.content,"html.parser")
        result=soup.select(".kCrYT a")
        for ans in result[:6]:
                global search
                search=ans.get("href")
                search=search[7:]
                search=search.split("&")
                print(search)
                webbrowser.open(search[0])
searches()

# def op():
#         bro=webbrowser.open(search)
# op()

label=Label(structure,font=("Times",15,"bold"),text="Enter here to search",bg="dark green",fg="cyan")
label.place(x=510,y=540)
enter=Entry(structure,font=("Times",15,"bold"),textvar=text,width=70,bd=2,bg="white")
enter.place(x=500,y=500)
button=Button(structure,text="Search",font=("Times",15,"bold"),width=10,bd=2,bg="white",command=searches)
button.place(x=1100,y=550)

# lab=Button(structure,font=("ComicSans",15,"bold"),text=f"Your results: {search}",bg="dark green",fg="cyan",command=op)
# lab.place(x=515,y=580)

structure.mainloop()

</code>```

There are some edits that I tried to make but they ended in vain so I have commented them out because I was getting the error that "search" is not defined.

Body:
I have made a search engine that fetches results from google.com and opens them in the web browser but the thing is that I want the results to be shown in the GUI and then be able to open the specific result .There are some edits that I tried to make but they ended in vain so I have commented them out .Here is the code -->

import requests,webbrowser
from bs4 import BeautifulSoup
from tkinter import  *

structure=Tk()
structure.geometry("1920x1080")
structure.title("The Cgo Search Engine")
structure.config(background="dark green")
label=Label(structure,text="Cgo Engine",bg="dark green",fg="gold",font=("ComicSans",60,"italic"))
label.pack(side=TOP)
label.place(x=600,y=350)
text=StringVar()

def searches():
        data=requests.get('https://www.google.com/search?q='+text.get())
        soup=BeautifulSoup(data.content,"html.parser")
        result=soup.select(".kCrYT a")
        for ans in result[:6]:
                global search
                search=ans.get("href")
                search=search[7:]
                search=search.split("&")
                print(search)
                webbrowser.open(search[0])
searches()

# def op():
#         bro=webbrowser.open(search)
# op()

label=Label(structure,font=("Times",15,"bold"),text="Enter here to search",bg="dark green",fg="cyan")
label.place(x=510,y=540)
enter=Entry(structure,font=("Times",15,"bold"),textvar=text,width=70,bd=2,bg="white")
enter.place(x=500,y=500)
button=Button(structure,text="Search",font=("Times",15,"bold"),width=10,bd=2,bg="white",command=searches)
button.place(x=1100,y=550)

# lab=Button(structure,font=("ComicSans",15,"bold"),text=f"Your results: {search}",bg="dark green",fg="cyan",command=op)
# lab.place(x=515,y=580)

structure.mainloop()

There are some edits that I tried to make but they ended in vain so I have commented them out because I was getting the error that "search" is not defined.


问:
I tried graphing in 3d in python but I get multiple errors
I'm trying to graph a 3d function and I'm having a to of trouble with It.
Could you check where the problem is? Especially with the libraries and with the function E

I tried almost everything and I don't see the mistake.

```<code>import mpl_toolkits .mplot3d.axes3d as axes3d
import numpy as np
import matplotlib .pyplot as plt

plt.rcParams.update ({
    "text.usetex": True ,
    "font.family": "serif",
    "font.serif": "Palatino"
})

theta,phi=np.arange (0,np.pi ,0.02) ,np.arange (0 ,2*np.pi ,0.02)
THETA,PHI=np.meshgrid(theta , phi)

E = ((0.63)**2)*np.sin(THETA)*376.73*((np.cos(2.2302)-(np.sin(2.2302))j)/(1.77))*np.cos(np.pi*np.sin(THETA)*np.cos(PHI))*np.cos(np.py*np.sin(THETA)*np.sin(PHI))
#((np.cos(2.2302)-(np.sin(2.2302))j)/(1.77))
fig = plt.figure ()
fig.set_size_inches (w=7,h=4.32)
ax = fig.add_subplot (1,1,1, projection ="3d")
ax.axes.xaxis.set_ticklabels ([])
ax.axes.yaxis.set_ticklabels ([])
plot=ax.plot_surface (THETA, PHI, E,cmap=plt.get_cmap("RdYlGn"),linewidth =0, antialiased =True , alpha =0.6)
ax.set_xlabel ("$THETA$", fontsize = 12, fontweight = "bold")
ax.set_ylabel ("$PHI$", fontsize = 12, fontweight = "bold")
ax.set_zlabel ("$E$", fontsize = 12, fontweight = "bold")
plt.show ()

</code>```

Body:
I'm trying to graph a 3d function and I'm having a to of trouble with It.
Could you check where the problem is? Especially with the libraries and with the function E

I tried almost everything and I don't see the mistake.

import mpl_toolkits .mplot3d.axes3d as axes3d
import numpy as np
import matplotlib .pyplot as plt

plt.rcParams.update ({
    "text.usetex": True ,
    "font.family": "serif",
    "font.serif": "Palatino"
})

theta,phi=np.arange (0,np.pi ,0.02) ,np.arange (0 ,2*np.pi ,0.02)
THETA,PHI=np.meshgrid(theta , phi)

E = ((0.63)**2)*np.sin(THETA)*376.73*((np.cos(2.2302)-(np.sin(2.2302))j)/(1.77))*np.cos(np.pi*np.sin(THETA)*np.cos(PHI))*np.cos(np.py*np.sin(THETA)*np.sin(PHI))
#((np.cos(2.2302)-(np.sin(2.2302))j)/(1.77))
fig = plt.figure ()
fig.set_size_inches (w=7,h=4.32)
ax = fig.add_subplot (1,1,1, projection ="3d")
ax.axes.xaxis.set_ticklabels ([])
ax.axes.yaxis.set_ticklabels ([])
plot=ax.plot_surface (THETA, PHI, E,cmap=plt.get_cmap("RdYlGn"),linewidth =0, antialiased =True , alpha =0.6)
ax.set_xlabel ("$THETA$", fontsize = 12, fontweight = "bold")
ax.set_ylabel ("$PHI$", fontsize = 12, fontweight = "bold")
ax.set_zlabel ("$E$", fontsize = 12, fontweight = "bold")
plt.show ()


问:
how to update the excel formula calculate result ，I use apache poi 5.2.2
```<code>File f = new File("/data/test.xlsx");
InputStream is = new FileInputStream("/data/test.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(is);
XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
OutputStream os = new FileOutputStream(f);
wb.write(os);
os.close();
</code>```

but it doesn't work,when i open my excel,it still notice that do I need to save the excel file,it means that the formula doesn't update ,how to fix this issue?

Body:
File f = new File("/data/test.xlsx");
InputStream is = new FileInputStream("/data/test.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(is);
XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
OutputStream os = new FileOutputStream(f);
wb.write(os);
os.close();

but it doesn't work,when i open my excel,it still notice that do I need to save the excel file,it means that the formula doesn't update ,how to fix this issue?


问:
XML response deserialization problem - WebService
Good morning,

I'm having trouble getting a response using webservice. It seems that the request is fine because on the server side they receive messages.

```<code>ServiceReference1.ServiceClient servClient = new ServiceReference1.ServiceClient();

ServiceReference1.TLampInfo tLampInfo = new ServiceReference1.TLampInfo();
ServiceReference1.TRespons directResponse = new ServiceReference1.TRespons();

tLampInfo.Txt = "Test1234";

directResponse = servClient.SendLamp(tLampInfo); <---- error
</code>```

I get a message then I try to download the response:  "Error in deserializing body of request message for operation 'SendLamp'". What else should I do? How should I use deserialization in this case?

Body:
Good morning,

I'm having trouble getting a response using webservice. It seems that the request is fine because on the server side they receive messages.

ServiceReference1.ServiceClient servClient = new ServiceReference1.ServiceClient();

ServiceReference1.TLampInfo tLampInfo = new ServiceReference1.TLampInfo();
ServiceReference1.TRespons directResponse = new ServiceReference1.TRespons();

tLampInfo.Txt = "Test1234";

directResponse = servClient.SendLamp(tLampInfo); <---- error

I get a message then I try to download the response:  "Error in deserializing body of request message for operation 'SendLamp'". What else should I do? How should I use deserialization in this case?


问:
Using a map() function as a condition
I have two DataFrames, one gets daily new inputs via Id number and gives the related value. The other one corresponds to a "catalog" that lists all existing Ids and outputs the name of the corresponding Id.

So the Output looks like this:

```<code>daily input
    date        id  value
0   2010-03-01  2   57.9
1   2010-10-14  1   79.1
2   2010-12-18  3   0.0

catalog
    name         id
0   aba           1
1   aba-1         2
2   aba-2         3
3   aba           4
4   aba-2         5

</code>```

Now I want to build a function, whose first condition is, which name has the following ID and from this follows further subconditions, in order to return the appropriate value.

```<code>def numfunc (id, date):
     if (id == (map(catalog.set_index("id")["name"])) == "aba-1"):
        if date.dayofweek == 5:
                return 50
     else:
           return 25

df['num']= daily_input.apply(lambda x:numfunc(x['id'],x['date']),axis=1)
</code>```

So I'm only concerned with the first line here if (id == (map(catalog.set_index("id")["name"])) == "B"), whether this can be used that way at all?. When executing this function I get the error message: map() must have at least two arguments.

Goal Output:

```<code>df
    date        id  num
0   2010-03-01  2   25
1   2010-10-14  1   25
2   2010-12-18  3   25

</code>```

Many thanks for your support.

Title: Using a map() function as a condition

Body:
I have two DataFrames, one gets daily new inputs via Id number and gives the related value. The other one corresponds to a "catalog" that lists all existing Ids and outputs the name of the corresponding Id.

So the Output looks like this:

daily input
    date        id  value
0   2010-03-01  2   57.9
1   2010-10-14  1   79.1
2   2010-12-18  3   0.0

catalog
    name         id
0   aba           1
1   aba-1         2
2   aba-2         3
3   aba           4
4   aba-2         5

Now I want to build a function, whose first condition is, which name has the following ID and from this follows further subconditions, in order to return the appropriate value.

def numfunc (id, date):
     if (id == (map(catalog.set_index("id")["name"])) == "aba-1"):
        if date.dayofweek == 5:
                return 50
     else:
           return 25

df['num']= daily_input.apply(lambda x:numfunc(x['id'],x['date']),axis=1)

So I'm only concerned with the first line here if (id == (map(catalog.set_index("id")["name"])) == "B"), whether this can be used that way at all?. When executing this function I get the error message: map() must have at least two arguments.

Goal Output:

df
    date        id  num
0   2010-03-01  2   25
1   2010-10-14  1   25
2   2010-12-18  3   25

Many thanks for your support.


问:
How to call another function to an executing thread?
```<code>import threading
import time

class Test():

    def __init__(self) -> None:
        self.stop_threads = False

    def run(self):

        while True:
            print('thread running')
            time.sleep(5)

            if self.stop_threads:
                break

    def store(self):

        self.t1 = threading.Thread(target = self.run())
        self.t1.start()

    def stop(self):
        self.stop_threads = True
        self.t1.join()
        print('thread killed')
</code>```

When user clicks on the "Run" button, the store() function will execute. There is another button "Stop" which when clicked, the stop() function executes.

GUI:

```<code>from test2 import *
import streamlit as st

obj=Test()

if st.button("Run"):
    obj.store()

if st.button("Stop"):
    obj.stop()

</code>```

But since there is an infinite loop, I am unable to click the "Stop" button.

How can I implement the stop button?

Body:
import threading
import time

class Test():

    def __init__(self) -> None:
        self.stop_threads = False

    def run(self):

        while True:
            print('thread running')
            time.sleep(5)

            if self.stop_threads:
                break

    def store(self):

        self.t1 = threading.Thread(target = self.run())
        self.t1.start()

    def stop(self):
        self.stop_threads = True
        self.t1.join()
        print('thread killed')

When user clicks on the "Run" button, the store() function will execute. There is another button "Stop" which when clicked, the stop() function executes.

GUI:

from test2 import *
import streamlit as st

obj=Test()

if st.button("Run"):
    obj.store()

if st.button("Stop"):
    obj.stop()

But since there is an infinite loop, I am unable to click the "Stop" button.

How can I implement the stop button?


问:
KernelPCA explained variance is (99-100)% for all the features of the dataset
I am trying to perform PCA+LDA on this dataset Structural Protein Sequences.

The problem is that every feature has explained variance at 99-100 % and to keep 95% of the information only 1 principal component is needed.

```<code>X_mean = np.mean(X_train, axis=0)

cov_mat = (X_train - X_mean).T.dot((X_train - X_mean)) / (X_train.shape\[0\]-1)

eig_vals, eig_vecs = np.linalg.eig(cov_mat)

total = sum(eig_vals)
exp_var = \[(i /total)\*100 for i in sorted(eig_vals,reverse=True)\]
sum_exp_var = np.cumsum(exp_var)

sum_exp_var
</code>```

Output

```<code>array([ 99.99891234,  99.99947164,  99.99991711,  99.99999955,
        99.99999999, 100.        , 100.        , 100.        ,
       100.        , 100.        , 100.        , 100.        ,
       100.        , 100.        ])
</code>```

I am trying to reduce the dimensionality from 15 to maybe 10 features.

The dataset's categorical features are encoded with ordinalencoder() and scaled with standardscaler()

Any ideas on why every feature is so significant ? Are there datasets that KernelPCA can not yield results ?

Body:
I am trying to perform PCA+LDA on this dataset Structural Protein Sequences.

The problem is that every feature has explained variance at 99-100 % and to keep 95% of the information only 1 principal component is needed.

X_mean = np.mean(X_train, axis=0)

cov_mat = (X_train - X_mean).T.dot((X_train - X_mean)) / (X_train.shape\[0\]-1)

eig_vals, eig_vecs = np.linalg.eig(cov_mat)

total = sum(eig_vals)
exp_var = \[(i /total)\*100 for i in sorted(eig_vals,reverse=True)\]
sum_exp_var = np.cumsum(exp_var)

sum_exp_var

Output

array([ 99.99891234,  99.99947164,  99.99991711,  99.99999955,
        99.99999999, 100.        , 100.        , 100.        ,
       100.        , 100.        , 100.        , 100.        ,
       100.        , 100.        ])

I am trying to reduce the dimensionality from 15 to maybe 10 features.

The dataset's categorical features are encoded with ordinalencoder() and scaled with standardscaler()

Any ideas on why every feature is so significant ? Are there datasets that KernelPCA can not yield results ?


问:
Solr java.lang.OutOfMemoryError
I'm running Solr on Windows 11, using the following command:

```<code>java -Dc=core_1 -Drecursive -Dauto -jar example\exampledocs\post.jar D:\*
     -Xms8g -Xmx16g -XX:NewRatio=1 -XX:-UseAdaptiveSizePolicy -Xss16m
</code>```

The machine I am using has 256GB ECC RAM, running java 19.0.1

I'm trying to index about 10TB of files, but after running for a certain amount of time, I get the following error:

```<code>SimplePostTool: WARNING: Response: {
  "responseHeader":{
    "status":500,
    "QTime":22},
  "error":{
    "metadata":[
      "error-class","org.apache.solr.common.SolrException",
      "root-error-class","java.lang.OutOfMemoryError"],
    "msg":"Server error writing document id D:\myfile.pdf to the index",
    "trace":"org.apache.solr.common.SolrException: Server error writing document id D:\
</code>```

I have tried playing with the initial memory settings, such as adding -Xmx1024m recommended here, but to no avail.

Title: Solr java.lang.OutOfMemoryError

Body:
I'm running Solr on Windows 11, using the following command:

java -Dc=core_1 -Drecursive -Dauto -jar example\exampledocs\post.jar D:\*
     -Xms8g -Xmx16g -XX:NewRatio=1 -XX:-UseAdaptiveSizePolicy -Xss16m

The machine I am using has 256GB ECC RAM, running java 19.0.1

I'm trying to index about 10TB of files, but after running for a certain amount of time, I get the following error:

SimplePostTool: WARNING: Response: {
  "responseHeader":{
    "status":500,
    "QTime":22},
  "error":{
    "metadata":[
      "error-class","org.apache.solr.common.SolrException",
      "root-error-class","java.lang.OutOfMemoryError"],
    "msg":"Server error writing document id D:\myfile.pdf to the index",
    "trace":"org.apache.solr.common.SolrException: Server error writing document id D:\

I have tried playing with the initial memory settings, such as adding -Xmx1024m recommended here, but to no avail.


问:
How do I undo a expo project that I build locally using npx expo run:android?
How do I remove the local build that I accidentally created using npx expo run:android?

So I accidentally ran a npx expo run:android in my project which created a local build. However, I am perfectly happy with using the development server and bundling my project everytime. Since the local build is taking up a lot of space how do I revert back? I want to remove everything related to the local build and just use the development server.


问:
Django How to Feed Images channel from Server to Client Real Time? Http or WebSocket
I have a project like i,e tiktok , user swipe the screen left and right , to load new images from Backend server

I m confused about this architecture , whether :

Should call HTTP request on every swipe   i.e Demerit- This will create congestion and there will be a loader on every swipe ,

Or go with the Websockets ie Django Channels

Search for this architecture


问:
Null values inserting as empty string in Snowflake
I am trying to load the data into the Snowflake native table using ETL tool informatica cloud (IICS) and Azure Data Factory (ADF).
My source is Redshift table which have varchar columns containing both null values as well as empty string. Many times, I see that null values in the source are inserted as empty string in the varchar columns in Snowflake table.

When I tried to match the data and ran the following query in Redshift and Snowflake:

select count(1) from my_table where str_column1 is null

I can clearly see the difference. I have to use this table in some views in which I have given some filters based on null and some based on empty values.

I want empty string as empty and null value as null in my target table.
Can anyone suggest me the best way to tackle this problem?


问:
How Can I add trading view chart in my react website with custom data?
I want to use a trading view chart in my react project with my custom data. How can I add this?

I want a trading view chart like this.
chart demo


问:
Recordset is not updateable when using group by in query with checkbox
The checkbox on my continuous form cannot be checked, the recordset is not updateable, because I'm using group by (sum). The reason for this: It is summing up the value of a column (to show a total) if they have the same ID. So the checkbox can't be marked because it's not a single record.

```<code>SELECT DISTINCTROW WorkTable.ItemCode, Sum(WorkTable.QuantityInventory) AS SumOfQuantityInventory,
WorkTable.ItemName, WorkTable.CheckBox
FROM WorkTable
GROUP BY WorkTable.ItemCode, WorkTable.ItemName, WorkTable.CheckBox
HAVING (((Sum(WorkTable.QuantityInventory)) Is Not Null) AND ((WorkTable.CheckBox)=False));
</code>```

Can I make the checkbox clickable by adjusting my query, or my second idea, to have the checkbox event: On Click, and make a VBA that checks all checkbox if they have the same ID, but I have no clue where to begin on this.

The reason for this is, when the checkbox is marked, the record won't show up next time in the continuous form, or are there any better ways to do it?

I have looked at many other examples and have managed to bypass this by adding a subform in the main form, which is also a continuous form. In that subform it shows all records just like the main one, but the difference is, they are not sorted by sum and they are not grouped, so you can see records with the same ID several times and have to mark each checkbox in order to have that entire ID marked. But this takes a while and is a hassle as compared to a single checkbox that marks all of the records with the same ID.

Body:
The checkbox on my continuous form cannot be checked, the recordset is not updateable, because I'm using group by (sum). The reason for this: It is summing up the value of a column (to show a total) if they have the same ID. So the checkbox can't be marked because it's not a single record.

SELECT DISTINCTROW WorkTable.ItemCode, Sum(WorkTable.QuantityInventory) AS SumOfQuantityInventory,
WorkTable.ItemName, WorkTable.CheckBox
FROM WorkTable
GROUP BY WorkTable.ItemCode, WorkTable.ItemName, WorkTable.CheckBox
HAVING (((Sum(WorkTable.QuantityInventory)) Is Not Null) AND ((WorkTable.CheckBox)=False));

Can I make the checkbox clickable by adjusting my query, or my second idea, to have the checkbox event: On Click, and make a VBA that checks all checkbox if they have the same ID, but I have no clue where to begin on this.

The reason for this is, when the checkbox is marked, the record won't show up next time in the continuous form, or are there any better ways to do it?

I have looked at many other examples and have managed to bypass this by adding a subform in the main form, which is also a continuous form. In that subform it shows all records just like the main one, but the difference is, they are not sorted by sum and they are not grouped, so you can see records with the same ID several times and have to mark each checkbox in order to have that entire ID marked. But this takes a while and is a hassle as compared to a single checkbox that marks all of the records with the same ID.


问:
is there any method to deal with that problem
This error occurs while running app on mobile. All other functions are working, but when there is a click on a button the app crashes and the following error appears.

```<code>java.lang.NoSuchMethodError: No virtual method setDefaults(I)V in class Lcom/google/firebase/remoteconfig/FirebaseRemoteConfig; or its super classes (declaration of 'com.google.firebase.remoteconfig.FirebaseRemoteConfig' appears in /data/app/~~Q9836TULU-w8mOXN5-bEbw==/com.example.languagetranslator-TjdoPE1IvsvQKkgl6XTCVw==/base.apk!classes4.dex)
        at com.google.firebase.ml.naturallanguage.translate.internal.zzy$zzb.<init>(com.google.firebase:firebase-ml-natural-language-translate@@22.0.2:3)
        at com.google.firebase.ml.naturallanguage.translate.zzj.create(com.google.firebase:firebase-ml-natural-language-translate@@22.0.2:2)
        at com.google.firebase.components.ComponentRuntime.lambda$discoverComponents$0$com-google-firebase-components-ComponentRuntime(ComponentRuntime.java:140)
        at com.google.firebase.components.ComponentRuntime$$ExternalSyntheticLambda1.get(Unknown Source:4)
        at com.google.firebase.components.Lazy.get(Lazy.java:53)
        at com.google.firebase.components.AbstractComponentContainer.get(AbstractComponentContainer.java:27)
        at com.google.firebase.components.ComponentRuntime.get(ComponentRuntime.java:46)
        at com.google.firebase.components.RestrictedComponentContainer.get(RestrictedComponentContainer.java:89)
        at com.google.firebase.ml.naturallanguage.translate.zzm.create(com.google.firebase:firebase-ml-natural-language-translate@@22.0.2:4)
        at com.google.firebase.components.ComponentRuntime.lambda$discoverComponents$0$com-google-firebase-components-ComponentRuntime(ComponentRuntime.java:140)
        at com.google.firebase.components.ComponentRuntime$$ExternalSyntheticLambda1.get(Unknown Source:4)
        at com.google.firebase.components.Lazy.get(Lazy.java:53)
        at com.google.firebase.components.AbstractComponentContainer.get(AbstractComponentContainer.java:27)
        at com.google.firebase.components.ComponentRuntime.get(ComponentRuntime.java:46)
        at com.google.firebase.components.RestrictedComponentContainer.get(RestrictedComponentContainer.java:89)
        at com.google.firebase.ml.naturallanguage.translate.zzk.create(com.google.firebase:firebase-ml-natural-language-translate@@22.0.2:10)
        at com.google.firebase.components.ComponentRuntime.lambda$discoverComponents$0$com-google-firebase-components-ComponentRuntime(ComponentRuntime.java:140)
        at com.google.firebase.components.ComponentRuntime$$ExternalSyntheticLambda1.get(Unknown Source:4)
        at com.google.firebase.components.Lazy.get(Lazy.java:53)
        at com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage.getTranslator(com.google.firebase:firebase-ml-natural-language@@22.0.1:8)
        at com.example.languagetranslator.MainActivity.translatetext(MainActivity.java:148)
        at com.example.languagetranslator.MainActivity.access$000(MainActivity.java:34)
        at com.example.languagetranslator.MainActivity$3.onClick(MainActivity.java:106)
        at android.view.View.performClick(View.java:7506)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1219)
        at android.view.View.performClickInternal(View.java:7483)
        at android.view.View.-$$Nest$mperformClickInternal(Unknown Source:0)
        at android.view.View$PerformClick.run(View.java:29334)
        at android.os.Handler.handleCallback(Handler.java:942)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7872)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)

</code>```

I added some dependencies and updated all of them, but still I get the same error. What may I overlook?

Body:
This error occurs while running app on mobile. All other functions are working, but when there is a click on a button the app crashes and the following error appears.

java.lang.NoSuchMethodError: No virtual method setDefaults(I)V in class Lcom/google/firebase/remoteconfig/FirebaseRemoteConfig; or its super classes (declaration of 'com.google.firebase.remoteconfig.FirebaseRemoteConfig' appears in /data/app/~~Q9836TULU-w8mOXN5-bEbw==/com.example.languagetranslator-TjdoPE1IvsvQKkgl6XTCVw==/base.apk!classes4.dex)
        at com.google.firebase.ml.naturallanguage.translate.internal.zzy$zzb.<init>(com.google.firebase:firebase-ml-natural-language-translate@@22.0.2:3)
        at com.google.firebase.ml.naturallanguage.translate.zzj.create(com.google.firebase:firebase-ml-natural-language-translate@@22.0.2:2)
        at com.google.firebase.components.ComponentRuntime.lambda$discoverComponents$0$com-google-firebase-components-ComponentRuntime(ComponentRuntime.java:140)
        at com.google.firebase.components.ComponentRuntime$$ExternalSyntheticLambda1.get(Unknown Source:4)
        at com.google.firebase.components.Lazy.get(Lazy.java:53)
        at com.google.firebase.components.AbstractComponentContainer.get(AbstractComponentContainer.java:27)
        at com.google.firebase.components.ComponentRuntime.get(ComponentRuntime.java:46)
        at com.google.firebase.components.RestrictedComponentContainer.get(RestrictedComponentContainer.java:89)
        at com.google.firebase.ml.naturallanguage.translate.zzm.create(com.google.firebase:firebase-ml-natural-language-translate@@22.0.2:4)
        at com.google.firebase.components.ComponentRuntime.lambda$discoverComponents$0$com-google-firebase-components-ComponentRuntime(ComponentRuntime.java:140)
        at com.google.firebase.components.ComponentRuntime$$ExternalSyntheticLambda1.get(Unknown Source:4)
        at com.google.firebase.components.Lazy.get(Lazy.java:53)
        at com.google.firebase.components.AbstractComponentContainer.get(AbstractComponentContainer.java:27)
        at com.google.firebase.components.ComponentRuntime.get(ComponentRuntime.java:46)
        at com.google.firebase.components.RestrictedComponentContainer.get(RestrictedComponentContainer.java:89)
        at com.google.firebase.ml.naturallanguage.translate.zzk.create(com.google.firebase:firebase-ml-natural-language-translate@@22.0.2:10)
        at com.google.firebase.components.ComponentRuntime.lambda$discoverComponents$0$com-google-firebase-components-ComponentRuntime(ComponentRuntime.java:140)
        at com.google.firebase.components.ComponentRuntime$$ExternalSyntheticLambda1.get(Unknown Source:4)
        at com.google.firebase.components.Lazy.get(Lazy.java:53)
        at com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage.getTranslator(com.google.firebase:firebase-ml-natural-language@@22.0.1:8)
        at com.example.languagetranslator.MainActivity.translatetext(MainActivity.java:148)
        at com.example.languagetranslator.MainActivity.access$000(MainActivity.java:34)
        at com.example.languagetranslator.MainActivity$3.onClick(MainActivity.java:106)
        at android.view.View.performClick(View.java:7506)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1219)
        at android.view.View.performClickInternal(View.java:7483)
        at android.view.View.-$$Nest$mperformClickInternal(Unknown Source:0)
        at android.view.View$PerformClick.run(View.java:29334)
        at android.os.Handler.handleCallback(Handler.java:942)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7872)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)

I added some dependencies and updated all of them, but still I get the same error. What may I overlook?


问:
PowerApps-Canvas: Unable to use DependsOn functionality of the DropDown component
I have a 3 tables as following:

Over here, In canvas app, I wanted to set a dependant drop down fields, where based on a selected location, Bin dropdown should be filtered.

I have tried below PowerFx function but it seems not working.

```<code>Filter('Item Master', Bin.'Bin Name' = First(Filter('Item Master',"Warehouse" = Location.'Location Name')).Bin.'Bin Name')
</code>```

The formula does not show any error, but just a warning as below on 1st equal sign and last :
Delegation warning. The filter part of this formula might not work correctly on large data sets.

Any suggestion for this issue? How can I make this "Bin" dependant on the selected "Location"?

EDIT 1:

I have found some related videos but seems it does not fulfil my requirements as it supports only single lookup field.

Here's the reference for it: https://www.youtube.com/watch?v=IWEQwGLcW7Q

Body:
I have a 3 tables as following:

Over here, In canvas app, I wanted to set a dependant drop down fields, where based on a selected location, Bin dropdown should be filtered.

I have tried below PowerFx function but it seems not working.

Filter('Item Master', Bin.'Bin Name' = First(Filter('Item Master',"Warehouse" = Location.'Location Name')).Bin.'Bin Name')

The formula does not show any error, but just a warning as below on 1st equal sign and last :
Delegation warning. The filter part of this formula might not work correctly on large data sets.

Any suggestion for this issue? How can I make this "Bin" dependant on the selected "Location"?

EDIT 1:

I have found some related videos but seems it does not fulfil my requirements as it supports only single lookup field.

Here's the reference for it: https://www.youtube.com/watch?v=IWEQwGLcW7Q


问:
Gluon mobile "Missing CAP cache" when building for Android
I'm testing the gluon mobile library with a basic template project provided with the Gluon plugin for IntelliJ.

The sample app run without any problem but when building for a native app on Android, I have the following error :

Missing CAP cache value for: NativeCodeInfo:AArch64LibCHelperDirectives:StructInfo:CPUFeatures:StructFieldInfo:fDMB_ATOMICS

Launching several times, the problem appears for different values : fDMB_ATOMICS,

NativeCodeInfo:AArch64LibCHelperDirectives:StructInfo:CPUFeatures:StructFieldInfo:fDMB_ATOMICS

NativeCodeInfo:PosixDirectives:ConstantInfo:CLOCK_THREAD_CPUTIME_ID

I am beginner using gluon so I think some library is missing but I have no idea what is it...

Does someone have any idea?

Thank you for advance.


问:
In Pandas dataframe, how to add metadata to a column?
I am creating my own module for calculation of price indicators, and I would like to add metadata to a column of a dataframe, so each column will have unique metadata.

It is important for me since I have multiple functions and I can recalculate output of one function using another function, also I use some functions to do calculations inside the function I am calling.

For example:

```<code>def average_day_range(price_df: PandasDataFrame, n: int=14, calculation_tool: int=0):
    '''
    0 - SMA, 1 - EMA, 2 - WMA, 3 - EWMA, 4 - VWMA,  5 - ALMA, 6 - LSMA, 7 - HULL MA
    :param price_df:
    :param n:
    :param calculation_tool:
    :return:
    '''
    if calculation_tool not in range(0, 8, 1):
        calculation_tool = 0
    else:
        pass
    function_dict = {
        0: {
            "func": sma,
            "name": "SMA"
        },
        1: {
            "func": ema,
            "name": "EMA"
        },
        2: {
            "func": wma,
            "name": "WMA"
        },
        3: {
            "func": ewma,
            "name": "EWMA"
        },
        4: {
            "func": volume_weighted_moving_average,
            "name": "VWMA"
        },
        5: {
            "func": arnaud_legoux_ma,
            "name": "ALMA"
        },
        6: {
            "func": least_squares_moving_average,
            "name": "LSMA"
        },
        7: {
            "func": hull_ma,
            "name": "HULL_MA"
        },
    }

    function, name = function_dict[calculation_tool]["func"], function_dict[calculation_tool]["name"]
    high_var = function(price_df=price_df, input_mode=3, n=n, from_price=True)
    low_var = function(price_df=price_df, input_mode=4, n=n, from_price=True)
    adr = high_var[f'{name}_{n}'] - low_var[f'{name}_{n}']
    adr.rename(columns={0: f'Average Day Range {name}{n}'}, inplace=True)
    return adr
</code>```

As you see I can use different functions to do calculations inside one function, and then if I would like to I can recalculate the output using different functions.

So I want to avoid naming columns like func1 with func2 from func3 etc, because it is very confusing not to mention the horrendously long column names. Also, I don't want to store multiple dataframes separately but to concatenate the main dataframe with raw data and the dataframe with calculated output.

So let's say I have a dataframe with such columns datetime, open, close, high, low, volume, indicator1, indicator2.

How do I add metadata to each column in dataframe separately so I will be able to easily identify the column I am looking at? I would like to metadata to contain informations such as the source of the calculation (if it was open, high close or low or something else) and other.
(Identifying columns when there are only a couple of them is easy, but if I have ~50 columns, with names that are very similar to each other, then anybody who is looking at it will be just confused).

If adding the metadata to each column is not possible, is there maybe a way to connect a .json file to each column? If I have a wrong thinking process, is there another way to do what I want to do?

Body:
I am creating my own module for calculation of price indicators, and I would like to add metadata to a column of a dataframe, so each column will have unique metadata.

It is important for me since I have multiple functions and I can recalculate output of one function using another function, also I use some functions to do calculations inside the function I am calling.

For example:

def average_day_range(price_df: PandasDataFrame, n: int=14, calculation_tool: int=0):
    '''
    0 - SMA, 1 - EMA, 2 - WMA, 3 - EWMA, 4 - VWMA,  5 - ALMA, 6 - LSMA, 7 - HULL MA
    :param price_df:
    :param n:
    :param calculation_tool:
    :return:
    '''
    if calculation_tool not in range(0, 8, 1):
        calculation_tool = 0
    else:
        pass
    function_dict = {
        0: {
            "func": sma,
            "name": "SMA"
        },
        1: {
            "func": ema,
            "name": "EMA"
        },
        2: {
            "func": wma,
            "name": "WMA"
        },
        3: {
            "func": ewma,
            "name": "EWMA"
        },
        4: {
            "func": volume_weighted_moving_average,
            "name": "VWMA"
        },
        5: {
            "func": arnaud_legoux_ma,
            "name": "ALMA"
        },
        6: {
            "func": least_squares_moving_average,
            "name": "LSMA"
        },
        7: {
            "func": hull_ma,
            "name": "HULL_MA"
        },
    }

    function, name = function_dict[calculation_tool]["func"], function_dict[calculation_tool]["name"]
    high_var = function(price_df=price_df, input_mode=3, n=n, from_price=True)
    low_var = function(price_df=price_df, input_mode=4, n=n, from_price=True)
    adr = high_var[f'{name}_{n}'] - low_var[f'{name}_{n}']
    adr.rename(columns={0: f'Average Day Range {name}{n}'}, inplace=True)
    return adr

As you see I can use different functions to do calculations inside one function, and then if I would like to I can recalculate the output using different functions.

So I want to avoid naming columns like func1 with func2 from func3 etc, because it is very confusing not to mention the horrendously long column names. Also, I don't want to store multiple dataframes separately but to concatenate the main dataframe with raw data and the dataframe with calculated output.

So let's say I have a dataframe with such columns datetime, open, close, high, low, volume, indicator1, indicator2.

How do I add metadata to each column in dataframe separately so I will be able to easily identify the column I am looking at? I would like to metadata to contain informations such as the source of the calculation (if it was open, high close or low or something else) and other.
(Identifying columns when there are only a couple of them is easy, but if I have ~50 columns, with names that are very similar to each other, then anybody who is looking at it will be just confused).

If adding the metadata to each column is not possible, is there maybe a way to connect a .json file to each column? If I have a wrong thinking process, is there another way to do what I want to do?


问:
How do I deal with spaces in filenames for a wildcard parameter in a bash script?
I am writing a bash script that will take a list of filenames as an argument. It will generally be used with wildcards.

Right now, the script just prints the files:

```<code>#!/bin/bash
for file in $@
do
    echo "Processing $file"
done
</code>```

The problem is when using a wildcard, and the file list has filenames that contain spaces. For example, if I have two files file1.jpg and file two.jpg, and I run ./myscript.sh *.jpg my output is

```<code>Processing file1.jpg
Processing file
Processing two.jpg
</code>```

How do I make it recognize "file two.jpg" as one thing instead of two things? Note that the wildcard could be just * and files are not guaranteed to have an extension.

I am running this on a Mac, using GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin21)

Body:
I am writing a bash script that will take a list of filenames as an argument. It will generally be used with wildcards.

Right now, the script just prints the files:

#!/bin/bash
for file in $@
do
    echo "Processing $file"
done

The problem is when using a wildcard, and the file list has filenames that contain spaces. For example, if I have two files file1.jpg and file two.jpg, and I run ./myscript.sh *.jpg my output is

Processing file1.jpg
Processing file
Processing two.jpg

How do I make it recognize "file two.jpg" as one thing instead of two things? Note that the wildcard could be just * and files are not guaranteed to have an extension.

I am running this on a Mac, using GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin21)


问:
wordpress css code for cover image problem
I am trying to set cover photo in wordpress home page.
Desktop version works fine, but tablet and mobile version just crop image in viewer, mobile even more that in tablet.
I want to have full size photo on all devices.
I am using astra wordpress plugin.
Is there css code that i can insert to get same proportion on all devices?

Thanks,
B.

I tried code i found online

```<code>html {
   min-height: 100%;
   background-image: url(image.jpg);
   background-size: cover;
   background-repeat: no-repeat;
   background-position: center center;
}

</code>```

and it works for desktop version, but tablet and mobile still shrink.

Body:
I am trying to set cover photo in wordpress home page.
Desktop version works fine, but tablet and mobile version just crop image in viewer, mobile even more that in tablet.
I want to have full size photo on all devices.
I am using astra wordpress plugin.
Is there css code that i can insert to get same proportion on all devices?

Thanks,
B.

I tried code i found online

html {
   min-height: 100%;
   background-image: url(image.jpg);
   background-size: cover;
   background-repeat: no-repeat;
   background-position: center center;
}

and it works for desktop version, but tablet and mobile still shrink.


问:
Facebook Pixel PageView run another event on link with scroll
When I go to example.com events are fine, but when I click on scroll down I have another pageview without refreshing a page. Here is my code:

```<code>fbq( 'track', 'PageView', {}, {eventID: '1234'} );
</code>```

I think it should run once because it is the same page. Strange is that the second event haven't eventID. Why is that happening and what should i do to make it work once?

Body:
When I go to example.com events are fine, but when I click on scroll down I have another pageview without refreshing a page. Here is my code:

fbq( 'track', 'PageView', {}, {eventID: '1234'} );

I think it should run once because it is the same page. Strange is that the second event haven't eventID. Why is that happening and what should i do to make it work once?


问:
Part of UserFrom Combox items text is not showing when clicking on dropdown button
I have a combobox with a list of Right-To-Left language Items. As it appears in the picture my problem is that when I click on combobox drop-down button almost 2 first letters of each item is not showing.


问:
Can i write dropdown menu without using select element
I want to know if its okay to use
 and <button> elements instead of using <select> and <option> in React and make the <button> elements controlled.
I want to implement that for styling purposes since <select> and <option> is limited for styling.

```<code>import React, { useRef } from "react";

export const FiltersDropdown = () => {

    const currentFilter = useRef('All');

    const handleSelectFilter = (e) => {
        currentFilter.current =  e.target.value;
    }

    return (
        <div className='filters-dropdown'>
            <div className="select-header">
                <p>Filter by Region</p>
                <img src="../images/chevron-down-sharp.svg" alt='dropdown-arrow'></img>
            </div>
            <div className="select-body">
                <button value='All' className="select-option" onClick={handleSelectFilter}>All</button>
                <button value='Africa' className="select-option" onClick={handleSelectFilter}>Africa</button>
                <button value='America' className="select-option" onClick={handleSelectFilter}>America</button>
                <button value='Asia' className="select-option" onClick={handleSelectFilter}>Asia</button>
                <button value='Europe' className="select-option" onClick={handleSelectFilter}>Europe</button>
                <button value='Oceania' className="select-option" onClick={handleSelectFilter}>Oceania</button>
            </div>
        </div>
    )
}
</code>```

Body:
I want to know if its okay to use
 and <button> elements instead of using <select> and <option> in React and make the <button> elements controlled.
I want to implement that for styling purposes since <select> and <option> is limited for styling.

import React, { useRef } from "react";

export const FiltersDropdown = () => {

    const currentFilter = useRef('All');

    const handleSelectFilter = (e) => {
        currentFilter.current =  e.target.value;
    }

    return (

Filter by Region

                <button value='All' className="select-option" onClick={handleSelectFilter}>All</button>
                <button value='Africa' className="select-option" onClick={handleSelectFilter}>Africa</button>
                <button value='America' className="select-option" onClick={handleSelectFilter}>America</button>
                <button value='Asia' className="select-option" onClick={handleSelectFilter}>Asia</button>
                <button value='Europe' className="select-option" onClick={handleSelectFilter}>Europe</button>
                <button value='Oceania' className="select-option" onClick={handleSelectFilter}>Oceania</button>

    )
}


问:
Converting a BigInteger array to a byte array and back in C#

Problem

I have a BigInteger array which I'm converting to a byte array as:

```<code>var ciphertext = new BigInteger[ciphertextBlocks];
...
byte[] ciphertextBytes = ciphertext.SelectMany(c => c.ToByteArray()).ToArray();
</code>```

Now, I would like to get the original BigInteger array back. This seems impossible since the individual sizes of each BigInteger is lost when it is converted to byte[].

Context

I understand this could very well be an XY problem. Therefore, here's what I'm doing. I'm implementing a simple cryptosystem called Merkle-Hellman Knapsack Cryptosystem for encryption and decryption.

I know that rolling your own cryptographic algorithms is frowned upon but I'm doing it purely for educational purposes.

Since the output of a cryptographic operation is represented as byte[], I'm converting the resultant ciphertext (BigInteger[]) to a byte[] in Encrypt()).

However, I need access to the original BigInteger[] array in the Decrypt() method to individually decrypt each BigInteger. Is there a way to achieve this in the Decrypt() method?

If the type were a fixed-size primitive like long, I could do something like this:

```<code>long[] cipherTextInt = new long[ciphertext.Length / sizeof(long)];
Buffer.BlockCopy(ciphertext, 0, cipherTextInt, 0, ciphertext.Length);
</code>```

But since BigInteger can be arbitrarily large, how can this be done?

```<code>public class KnapsackCryptosystem
{
    const int BitsPerByte = 8;

    public PublicKeyInfo PublicKey { get; }

    private PrivateKeyInfo PrivateKey { get; }

    public byte[] Encrypt(byte[] plaintext)
    {

        var plaintextBits = new BitArray(plaintext);
        var sequence = PublicKey.Sequence;

        // Calculate number of ciphertext blocks:
        // Dividing the length of the sequence by the bit length of the plaintext gives
        // the number of ciphertext blocks. If the plaintext bit length is not a multiple of
        // the sequence length (remainder != 0), an extra block is required.
        var (quotient, remainder) = Math.DivRem(plaintextBits.Count, sequence.Count);
        var ciphertextBlocks = quotient + (remainder == 0 ? 0 : 1);

        // Create a BigInteger array to hold the ciphertext integers
        var ciphertext = new BigInteger[ciphertextBlocks];

        // Apply the sequence to each plaintext block
        for (int i = 0; i < ciphertextBlocks; i++)
        {
            for (int j = 0; j < sequence.Count; j++)
            {
                // Calculate the end index of the current block
                int endIndex = (i + 1) * sequence.Count;
                // Calculate the index of the jth bit from the end;
                int bitIndex = end - j - 1;

                try
                {
                    var bit = plaintextBits[bitIndex];
                    //Console.WriteLine($"j={j} : idx={rIndex} : bit={(bit ? 1 : 0)} | ");
                    Console.WriteLine($"j={j} : idx={index} : bit={(bit ? 1 : 0)} : ");
                    if (bit)
                    {
                        // Add the jth element to the ith ciphertext block if the bit is set
                        Console.WriteLine($"+{sequence[j]} .");
                        ciphertext[i] += sequence[j];
                    }
                }
                catch (ArgumentOutOfRangeException)
                {
                    // thrown at the last block when the sequence length exceeds the last plaintext block
                    Console.WriteLine(nameof(ArgumentOutOfRangeException) + " " + index);
                    break;
                }
            }
            Console.WriteLine();
        }
        Console.WriteLine("Ciphertext Elements:");
        Array.ForEach(ciphertext, x => Console.WriteLine(x));

        // Convert the BigInteger[] array to byte[]
        var ciphertextBytes = ciphertext.SelectMany(c => c.ToByteArray()).ToArray();
        return ciphertextBytes;
    }

    public byte[] Decrypt(byte[] ciphertext)
    {
        var sequence = PrivateKey.Sequence;
        int wInverse = ModularArithmetic.MultiplicativeInverse(PrivateKey.W, PrivateKey.M);
        Console.WriteLine($"wInverse: {wInverse}");

        // RESTORE BigInteger[] FROM byte[] ciphertext. How to achieve this?
        // cipherTextInts is the restored BigInteger array containing the ciphertext for each block
        var ciphertextInts = BACK_TO_BIG_INTEGER_ARRAY(ciphertext);
        var plaintextBits = new BitArray(<UNKNOWN_LENGTH>);

        for (int i = 0; i < ciphertextInts.Length; i++)
        {
            var ciphertextElement = (wInverse * ciphertextInts[i]) % PrivateKey.M;

            // Solve the subset sum problem
            for (int j = PrivateKey.Sequence.Count - 1; j >= 0; j--)
            {
                if (PrivateKey.Sequence[j] <= ciphertextElement)
                {
                    // Calculate the end index of the current block
                    int endIndex = (i + 1) * sequence.Count;
                    // Calculate the index of the jth bit from the end;
                    int bitIndex = end - j - 1;

                    plaintextBits[bitIndex] = true;
                    ciphertextElement -= PrivateKey.Sequence[j];
                    //Console.WriteLine($"    Minus {PrivateKey.Sequence[j]}. element: {ciphertextElement}");
                }
            }
        }

        // Copy BitArray data to byte[] array and return
        var (quotient1, remainder1) = Math.DivRem(plaintextBits.Length, BitsPerByte);
        byte[] bytes = new byte[quotient1 + (remainder1 == 0 ? 0 : 1)];
        plaintextBits.CopyTo(bytes, 0);
        return bytes;
    }

    public static KnapsackCryptosystem Create(
        IReadOnlyList<int> sequence, int m, int w)
    {
        if (sequence.Count == 0)
        {
            throw new ArgumentException(
                "Sequence must be non-empty.",
                nameof(sequence));
        }
        int sum = sequence[0];
        for (int i = 1; i < sequence.Count; i++)
        {
            if (sequence[i] <= sum)
            {
                throw new ArgumentException(
                    "Not a superincreasing sequence.",
                    nameof(sequence));
            }
            sum += sequence[i];
        }
        if (m <= sum)
        {
            throw new ArgumentOutOfRangeException(
                nameof(m),
                "m must be greater than the sum of the sequence.");
        }

        if (MathHelpers.Gcd(m, w) != 1)
        {
            throw new ArgumentException(
                "w must be coprime to m.",
                nameof(w));
        }

        IReadOnlyList<int> publicSequence = GeneratePublicSequence(sequence, m, w);

        return new KnapsackCryptosystem(
            new PublicKeyInfo(publicSequence),
            new PrivateKeyInfo(sequence, m, w)
        );
    }

    private static IReadOnlyList<int> GeneratePublicSequence(
        IReadOnlyList<int> sequence, int m, int w) => (
            from item in sequence
            select (w * item) % m)
            .ToList()
            .AsReadOnly();    // Multiply each item in the sequence by w and mod by m

    public readonly record struct PublicKeyInfo(IReadOnlyList<int> Sequence);

    // M is the modulus greater than sum of public sequence
    // W is the integer coprime to M
    private readonly record struct PrivateKeyInfo(IReadOnlyList<int> Sequence, int M, int W);

    private KnapsackCryptosystem(PublicKeyInfo publicKey, PrivateKeyInfo privateKey)
    {
        PublicKey = publicKey;
        PrivateKey = privateKey;
    }
}
</code>```

Body:
Problem

I have a BigInteger array which I'm converting to a byte array as:

var ciphertext = new BigInteger[ciphertextBlocks];
...
byte[] ciphertextBytes = ciphertext.SelectMany(c => c.ToByteArray()).ToArray();

Now, I would like to get the original BigInteger array back. This seems impossible since the individual sizes of each BigInteger is lost when it is converted to byte[].

Context

I understand this could very well be an XY problem. Therefore, here's what I'm doing. I'm implementing a simple cryptosystem called Merkle-Hellman Knapsack Cryptosystem for encryption and decryption.

I know that rolling your own cryptographic algorithms is frowned upon but I'm doing it purely for educational purposes.

Since the output of a cryptographic operation is represented as byte[], I'm converting the resultant ciphertext (BigInteger[]) to a byte[] in Encrypt()).

However, I need access to the original BigInteger[] array in the Decrypt() method to individually decrypt each BigInteger. Is there a way to achieve this in the Decrypt() method?

If the type were a fixed-size primitive like long, I could do something like this:

long[] cipherTextInt = new long[ciphertext.Length / sizeof(long)];
Buffer.BlockCopy(ciphertext, 0, cipherTextInt, 0, ciphertext.Length);

But since BigInteger can be arbitrarily large, how can this be done?

public class KnapsackCryptosystem
{
    const int BitsPerByte = 8;

    public PublicKeyInfo PublicKey { get; }

    private PrivateKeyInfo PrivateKey { get; }

    public byte[] Encrypt(byte[] plaintext)
    {

        var plaintextBits = new BitArray(plaintext);
        var sequence = PublicKey.Sequence;

        // Calculate number of ciphertext blocks:
        // Dividing the length of the sequence by the bit length of the plaintext gives
        // the number of ciphertext blocks. If the plaintext bit length is not a multiple of
        // the sequence length (remainder != 0), an extra block is required.
        var (quotient, remainder) = Math.DivRem(plaintextBits.Count, sequence.Count);
        var ciphertextBlocks = quotient + (remainder == 0 ? 0 : 1);

        // Create a BigInteger array to hold the ciphertext integers
        var ciphertext = new BigInteger[ciphertextBlocks];

        // Apply the sequence to each plaintext block
        for (int i = 0; i < ciphertextBlocks; i++)
        {
            for (int j = 0; j < sequence.Count; j++)
            {
                // Calculate the end index of the current block
                int endIndex = (i + 1) * sequence.Count;
                // Calculate the index of the jth bit from the end;
                int bitIndex = end - j - 1;

                try
                {
                    var bit = plaintextBits[bitIndex];
                    //Console.WriteLine($"j={j} : idx={rIndex} : bit={(bit ? 1 : 0)} | ");
                    Console.WriteLine($"j={j} : idx={index} : bit={(bit ? 1 : 0)} : ");
                    if (bit)
                    {
                        // Add the jth element to the ith ciphertext block if the bit is set
                        Console.WriteLine($"+{sequence[j]} .");
                        ciphertext[i] += sequence[j];
                    }
                }
                catch (ArgumentOutOfRangeException)
                {
                    // thrown at the last block when the sequence length exceeds the last plaintext block
                    Console.WriteLine(nameof(ArgumentOutOfRangeException) + " " + index);
                    break;
                }
            }
            Console.WriteLine();
        }
        Console.WriteLine("Ciphertext Elements:");
        Array.ForEach(ciphertext, x => Console.WriteLine(x));

        // Convert the BigInteger[] array to byte[]
        var ciphertextBytes = ciphertext.SelectMany(c => c.ToByteArray()).ToArray();
        return ciphertextBytes;
    }

    public byte[] Decrypt(byte[] ciphertext)
    {
        var sequence = PrivateKey.Sequence;
        int wInverse = ModularArithmetic.MultiplicativeInverse(PrivateKey.W, PrivateKey.M);
        Console.WriteLine($"wInverse: {wInverse}");

        // RESTORE BigInteger[] FROM byte[] ciphertext. How to achieve this?
        // cipherTextInts is the restored BigInteger array containing the ciphertext for each block
        var ciphertextInts = BACK_TO_BIG_INTEGER_ARRAY(ciphertext);
        var plaintextBits = new BitArray(<UNKNOWN_LENGTH>);

        for (int i = 0; i < ciphertextInts.Length; i++)
        {
            var ciphertextElement = (wInverse * ciphertextInts[i]) % PrivateKey.M;

            // Solve the subset sum problem
            for (int j = PrivateKey.Sequence.Count - 1; j >= 0; j--)
            {
                if (PrivateKey.Sequence[j] <= ciphertextElement)
                {
                    // Calculate the end index of the current block
                    int endIndex = (i + 1) * sequence.Count;
                    // Calculate the index of the jth bit from the end;
                    int bitIndex = end - j - 1;

                    plaintextBits[bitIndex] = true;
                    ciphertextElement -= PrivateKey.Sequence[j];
                    //Console.WriteLine($"    Minus {PrivateKey.Sequence[j]}. element: {ciphertextElement}");
                }
            }
        }

        // Copy BitArray data to byte[] array and return
        var (quotient1, remainder1) = Math.DivRem(plaintextBits.Length, BitsPerByte);
        byte[] bytes = new byte[quotient1 + (remainder1 == 0 ? 0 : 1)];
        plaintextBits.CopyTo(bytes, 0);
        return bytes;
    }

    public static KnapsackCryptosystem Create(
        IReadOnlyList<int> sequence, int m, int w)
    {
        if (sequence.Count == 0)
        {
            throw new ArgumentException(
                "Sequence must be non-empty.",
                nameof(sequence));
        }
        int sum = sequence[0];
        for (int i = 1; i < sequence.Count; i++)
        {
            if (sequence[i] <= sum)
            {
                throw new ArgumentException(
                    "Not a superincreasing sequence.",
                    nameof(sequence));
            }
            sum += sequence[i];
        }
        if (m <= sum)
        {
            throw new ArgumentOutOfRangeException(
                nameof(m),
                "m must be greater than the sum of the sequence.");
        }

        if (MathHelpers.Gcd(m, w) != 1)
        {
            throw new ArgumentException(
                "w must be coprime to m.",
                nameof(w));
        }

        IReadOnlyList<int> publicSequence = GeneratePublicSequence(sequence, m, w);

        return new KnapsackCryptosystem(
            new PublicKeyInfo(publicSequence),
            new PrivateKeyInfo(sequence, m, w)
        );
    }

    private static IReadOnlyList<int> GeneratePublicSequence(
        IReadOnlyList<int> sequence, int m, int w) => (
            from item in sequence
            select (w * item) % m)
            .ToList()
            .AsReadOnly();    // Multiply each item in the sequence by w and mod by m

    public readonly record struct PublicKeyInfo(IReadOnlyList<int> Sequence);

    // M is the modulus greater than sum of public sequence
    // W is the integer coprime to M
    private readonly record struct PrivateKeyInfo(IReadOnlyList<int> Sequence, int M, int W);

    private KnapsackCryptosystem(PublicKeyInfo publicKey, PrivateKeyInfo privateKey)
    {
        PublicKey = publicKey;
        PrivateKey = privateKey;
    }
}


问:
why when I add a node clone, it acts differently to adding the same div to the html
I am creating an infinite sliding carousel. when I add the below, after the animation there is a little glitch with the carousel jumping and returning to the start.

If I remove the Javascript and manual add another "box-container prim" the carousel works perfectly. I dont want to editing 2 divs, so I want to clone the div. Why is the behavior different when you clone the div? when you inspect the code the divs are exactly the same?

let x = document.querySelector('.box-container')
let clone = x.cloneNode(true);
x.after(clone)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  padding: 0;
  margin: 0;
}

.wrapper {
  width: 100vw;
  height: 100px;
  display: flex;
  overflow: hidden;
}

.box-container {
  display: flex;
  width: 100%;
  height: 100%;
}

.box {
  width: 200px;
  border: 1px solid black;
}

.prim {
  animation: scroll 10s linear infinite;
}</code>```

1

2

3

4

5

```

Adding manual html, and cloning with js

Body:
I am creating an infinite sliding carousel. when I add the below, after the animation there is a little glitch with the carousel jumping and returning to the start.

If I remove the Javascript and manual add another "box-container prim" the carousel works perfectly. I dont want to editing 2 divs, so I want to clone the div. Why is the behavior different when you clone the div? when you inspect the code the divs are exactly the same?

let x = document.querySelector('.box-container')
let clone = x.cloneNode(true);
x.after(clone)

* {
  padding: 0;
  margin: 0;
}

.wrapper {
  width: 100vw;
  height: 100px;
  display: flex;
  overflow: hidden;
}

.box-container {
  display: flex;
  width: 100%;
  height: 100%;
}

.box {
  width: 200px;
  border: 1px solid black;
}

.prim {
  animation: scroll 10s linear infinite;
}

1

2

3

4

5

Adding manual html, and cloning with js


问:
time range error when using interval in TDengine
I have an sql statement:

```<code>select _WSTART startTime, _WEND endTime, avg(drp) drp, avg(intv) intv, avg(pdr) pdr, avg(dyp) dyp, avg(dy) dy from st_pptn where tm >= 1653619243000 interval(1h) fill(VALUE, 0)
</code>```

It reported an error when executing:

Start(end) time of query range required or time range too large

I did not understand exactly what it means.

Body:
I have an sql statement:

select _WSTART startTime, _WEND endTime, avg(drp) drp, avg(intv) intv, avg(pdr) pdr, avg(dyp) dyp, avg(dy) dy from st_pptn where tm >= 1653619243000 interval(1h) fill(VALUE, 0)

It reported an error when executing:

Start(end) time of query range required or time range too large

I did not understand exactly what it means.


问:
How to mock file system with memfs in NodeJS
I want to test the following function with the memfs package

import fs from 'fs-extra'
import path from 'path'

async function ensureParent(filepath: string) {
  const absolutePath = path.resolve(filepath)
  const parentDir = path.dirname(absolutePath)

  const exists = await fs.pathExists(parentDir)

  return exists
}

export default {
  ensureParent,
}

```
<p>To test it with an in-memory file system I have at the root of the project, the following <code>__mocks__/fs.ts</code> file</p>
<pre class="lang-js prettyprint-override"><code>import { fs } from 'memfs'

export default fs
</code>```

and the following __mocks__/fs/promises.ts file

import { fs } from 'memfs'

export default fs.promises
```
<p>Here is the test file <code>file.test.ts</code></p>
<pre class="lang-js prettyprint-override"><code>import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
import { vol } from 'memfs'

import f from '../file'

vi.mock('fs')
vi.mock('fs/promises')

const fileSystem = {
  './exists/shiman.txt': 'Hello shiman',
}

beforeAll(() => {
  vol.fromJSON(fileSystem, '/tmp')
})

beforeEach(() => {
  vol.reset()
})

describe.concurrent('file utils', () => {
  it('ensure a directory exists', async () => {
    expect(await f.ensureParent('/tmp/exists/shiman.txt')).toBe(true)
  })
})
</code>```

However, the test keeps failing, and I realized that, although the mock is taken into account, the in-memory file system is not because await fs.readdir('/', (err, data) => console.log(err, data)) logs the content of / in my machine.

Have I done something wrong?

Body:
I want to test the following function with the memfs package

import fs from 'fs-extra'
import path from 'path'

async function ensureParent(filepath: string) {
  const absolutePath = path.resolve(filepath)
  const parentDir = path.dirname(absolutePath)

  const exists = await fs.pathExists(parentDir)

  return exists
}

export default {
  ensureParent,
}

To test it with an in-memory file system I have at the root of the project, the following __mocks__/fs.ts file

import { fs } from 'memfs'

export default fs

and the following __mocks__/fs/promises.ts file

import { fs } from 'memfs'

export default fs.promises

Here is the test file file.test.ts

import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
import { vol } from 'memfs'

import f from '../file'

vi.mock('fs')
vi.mock('fs/promises')

const fileSystem = {
  './exists/shiman.txt': 'Hello shiman',
}

beforeAll(() => {
  vol.fromJSON(fileSystem, '/tmp')
})

beforeEach(() => {
  vol.reset()
})

describe.concurrent('file utils', () => {
  it('ensure a directory exists', async () => {
    expect(await f.ensureParent('/tmp/exists/shiman.txt')).toBe(true)
  })
})

However, the test keeps failing, and I realized that, although the mock is taken into account, the in-memory file system is not because await fs.readdir('/', (err, data) => console.log(err, data)) logs the content of / in my machine.

Have I done something wrong?