问:
Got these errors after changing the version of Stackdriver Logging to v2 in Golang
When I updated my appengine logging version to v2. I got these errors.

Package: google.golang.org/appengine/v2/log

```<code>import (
    "context"
    "google.golang.org/appengine/v2/log"
)

// LogDebug
func LogDebug(ctx context.Context, format string, args ...interface{}) {
    log.Debugf(ctx, format, args)
}

// LogInfo
func LogInfo(ctx context.Context, format string, args ...interface{}) {
    log.Infof(ctx, format, args)
}
</code>```

Anyone knows how to resolve this?

Errors:

```<code>panic: proto: message appengine.base.StringProto is already registered

See https://developers.google.com/protocol-buffers/docs/reference/go/faq#namespace-conflict

google.golang.org/protobuf/reflect/protoregistry.glob..func1(0xf2a3d8, 0xc0001a4c00, 0xf11ac0, 0xc0002a8370, 0xdce5a0)

/layers/google.go.gomod/gopath/pkg/mod/google.golang.org/protobuf@v1.27.1/reflect/protoregistry/registry.go:54 +0x25f

/layers/google.go.gomod/gopath/pkg/mod/google.golang.org/protobuf@v1.27.1/reflect/protoregistry/registry.go:577 +0x32d

github.com/golang/protobuf/proto.RegisterType(0xf1d6f0, 0x0, 0xdf658a, 0x1a)

/layers/google.go.gomod/gopath/pkg/mod/google.golang.org/appengine@v1.6.7/internal/base/api_base.pb.go:280 +0x4f

Start program failed: failed to detect app after start: ForAppStart():
</code>```

Body:
When I updated my appengine logging version to v2. I got these errors.

Package: google.golang.org/appengine/v2/log

import (
    "context"
    "google.golang.org/appengine/v2/log"
)

// LogDebug
func LogDebug(ctx context.Context, format string, args ...interface{}) {
    log.Debugf(ctx, format, args)
}

// LogInfo
func LogInfo(ctx context.Context, format string, args ...interface{}) {
    log.Infof(ctx, format, args)
}

Anyone knows how to resolve this?

Errors:

panic: proto: message appengine.base.StringProto is already registered

See https://developers.google.com/protocol-buffers/docs/reference/go/faq#namespace-conflict

google.golang.org/protobuf/reflect/protoregistry.glob..func1(0xf2a3d8, 0xc0001a4c00, 0xf11ac0, 0xc0002a8370, 0xdce5a0)

/layers/google.go.gomod/gopath/pkg/mod/google.golang.org/protobuf@v1.27.1/reflect/protoregistry/registry.go:54 +0x25f

/layers/google.go.gomod/gopath/pkg/mod/google.golang.org/protobuf@v1.27.1/reflect/protoregistry/registry.go:577 +0x32d

github.com/golang/protobuf/proto.RegisterType(0xf1d6f0, 0x0, 0xdf658a, 0x1a)

/layers/google.go.gomod/gopath/pkg/mod/google.golang.org/appengine@v1.6.7/internal/base/api_base.pb.go:280 +0x4f

Start program failed: failed to detect app after start: ForAppStart():


来源: stackexchange

问:
SQL Server connection via LAN IP in windows Form
I want to connect my Windows Forms application via local area network. I want to enable database access via the Windows Forms application over the LAN. I have tried different connection string but it is connecting except this string:

```<code>string sqlConnectionString = "Server=localhost\\SQLEXPRESS;Database=DMStorage;Trusted_Connection=True;";
</code>```

The above string works fine to connect but if I try to access the database with a local ip address it failed to reach the server. Here are the strings that I have tried. I am using sql server 2022.

//string sqlConnectionString = "Data Source = 192.9.210.62,1433; Initial Catalog = DM_Storage;Trusted_Connection=True;";
//string sqlConnectionString = "Data Source = 192.9.210.62,1433; Network Library = DBMSSOCN;Initial Catalog = DM_Storage; User ID = FKJ; Password=123456";
//string sqlConnectionString = "Data Source = 192.9.210.62,1433;Initial Catalog = DM_Storage; User ID = Faizan Khan; Password=123456";
```

I have also enabled the sql server settings like

Allow remote connection to this server

Sql server and windows authentication mode

tcp is also enabled, forget to mention it.  and In TCP port it is set to 1443. While the TCP dynamic Ports is set to 61354. Is t his correct?

In bound in firewall

ContentLicense: CC BY-SA 4.0

Body:
I want to connect my Windows Forms application via local area network. I want to enable database access via the Windows Forms application over the LAN. I have tried different connection string but it is connecting except this string:

string sqlConnectionString = "Server=localhost\\SQLEXPRESS;Database=DMStorage;Trusted_Connection=True;";

The above string works fine to connect but if I try to access the database with a local ip address it failed to reach the server. Here are the strings that I have tried. I am using sql server 2022.

//string sqlConnectionString = "Data Source = 192.9.210.62,1433; Initial Catalog = DM_Storage;Trusted_Connection=True;";
//string sqlConnectionString = "Data Source = 192.9.210.62,1433; Network Library = DBMSSOCN;Initial Catalog = DM_Storage; User ID = FKJ; Password=123456";
//string sqlConnectionString = "Data Source = 192.9.210.62,1433;Initial Catalog = DM_Storage; User ID = Faizan Khan; Password=123456";

I have also enabled the sql server settings like

Allow remote connection to this server

Sql server and windows authentication mode

tcp is also enabled, forget to mention it.  and In TCP port it is set to 1443. While the TCP dynamic Ports is set to 61354. Is t his correct?

In bound in firewall


问:
How to create a combo box column using raw values of a data table in C#
My goal would be to modify an already existing data grid column into a combo box (drop down list) using C#. The grid is populated using a data table.
So basically, let's say the column "Profile" has following string values={"X", "Y", "Z", "W"}. The "new" column "Profile" should have then for each cell a drop down list containing the beforementioned string values. However, the column "Profile" should not be a new one but should be the modified version of the already existing "profile" column. So ideally, the algorithm or function should follow these steps:

Search for the Column I want to transform into a drop down list

Look trough all the rows and collect all the unique values

Substitute the column with the new one containing for each cell the values using a dropdown.
So at the end the number of columns should remain the same.
Thank you in advance for your precious help.
Cheers!!

So far the only I managed to do something was by creating a new column and hiding/Deleting the old one. But doing so, it would be a very inefficient way as if 1 Mil rows exist then all the values need to be copied over.


Title: React Native. Icon displays differently in iOS and Android

Body:
I can't understand why the icon (Pencil) is displayed differently on Android. I think the margin is not  working in Android but I can not fix it. Does anyone have a tip for me? Below is my code...

<G fill-rule="nonzero" scale={1}>
          <Circle fill="#60666F" cx="12" cy="12" r="12" />
          <Circle fill="#FFFFFF" cx="12" cy="12" r="10" />
          <View style={{ margin: 6 }}>
            <SvgXml xml={Pencil} fill={Theme.COLOR_PRIMARY} />
          </View>
</G>

Pencil.svg

<svg width="21" height="25" viewBox="0 0 21 25" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M11.8050271,2.69462575 C12.064991,2.43466185 12.064991,2.0013887 11.8050271,1.75475628 L10.2452437,0.19497292 C9.9986113,-0.0649909735 9.56533815,-0.0649909735 9.30537425,0.19497292 L8.07887793,1.4148035 L10.5785308,3.91445633 L11.8050271,2.69462575 Z M0,9.50034717 L0,12 L2.49965283,12 L9.87196223,4.62102486 L7.3723094,2.12137203 L0,9.50034717 Z"></path>
</svg>

Android icon should be like in iOS.


问:
[tailwind]What are those faintly visible lines on the checked radio? How to align checked images?
What are those faintly visible lines on the checked radio? How to align checked images?

```<code>input {
    @apply border-Neutrals-Grey3 checked:border-Brand-Primary ring-0 ring-inset checked:bg-radio_checked checked:bg-[center_left_right] checked:bg-no-repeat checked:bg-[length:7.99px_7.99px] checked:text-Neutrals-White;
  }
</code>```

Aligned input image and disappearing faint lines

Body:
What are those faintly visible lines on the checked radio? How to align checked images?

input {
    @apply border-Neutrals-Grey3 checked:border-Brand-Primary ring-0 ring-inset checked:bg-radio_checked checked:bg-[center_left_right] checked:bg-no-repeat checked:bg-[length:7.99px_7.99px] checked:text-Neutrals-White;
  }

Aligned input image and disappearing faint lines


问:
Unable to create model class instance from retrofit2 reponse generic ApiResponse sealed class
I am implementing MVVM with repository in my application. Created a generic response class and facing exception while trying to create ApiResponse.Success in repository with response received using retrofit2.

ApiResponse class

```<code>sealed class ApiResponse<T> (
    val code: Int? = null,
    val status: String? = null,
    val message: String? = null,
    val data: T? = null,
    val errors: Map<String, ArrayList<String>>? = null,
    val exceptionMessage: String? = null,
) {
    // Loading state
    class Loading<T>: ApiResponse<T>()

    // Success state
    class Success<T> (data: T?): ApiResponse<T> (data = data)

    // Error state
    class Error<T> (errors: Map<String, ArrayList<String>>?): ApiResponse<T> (errors = errors)

    // Runtime Exception
    class ExceptionError<T> (exceptionMessage: String?): ApiResponse<T> (exceptionMessage = exceptionMessage)
}
</code>```

AuthService Interface

```<code>interface AuthService {

    @POST("accounts/login")
    suspend fun getTokenPair(@Body userLoginCred: UserLoginCred): Response<ApiResponse<UserTokenPair>>
}
</code>```

AuthRepository Code

```<code>if (NetworkUtil.isInternetAvailable(context)!!) {
    try {
        val response = authService.getTokenPair(userLoginCred)
        if (response.isSuccessful && response.body() != null) {
            _userTokenPairResponse.postValue(ApiResponse.Success(response.body()!!.data))
        }
        else if (response.errorBody() != null) {
            _userTokenPairResponse.postValue(ApiResponse.Error(Gson().fromJson(response.errorBody()!!.string(), Map::class.java) as Map<String, ArrayList<String>>))
        }
        else {
            _userTokenPairResponse.postValue(ApiResponse.Loading())
        }
    }
    catch (e: Exception) {
        _userTokenPairResponse.postValue(ApiResponse.ExceptionError(e.message))
    }
}
else {
    _userTokenPairResponse.postValue(ApiResponse.ExceptionError("Device not connected to internet."))
}
</code>```

What is working and what not?

```<code>Loading state -> Working
Error state -> working
Execption state -> working
Success state -> always have exception
</code>```
```<code>Unable to create instance of class com.example.ApiResponse. Registering an InstanceCreator or a TypeAdapter for this type, or adding a no-args constructor may fix this problem.
</code>```

Body:
I am implementing MVVM with repository in my application. Created a generic response class and facing exception while trying to create ApiResponse.Success in repository with response received using retrofit2.

ApiResponse class

sealed class ApiResponse<T> (
    val code: Int? = null,
    val status: String? = null,
    val message: String? = null,
    val data: T? = null,
    val errors: Map<String, ArrayList<String>>? = null,
    val exceptionMessage: String? = null,
) {
    // Loading state
    class Loading<T>: ApiResponse<T>()

    // Success state
    class Success<T> (data: T?): ApiResponse<T> (data = data)

    // Error state
    class Error<T> (errors: Map<String, ArrayList<String>>?): ApiResponse<T> (errors = errors)

    // Runtime Exception
    class ExceptionError<T> (exceptionMessage: String?): ApiResponse<T> (exceptionMessage = exceptionMessage)
}

AuthService Interface

interface AuthService {

    @POST("accounts/login")
    suspend fun getTokenPair(@Body userLoginCred: UserLoginCred): Response<ApiResponse<UserTokenPair>>
}

AuthRepository Code

if (NetworkUtil.isInternetAvailable(context)!!) {
    try {
        val response = authService.getTokenPair(userLoginCred)
        if (response.isSuccessful && response.body() != null) {
            _userTokenPairResponse.postValue(ApiResponse.Success(response.body()!!.data))
        }
        else if (response.errorBody() != null) {
            _userTokenPairResponse.postValue(ApiResponse.Error(Gson().fromJson(response.errorBody()!!.string(), Map::class.java) as Map<String, ArrayList<String>>))
        }
        else {
            _userTokenPairResponse.postValue(ApiResponse.Loading())
        }
    }
    catch (e: Exception) {
        _userTokenPairResponse.postValue(ApiResponse.ExceptionError(e.message))
    }
}
else {
    _userTokenPairResponse.postValue(ApiResponse.ExceptionError("Device not connected to internet."))
}

What is working and what not?

Loading state -> Working
Error state -> working
Execption state -> working
Success state -> always have exception

Unable to create instance of class com.example.ApiResponse. Registering an InstanceCreator or a TypeAdapter for this type, or adding a no-args constructor may fix this problem.


问:
CDK pipeline: Cannot parse SecretValue in UpdatePipeline step?
I am deploying a CDK pipeline. My code is on GitHub in the repo myUsername/myRepo, and I would like to give the pipeline access to that GitHub repo.

First I created a GitHub personal access token with the required permissions (admin:repo_hook and repo) and stored it in AWS Secrets Manager with name my-github-access-token and JSON value {token: "ghp_000000000000000000000000000000000000"}.

My CDK code is:

class DeploymentPipelineStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {

    // Get GitHub access token from Secrets Manager
    const githubAccessToken = SecretValue.secretsManager('my-github-access-token', {
      jsonField: 'token',
    });

    // Give CodePipeline access to GitHub repo
    const pipelineCodeSource = pipelines.CodePipelineSource.gitHub('myUsername/myRepo', 'main', {
      authentication: githubAccessToken,
    });

    // Create pipeline
    new pipelines.CodePipeline(this, 'Pipeline', {
      synth: new ShellStep('PipelineSynth', {
        input: pipelineCodeSource,
        installCommands: ['npm i -g npm@latest'],
        commands: ['npm ci', 'npx cdk synth -q --verbose'],
      }),
      selfMutation: true,
    });
  }
}
```
<p>When I deploy this pipeline, the Source and Build steps complete successfully, but the UpdatePipeline step fails:
<img src="https://i.stack.imgur.com/pSyZE.png" alt="AWS Console CodePipeline" /></p>
<p>The error message is:</p>
```DeploymentPipeline failed: Error: The stack named DeploymentPipeline failed to deploy:
UPDATE_ROLLBACK_COMPLETE: 1 validation error detected:
Value at 'pipeline.stages.1.member.actions.1.member.configuration' failed to satisfy constraint:
Map value must satisfy constraint:
[Member must have length less than or equal to 50000, Member must have length greater than or equal to 1]
(Service: AWSCodePipeline; Status Code: 400; Error Code: ValidationException; Request ID: ...; Proxy: null)
```
<p>When checking the CloudFormation template generated by CDK, the configuration throwing the error is:</p>
<pre class="lang-json prettyprint-override"><code>"Configuration": {
  "Owner": "myUsername",
  "Repo": "myRepo",
  "Branch": "main",
  "OAuthToken": "{{resolve:secretsmanager:my-github-access-token:SecretString:token::}}",
  "PollForSourceChanges": false
}
</code>```

My conclusion is that the pipeline is unable to parse the SecretValue for OAuthToken  during the UpdatePipeline step. Why? Is this a permissions issue?

Body:
I am deploying a CDK pipeline. My code is on GitHub in the repo myUsername/myRepo, and I would like to give the pipeline access to that GitHub repo.

First I created a GitHub personal access token with the required permissions (admin:repo_hook and repo) and stored it in AWS Secrets Manager with name my-github-access-token and JSON value {token: "ghp_000000000000000000000000000000000000"}.

My CDK code is:

class DeploymentPipelineStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {

    // Get GitHub access token from Secrets Manager
    const githubAccessToken = SecretValue.secretsManager('my-github-access-token', {
      jsonField: 'token',
    });

    // Give CodePipeline access to GitHub repo
    const pipelineCodeSource = pipelines.CodePipelineSource.gitHub('myUsername/myRepo', 'main', {
      authentication: githubAccessToken,
    });

    // Create pipeline
    new pipelines.CodePipeline(this, 'Pipeline', {
      synth: new ShellStep('PipelineSynth', {
        input: pipelineCodeSource,
        installCommands: ['npm i -g npm@latest'],
        commands: ['npm ci', 'npx cdk synth -q --verbose'],
      }),
      selfMutation: true,
    });
  }
}

When I deploy this pipeline, the Source and Build steps complete successfully, but the UpdatePipeline step fails:

The error message is:

DeploymentPipeline failed: Error: The stack named DeploymentPipeline failed to deploy:
UPDATE_ROLLBACK_COMPLETE: 1 validation error detected:
Value at 'pipeline.stages.1.member.actions.1.member.configuration' failed to satisfy constraint:
Map value must satisfy constraint:
[Member must have length less than or equal to 50000, Member must have length greater than or equal to 1]
(Service: AWSCodePipeline; Status Code: 400; Error Code: ValidationException; Request ID: ...; Proxy: null)

When checking the CloudFormation template generated by CDK, the configuration throwing the error is:

"Configuration": {
  "Owner": "myUsername",
  "Repo": "myRepo",
  "Branch": "main",
  "OAuthToken": "{{resolve:secretsmanager:my-github-access-token:SecretString:token::}}",
  "PollForSourceChanges": false
}

My conclusion is that the pipeline is unable to parse the SecretValue for OAuthToken  during the UpdatePipeline step. Why? Is this a permissions issue?


问:
Problem in using pickle to save complex data structures in Python
I have configured a neural network comprising "elements" and "links" - two different class types.

Each element has certain links with other elements.

In trying to save the network I used pickle.

In another progam I open the network via pickle but I think there is a problem.

I think pickle saves different tokens of the class types.

For example, if there are three elements A -> B -> C -> B

so A connects to B and B connects to C and C connects to B

it saves different tokens for B and so fails to save the fact that B is the same element in the two cases.

Is this a correct understanding and if so is there a ready work around?

In the end I saved everything to pandas dataframes and then saved these as excel files.

This works but because of the size of the neural network it takes ages to then load the network again.


问:
Reactjs not processed
I installed reactjs with the instructions of this website
https://learn.microsoft.com/en-us/windows/dev-environment/javascript/react-on-windows
then I deleted all what was in the src folder and created a file in it.Next,I wrote the following code:

```<code>import React from 'react';
import { ReactDOM } from "react";

const element = <h1>Hello</h1>;
console.log(element);
</code>```

When I checked the react website there was nothing on the console. I think that Babel did not convert it into something that computer can understand.So, How can I fix this?

Title: Reactjs not processed

Body:
I installed reactjs with the instructions of this website
https://learn.microsoft.com/en-us/windows/dev-environment/javascript/react-on-windows
then I deleted all what was in the src folder and created a file in it.Next,I wrote the following code:

import React from 'react';
import { ReactDOM } from "react";

const element =
Hello
;
console.log(element);

When I checked the react website there was nothing on the console. I think that Babel did not convert it into something that computer can understand.So, How can I fix this?


问:
Can't runtime self-update a Node app packaged into an .exe by "pkg" tool
I'm instructed to make a Node app, packaged into executable using the npm "pkg" package that updates itself while running without a separate updater executable, but this isn't working for me on Windows (Linux works fine). I'm trying to accomplish this by renaming the running .exe file, downloading the new version and then putting this new .exe file in the old one's place (which works because the old one has been renamed).

Everything is fine up to this point. Then I try to start the new version of the .exe using exec inside the running, renamed old file. This fails.

Example:

```<code>app1.exe ---> renamed (in the same folder) to appTimestamp.exe
app1.exe (new version) ---> gets downloaded and placed next to appTimestamp
appTimestamp (still running) ---> tries to start app1.exe [FAILS]
</code>```

If before doing anything else, I manually change the name of app1.exe in step 1 to something different, say appRand.exe, THEN start up appRand.exe and hit the update button, everything works fine, there is no conflict and a new version of app1.exe is downloaded and appRand.exe can start up the new app1 perfectly. Thus it seems to be some sort of a file name issue despite me going out of my way to rename the running app before attempting the update process. I don't know if the file name problem is with Windows itself, or with Node, or what's going on.

Body:
I'm instructed to make a Node app, packaged into executable using the npm "pkg" package that updates itself while running without a separate updater executable, but this isn't working for me on Windows (Linux works fine). I'm trying to accomplish this by renaming the running .exe file, downloading the new version and then putting this new .exe file in the old one's place (which works because the old one has been renamed).

Everything is fine up to this point. Then I try to start the new version of the .exe using exec inside the running, renamed old file. This fails.

Example:

app1.exe ---> renamed (in the same folder) to appTimestamp.exe
app1.exe (new version) ---> gets downloaded and placed next to appTimestamp
appTimestamp (still running) ---> tries to start app1.exe [FAILS]

If before doing anything else, I manually change the name of app1.exe in step 1 to something different, say appRand.exe, THEN start up appRand.exe and hit the update button, everything works fine, there is no conflict and a new version of app1.exe is downloaded and appRand.exe can start up the new app1 perfectly. Thus it seems to be some sort of a file name issue despite me going out of my way to rename the running app before attempting the update process. I don't know if the file name problem is with Windows itself, or with Node, or what's going on.


问:
QML MediaPlayer, Raspberry Pi 4. gst_alsa_device_new: assertion 'caps' failed error
I've tested a video streaming from host, I can receive video successfully on RPi, but only in terminal.
If I launch a Qt app with Media Player it receives but it's broken screen is blinking with only black image, in console I have this strings:
gst_alsa_device_new: assertion 'caps' failed

In Media Player I enter only address to video

```<code>import QtQuick
import QtMultimedia

Item
{
    id: root

    Component.onCompleted:
    {
        player.play();
    }

    MediaPlayer
    {
        id: player

        source: "udp://192.168.0.152:10001"
        videoOutput: video
    }

    VideoOutput
    {
        id: video

        anchors.fill: parent
        fillMode: VideoOutput.PreserveAspectCrop
    }
}
</code>```

I've discovered that it's only a problem with Qt. Do I need to reinstall it from the ground up or check for Gstreamer libs, but I've already checked it?

Qt version - 6.3.2, builded for RPi from sources via cross-compiling

It's all working normally on x86

Body:
I've tested a video streaming from host, I can receive video successfully on RPi, but only in terminal.
If I launch a Qt app with Media Player it receives but it's broken screen is blinking with only black image, in console I have this strings:
gst_alsa_device_new: assertion 'caps' failed

In Media Player I enter only address to video

import QtQuick
import QtMultimedia

Item
{
    id: root

    Component.onCompleted:
    {
        player.play();
    }

    MediaPlayer
    {
        id: player

        source: "udp://192.168.0.152:10001"
        videoOutput: video
    }

    VideoOutput
    {
        id: video

        anchors.fill: parent
        fillMode: VideoOutput.PreserveAspectCrop
    }
}

I've discovered that it's only a problem with Qt. Do I need to reinstall it from the ground up or check for Gstreamer libs, but I've already checked it?

Qt version - 6.3.2, builded for RPi from sources via cross-compiling

It's all working normally on x86


问:
Only last PointAnnotation have listners, mapbox, react native
I am trying to add points, that can be dragged. I want to be able to click on point to remove it.
but at this moment I have only found a way to remove the last clicked. the other listeners don't work anymore.</p>
```<code>    <Mapbox.PointAnnotation
      draggable={true}
      coordinate={item}
      key={index}
      style={{ heigth: 40, width: 40, backgroundColor: 'red' }}
      onDrag={(e) => handleDrag(e,index)}
      onSelected={()=>handleSelected}
    >
</code>```

Body:
I am trying to add points, that can be dragged. I want to be able to click on point to remove it.
but at this moment I have only found a way to remove the last clicked. the other listeners don't work anymore.

    <Mapbox.PointAnnotation
      draggable={true}
      coordinate={item}
      key={index}
      style={{ heigth: 40, width: 40, backgroundColor: 'red' }}
      onDrag={(e) => handleDrag(e,index)}
      onSelected={()=>handleSelected}
    >


问:
Creating AWS route53 module using Terraform with for_each and data lookup
I am fairly new to terraform and trying to learn about using the for_each argument in order to write a scalable route53 module. Idea is to write a root route53 record module which can be used to create multiple alias records in a private hosted zone with the ability to add weighted routing if required for blue / green deployments.

The repo is setup to have root aws modules, and then two layers of child modules below the root modules to define resources per environment:

```<code>-aws
--modules

---route53
----main.tf
----variables.tf
----locals.tf
----data.tf

---s3
----main.tf
----variables.tf
----locals.tf
----data.tf

...etc (other aws root modules)

--modules.tf (pulls code using root modules as the source)
--variables.tf
--locals.tf
--data.tf

--environment (specify aws tfvars for each environment)
---dev.tfvars
---test.tfvars
---prod.tfvars

</code>```

I have written the root module as follows:

Main.tf

```<code>resource "aws_route53_record" "private_alias_record" {
  name     = var.name
  zone_id  = data.aws_route53_zone.private.zone_id
  type     = var.type

  alias {
    name    = var.alias_name
    zone_id = var.alias_zone_id
  }

  dynamic "weighted_routing_policy" {
    for_each = each.value.weight == null ? [] : [each.value.weight]

    content {
      weight = weighted_routing_policy.value
    }
  }

  set_identifier = var.set_identifer

</code>```

Then first child layer to call the root module:

modules.tf

```<code>#this module creates a route53 weighted record that points to an NLB

module "route53-private-alias-record" {
  source = "./modules/route53"
  for_each = var.records

  name            = each.value.name
  type            = each.value.type
  alias_name      = data.aws_lb.eks_nlb.dns_name
  alias_zone_id   = data.aws_lb.eks_nlb.zone_id
  weight          = each.value.weight
  set_identifier  = each.key

</code>```

variables.tf

```<code>variable "records" {
description = "Specifies values for route53 private alias records"
  type = map(object({
    name             = string
    type             = string
    alias            = map(string)
    weight           = number
    cluster_name     = string
    nlb_tag = string
  }))
  }
}
</code>```

data.tf

This looks up the NLB using tags (As NLB created via kubernetes not AWS directly)

```<code>data "aws_lb" "eks_nlb" {
  for_each = var.records
  tags = {
    "kubernetes.io/${each.value.cluster_name}" = "owned"
    "kubernetes.io/service-name"               = each.value.nlb_tag
  }
}
</code>```

dev environment tfvars

```<code>  records = {
    blue = {
      name             = "application_1"
      type             = "A"
      cluster_name     = "cluster_a"
      weight           = "90"
      nlb_tag          = "ingress"
    }
    green = {
      name             = "application-1"
      type             = "A"
      cluster_name     = "cluster_b"
      weight           = "10"
      nlb_tag          = "ingress"
    }
  }
</code>```

Questions I have are:

Is it correct to use the for_each loop in the first child module rather than the root?

Is the data type in variables.tf correct at map(object)?

Is it correct having the set_identifier as the 'key'? This is a unique value in route53

And am I generally on the right track here with the use of for_each and the fact that there are 2 layers of child modules?

Body:
I am fairly new to terraform and trying to learn about using the for_each argument in order to write a scalable route53 module. Idea is to write a root route53 record module which can be used to create multiple alias records in a private hosted zone with the ability to add weighted routing if required for blue / green deployments.

The repo is setup to have root aws modules, and then two layers of child modules below the root modules to define resources per environment:

-aws
--modules

---route53
----main.tf
----variables.tf
----locals.tf
----data.tf

---s3
----main.tf
----variables.tf
----locals.tf
----data.tf

...etc (other aws root modules)

--modules.tf (pulls code using root modules as the source)
--variables.tf
--locals.tf
--data.tf

--environment (specify aws tfvars for each environment)
---dev.tfvars
---test.tfvars
---prod.tfvars

I have written the root module as follows:

Main.tf

resource "aws_route53_record" "private_alias_record" {
  name     = var.name
  zone_id  = data.aws_route53_zone.private.zone_id
  type     = var.type

  alias {
    name    = var.alias_name
    zone_id = var.alias_zone_id
  }

  dynamic "weighted_routing_policy" {
    for_each = each.value.weight == null ? [] : [each.value.weight]

    content {
      weight = weighted_routing_policy.value
    }
  }

  set_identifier = var.set_identifer

Then first child layer to call the root module:

modules.tf

#this module creates a route53 weighted record that points to an NLB

module "route53-private-alias-record" {
  source = "./modules/route53"
  for_each = var.records

  name            = each.value.name
  type            = each.value.type
  alias_name      = data.aws_lb.eks_nlb.dns_name
  alias_zone_id   = data.aws_lb.eks_nlb.zone_id
  weight          = each.value.weight
  set_identifier  = each.key

variables.tf

variable "records" {
description = "Specifies values for route53 private alias records"
  type = map(object({
    name             = string
    type             = string
    alias            = map(string)
    weight           = number
    cluster_name     = string
    nlb_tag = string
  }))
  }
}

data.tf

This looks up the NLB using tags (As NLB created via kubernetes not AWS directly)

data "aws_lb" "eks_nlb" {
  for_each = var.records
  tags = {
    "kubernetes.io/${each.value.cluster_name}" = "owned"
    "kubernetes.io/service-name"               = each.value.nlb_tag
  }
}

dev environment tfvars

  records = {
    blue = {
      name             = "application_1"
      type             = "A"
      cluster_name     = "cluster_a"
      weight           = "90"
      nlb_tag          = "ingress"
    }
    green = {
      name             = "application-1"
      type             = "A"
      cluster_name     = "cluster_b"
      weight           = "10"
      nlb_tag          = "ingress"
    }
  }

Questions I have are:

Is it correct to use the for_each loop in the first child module rather than the root?

Is the data type in variables.tf correct at map(object)?

Is it correct having the set_identifier as the 'key'? This is a unique value in route53

And am I generally on the right track here with the use of for_each and the fact that there are 2 layers of child modules?


问:
Error n.getTransport is not a function (@sentry)
So i got error in console n.getTransport is not a function
Sentry refers to:

./node_modules/@sentry/tracing/esm/transaction.js in call at line 84:1

./node_modules/@sentry/tracing/esm/idletransaction.js in finish at line 135:1

./node_modules/@sentry/tracing/esm/idletransaction.js in apply at line 82:1

./node_modules/@sentry/browser/esm/helpers.js in r at line 72:1

code with line 84 (transaction):

```<code>if (transport && transport.recordLostEvent) {
 transport.recordLostEvent('sample_rate', 'transaction');
}
</code>```

code with line 135 and 82(idletransaction):

```<code>// if `this._onScope` is `true`, the transaction put itself on the scope when it started
    if (this._onScope) {
        clearActiveTransaction(this._idleHub);
    }
    return _super.prototype.finish.call(this, endTimestamp);

    string 82
    if (!_this._finished) {
       _this.finish();
    }
</code>```

code with line 72 (helpers):

```<code>return fn.apply(this, wrappedArguments);
</code>```

How can I fix this? (if possible)

Body:
So i got error in console n.getTransport is not a function
Sentry refers to:

./node_modules/@sentry/tracing/esm/transaction.js in call at line 84:1

./node_modules/@sentry/tracing/esm/idletransaction.js in finish at line 135:1

./node_modules/@sentry/tracing/esm/idletransaction.js in apply at line 82:1

./node_modules/@sentry/browser/esm/helpers.js in r at line 72:1

code with line 84 (transaction):

if (transport && transport.recordLostEvent) {
 transport.recordLostEvent('sample_rate', 'transaction');
}

code with line 135 and 82(idletransaction):

// if `this._onScope` is `true`, the transaction put itself on the scope when it started
    if (this._onScope) {
        clearActiveTransaction(this._idleHub);
    }
    return _super.prototype.finish.call(this, endTimestamp);

    string 82
    if (!_this._finished) {
       _this.finish();
    }

code with line 72 (helpers):

return fn.apply(this, wrappedArguments);

How can I fix this? (if possible)


问:
Can I redirect an url by keyword to specific domain keeping the url structure?
I have a Magento 2 shop which I am going to split up in multiple brandshops. I want to redirect old links to new domains for products.
So another redirection based on found keyword in url

So what I need to achieve is next:

original-domain.com/keyword1-product.html --> brand1-domain.com/keyword1-product.html
original-domain.com/keyword2-product.html --> brand2-domain.com/keyword2-product.html
original-domain.com/keyword3-product.html --> brand3-domain.com/keyword3-product.html
original-domain.com/other product --> keep as it is.

I think it should be possible by htaccess but no clue how. Thanks in advance

tried finding a solution on this website but couldn't find


问:
FATAL EXCEPTION: mqt_native_modules
```<code>2022-12-15 17:47:42.350 7215-7254/com.affina.agency E/AndroidRuntime: FATAL EXCEPTION: mqt_native_modules
    Process: com.affina.agency, PID: 7215
    java.lang.RuntimeException: Could not invoke PayooSDKAndroidModule.pay
        at com.facebook.react.bridge.JavaMethodWrapper.invoke(Unknown Source:192)
        at com.facebook.react.bridge.JavaModuleWrapper.invoke(Unknown Source:147)
        at com.facebook.jni.NativeRunnable.run(Native Method)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(Unknown Source:0)
        at android.os.Looper.loop(Looper.java:214)
        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(Unknown Source:37)
        at java.lang.Thread.run(Thread.java:919)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at com.facebook.react.bridge.JavaMethodWrapper.invoke(Unknown Source:148)
        at com.facebook.react.bridge.JavaModuleWrapper.invoke(Unknown Source:147)
        at com.facebook.jni.NativeRunnable.run(Native Method)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(Unknown Source:0)
        at android.os.Looper.loop(Looper.java:214)
        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(Unknown Source:37)
        at java.lang.Thread.run(Thread.java:919)
     Caused by: java.lang.AssertionError: java.lang.NoSuchFieldException: EXTERNAL
        at va.n$j0.<init>(Unknown Source:87)
        at va.n$w.b(Unknown Source:27)
        at sa.f.k(Unknown Source:74)
        at va.i.a(Unknown Source:42)
        at va.i.e(Unknown Source:123)
        at va.i.b(Unknown Source:22)
        at sa.f.k(Unknown Source:74)
        at va.b.b(Unknown Source:26)
        at sa.f.k(Unknown Source:74)
        at va.i.a(Unknown Source:42)
        at va.i.e(Unknown Source:123)
        at va.i.b(Unknown Source:22)
        at sa.f.k(Unknown Source:74)
        at va.i.a(Unknown Source:42)
        at va.i.e(Unknown Source:123)
        at va.i.b(Unknown Source:22)
        at sa.f.k(Unknown Source:74)
        at pf.a.d(Unknown Source:6)
        at nf.s.g(Unknown Source:35)
        at nf.s.i(Unknown Source:1)
        at nf.i.e(Unknown Source:4)
        at nf.i.f(Unknown Source:109)
        at nf.t.b(Unknown Source:19)
        at nf.s.d(Unknown Source:24)
        at nf.s$a.invoke(Unknown Source:32)
        at java.lang.reflect.Proxy.invoke(Proxy.java:1006)
        at $Proxy8.k(Unknown Source)
        at f.b.k(Unknown Source:7)
        at c.g.a(Unknown Source:12)
        at vn.payoo.paymentsdk.PayooPaymentSDK$Companion.pay(Unknown Source:13)
        at vn.payoo.paymentsdk.PayooPaymentSDK$Companion.pay(Unknown Source:130)
        at vn.payoo.paymentsdk.PayooPaymentSDK.pay(Unknown Source:5)
        at com.affina.agency.PayooSDKAndroidModule.pay(Unknown Source:214)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.facebook.react.bridge.JavaMethodWrapper.invoke(Unknown Source:148)
        at com.facebook.react.bridge.JavaModuleWrapper.invoke(Unknown Source:147)
        at com.facebook.jni.NativeRunnable.run(Native Method)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(Unknown Source:0)
        at android.os.Looper.loop(Looper.java:214)
        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(Unknown Source:37)
        at java.lang.Thread.run(Thread.java:919)
     Caused by: java.lang.NoSuchFieldException: EXTERNAL
        at java.lang.Class.getField(Class.java:1604)
        at va.n$j0.<init>(Unknown Source:34)
        at va.n$w.b(Unknown Source:27)
        at sa.f.k(Unknown Source:74)
        at va.i.a(Unknown Source:42)
        at va.i.e(Unknown Source:123)
        at va.i.b(Unknown Source:22)
        at sa.f.k(Unknown Source:74)
        at va.b.b(Unknown Source:26)
        at sa.f.k(Unknown Source:74)
        at va.i.a(Unknown Source:42)
        at va.i.e(Unknown Source:123)
        at va.i.b(Unknown Source:22)
        at sa.f.k(Unknown Source:74)
        at va.i.a(Unknown Source:42)
        at va.i.e(Unknown Source:123)
        at va.i.b(Unknown Source:22)
        at sa.f.k(Unknown Source:74)
        at pf.a.d(Unknown Source:6)
        at nf.s.g(Unknown Source:35)
        at nf.s.i(Unknown Source:1)
        at nf.i.e(Unknown Source:4)
        at nf.i.f(Unknown Source:109)
        at nf.t.b(Unknown Source:19)
        at nf.s.d(Unknown Source:24)
        at nf.s$a.invoke(Unknown Source:32)
        at java.lang.reflect.Proxy.invoke(Proxy.java:1006)
        at $Proxy8.k(Unknown Source)
        at f.b.k(Unknown Source:7)
        at c.g.a(Unknown Source:12)
        at vn.payoo.paymentsdk.PayooPaymentSDK$Companion.pay(Unknown Source:13)
        at vn.payoo.paymentsdk.PayooPaymentSDK$Companion.pay(Unknown Source:130)
        at vn.payoo.paymentsdk.PayooPaymentSDK.pay(Unknown Source:5)
        at com.affina.agency.PayooSDKAndroidModule.pay(Unknown Source:214)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.facebook.react.bridge.JavaMethodWrapper.invoke(Unknown Source:148)
        at com.facebook.react.bridge.JavaModuleWrapper.invoke(Unknown Source:147)
        at com.facebook.jni.NativeRunnable.run(Native Method)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(Unknown Source:0)
        at android.os.Looper.loop(Looper.java:214)
        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(Unknown Source:37)
        at java.lang.Thread.run(Thread.java:919)
</code>```

I added an external library to my React Native application and it worked fine during development, but when I built the release apk, it failed and I still don't have a solution for it.

I tried deleting the gradlew cache and looking at its documentation, but it still didn't work. It still works fine on the development environment, but when I build the release apk, it fails as mentioned above.

Title: FATAL EXCEPTION: mqt_native_modules

Body:
2022-12-15 17:47:42.350 7215-7254/com.affina.agency E/AndroidRuntime: FATAL EXCEPTION: mqt_native_modules
    Process: com.affina.agency, PID: 7215
    java.lang.RuntimeException: Could not invoke PayooSDKAndroidModule.pay
        at com.facebook.react.bridge.JavaMethodWrapper.invoke(Unknown Source:192)
        at com.facebook.react.bridge.JavaModuleWrapper.invoke(Unknown Source:147)
        at com.facebook.jni.NativeRunnable.run(Native Method)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(Unknown Source:0)
        at android.os.Looper.loop(Looper.java:214)
        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(Unknown Source:37)
        at java.lang.Thread.run(Thread.java:919)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at com.facebook.react.bridge.JavaMethodWrapper.invoke(Unknown Source:148)
        at com.facebook.react.bridge.JavaModuleWrapper.invoke(Unknown Source:147)
        at com.facebook.jni.NativeRunnable.run(Native Method)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(Unknown Source:0)
        at android.os.Looper.loop(Looper.java:214)
        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(Unknown Source:37)
        at java.lang.Thread.run(Thread.java:919)
     Caused by: java.lang.AssertionError: java.lang.NoSuchFieldException: EXTERNAL
        at va.n$j0.<init>(Unknown Source:87)
        at va.n$w.b(Unknown Source:27)
        at sa.f.k(Unknown Source:74)
        at va.i.a(Unknown Source:42)
        at va.i.e(Unknown Source:123)
        at va.i.b(Unknown Source:22)
        at sa.f.k(Unknown Source:74)
        at va.b.b(Unknown Source:26)
        at sa.f.k(Unknown Source:74)
        at va.i.a(Unknown Source:42)
        at va.i.e(Unknown Source:123)
        at va.i.b(Unknown Source:22)
        at sa.f.k(Unknown Source:74)
        at va.i.a(Unknown Source:42)
        at va.i.e(Unknown Source:123)
        at va.i.b(Unknown Source:22)
        at sa.f.k(Unknown Source:74)
        at pf.a.d(Unknown Source:6)
        at nf.s.g(Unknown Source:35)
        at nf.s.i(Unknown Source:1)
        at nf.i.e(Unknown Source:4)
        at nf.i.f(Unknown Source:109)
        at nf.t.b(Unknown Source:19)
        at nf.s.d(Unknown Source:24)
        at nf.s$a.invoke(Unknown Source:32)
        at java.lang.reflect.Proxy.invoke(Proxy.java:1006)
        at $Proxy8.k(Unknown Source)
        at f.b.k(Unknown Source:7)
        at c.g.a(Unknown Source:12)
        at vn.payoo.paymentsdk.PayooPaymentSDK$Companion.pay(Unknown Source:13)
        at vn.payoo.paymentsdk.PayooPaymentSDK$Companion.pay(Unknown Source:130)
        at vn.payoo.paymentsdk.PayooPaymentSDK.pay(Unknown Source:5)
        at com.affina.agency.PayooSDKAndroidModule.pay(Unknown Source:214)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.facebook.react.bridge.JavaMethodWrapper.invoke(Unknown Source:148)
        at com.facebook.react.bridge.JavaModuleWrapper.invoke(Unknown Source:147)
        at com.facebook.jni.NativeRunnable.run(Native Method)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(Unknown Source:0)
        at android.os.Looper.loop(Looper.java:214)
        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(Unknown Source:37)
        at java.lang.Thread.run(Thread.java:919)
     Caused by: java.lang.NoSuchFieldException: EXTERNAL
        at java.lang.Class.getField(Class.java:1604)
        at va.n$j0.<init>(Unknown Source:34)
        at va.n$w.b(Unknown Source:27)
        at sa.f.k(Unknown Source:74)
        at va.i.a(Unknown Source:42)
        at va.i.e(Unknown Source:123)
        at va.i.b(Unknown Source:22)
        at sa.f.k(Unknown Source:74)
        at va.b.b(Unknown Source:26)
        at sa.f.k(Unknown Source:74)
        at va.i.a(Unknown Source:42)
        at va.i.e(Unknown Source:123)
        at va.i.b(Unknown Source:22)
        at sa.f.k(Unknown Source:74)
        at va.i.a(Unknown Source:42)
        at va.i.e(Unknown Source:123)
        at va.i.b(Unknown Source:22)
        at sa.f.k(Unknown Source:74)
        at pf.a.d(Unknown Source:6)
        at nf.s.g(Unknown Source:35)
        at nf.s.i(Unknown Source:1)
        at nf.i.e(Unknown Source:4)
        at nf.i.f(Unknown Source:109)
        at nf.t.b(Unknown Source:19)
        at nf.s.d(Unknown Source:24)
        at nf.s$a.invoke(Unknown Source:32)
        at java.lang.reflect.Proxy.invoke(Proxy.java:1006)
        at $Proxy8.k(Unknown Source)
        at f.b.k(Unknown Source:7)
        at c.g.a(Unknown Source:12)
        at vn.payoo.paymentsdk.PayooPaymentSDK$Companion.pay(Unknown Source:13)
        at vn.payoo.paymentsdk.PayooPaymentSDK$Companion.pay(Unknown Source:130)
        at vn.payoo.paymentsdk.PayooPaymentSDK.pay(Unknown Source:5)
        at com.affina.agency.PayooSDKAndroidModule.pay(Unknown Source:214)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.facebook.react.bridge.JavaMethodWrapper.invoke(Unknown Source:148)
        at com.facebook.react.bridge.JavaModuleWrapper.invoke(Unknown Source:147)
        at com.facebook.jni.NativeRunnable.run(Native Method)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(Unknown Source:0)
        at android.os.Looper.loop(Looper.java:214)
        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(Unknown Source:37)
        at java.lang.Thread.run(Thread.java:919)

I added an external library to my React Native application and it worked fine during development, but when I built the release apk, it failed and I still don't have a solution for it.

I tried deleting the gradlew cache and looking at its documentation, but it still didn't work. It still works fine on the development environment, but when I build the release apk, it fails as mentioned above.


问:
Android: MultiChannel Lightining Chart
I am using a Headbox with electrodes to the controller and further connected with an android device. I want to display live channel data using a multichannel lighting chart. Unable to feed the data to the js file.

I tried creating addData function but was unable to go further.

Title: Android: MultiChannel Lightining Chart


问:
Not able to read google sheet using pyscript
the requirement is reading the sheet name from html and opening the file and fetching some values and writing back to same html using pyscript.

```<code><head>
</code>```
  -->

```<code><py-env>
 -gspread
</py-env>
</code>```

```<code><py-script>
from js import console
import gspread
  text = Element('test-input').element.value
  sa = gspread.service_account(filename="filename.json")
sheets = sa.open("googlesheetname")
  wks = sheets.worksheet("sheet1")
  Element('test-output').element.innerText = wks.row_count
</code>```

But whenever i try this i get the below error.

```<code>JsException(PythonError: Traceback (most recent call last): File "/lib/python3.10/site-packages/_pyodide/_base.py", line 429, in eval_code .run(globals, locals) File "/lib/python3.10/site-packages/_pyodide/_base.py", line 300, in run coroutine = eval(self.code, globals, locals) File "", line 2, in ModuleNotFoundError: No module named 'gspread' )
</code>```

But actually gspread package is included and works well when tried to pycharm.

What might be the issue. kindly help.
Thanks in advance

Body:
the requirement is reading the sheet name from html and opening the file and fetching some values and writing back to same html using pyscript.

  -->

<py-env>
 -gspread
</py-env>

<py-script>
from js import console
import gspread
  text = Element('test-input').element.value
  sa = gspread.service_account(filename="filename.json")
sheets = sa.open("googlesheetname")
  wks = sheets.worksheet("sheet1")
  Element('test-output').element.innerText = wks.row_count

But whenever i try this i get the below error.

JsException(PythonError: Traceback (most recent call last): File "/lib/python3.10/site-packages/_pyodide/_base.py", line 429, in eval_code .run(globals, locals) File "/lib/python3.10/site-packages/_pyodide/_base.py", line 300, in run coroutine = eval(self.code, globals, locals) File "", line 2, in ModuleNotFoundError: No module named 'gspread' )

But actually gspread package is included and works well when tried to pycharm.

What might be the issue. kindly help.
Thanks in advance


问:
Angular calendar external event drop to day view scheduler
I am working on the Angular calendar and the requirement is to drop external event to the day timeline to specific user.

I am using day-view-scheduler for day view timeline and external events.
https://mattlewis92.github.io/angular-calendar/#/day-view-scheduler

Problem is when dropping external event to the specific user it will automatically move to the default user which was added in externalEvents, if there was any workaround please let me know.

Demo Gif


问:
How can I switch between Mongo and Postgres using TypeORM with NestJS?
I have written my backend to use MongoDB but I would like to make the existing solution DB agnostic.

Is there an easier way to switch between Postgres and Mongo DB?

When trying to migrate to Postgres I had to manually comment out the ObjectID field (a mandatory primary key for MongoDB).

I would like to know if there is an easier way to define entities in TypeORM without having to manually comment out columns when migrating to different DB


问:
How to fix a page use vis.js?
I have a NET 6 application which has access to SQL Server Graph table. Also it has a page which returns a graph visualization using vis.js.
But during the rendering I receive an error:

```<code>***Fetching
(index):37 ***Now process the JSON
(index):42 Object
(index):55 ***container=[object HTMLDivElement]
(index):56 ***Network
DevTools failed to load source map: Could not load content for http://localhost:5000/js/vis.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
</code>```

That is the page code:

```<code>@page
@model IndexModel
@{
    ViewData["Title"] = "Home";
}

<style>
    body {
        color: #d3d3d3;
        font: 12pt arial;
        background-color: #ffffff;
    }

    #mynetwork {
        width: 800px;
        height: 800px;
        background-color: #fff;
    }
</style>

<div id="mynetwork"></div>

<script type="text/javascript">
    console.log('***Fetching');
    fetch('api/graph/schema')
        .then((response) => {
            console.log('***Now process the JSON');
            // Now process the JSON:
            response.json().then((data) => {

                // Log the data :
                console.log(data);

                // Now display the graph using vis.js:
                var options = {
                    edges: {
                        arrows: {
                            to: { enabled: true },
                            from: { enabled: false }
                        }
                    }
                };

                var container = document.getElementById('mynetwork');
                console.log('***container='+container);
                console.log('***Network');
                new vis.Network(container, data, options);
            });
        })
        .catch((err) => {
            alert("***Fetching Graph Schema Failed: " + err);
        });

</script>
</code>```

How to fix the code?

Title: How to fix a page use vis.js?

Body:
I have a NET 6 application which has access to SQL Server Graph table. Also it has a page which returns a graph visualization using vis.js.
But during the rendering I receive an error:

***Fetching
(index):37 ***Now process the JSON
(index):42 Object
(index):55 ***container=[object HTMLDivElement]
(index):56 ***Network
DevTools failed to load source map: Could not load content for http://localhost:5000/js/vis.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE

That is the page code:

@page
@model IndexModel
@{
    ViewData["Title"] = "Home";
}

How to fix the code?


问:
Use list as value of dictionary in webconfig file C#
In the below file I want to use the values of myList as the value of myDictionary, as some of the values are going to be the same. Is there any way of doing this?

```<code><configuration>
  <configSections>
      <section
     name="MyDictionary"
     type="System.Configuration.NameValueFileSectionHandler,System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>
    <add key ="myList" value="Abc,xyz,test12"/>

    <MyDictionary>
        <add key="k1" value="values of myList here" />
        <add key="k2" value="values of myList here" />
        <add key="k3" value="value3" />
    </MyDictionary>
</configuration>
</code>```

Body:
In the below file I want to use the values of myList as the value of myDictionary, as some of the values are going to be the same. Is there any way of doing this?

<configuration>
  <configSections>

  </configSections>
    <add key ="myList" value="Abc,xyz,test12"/>

    <MyDictionary>
        <add key="k1" value="values of myList here" />
        <add key="k2" value="values of myList here" />
        <add key="k3" value="value3" />
    </MyDictionary>
</configuration>


问:
Unit Testing Azure ServiceBusClient Typescript
So I have this simple bit of code to put messages on a azure queue:

  const sbClient = new ServiceBusClient(process.env.QUEUE_CONNECTION_STRING);
  const sender = sbClient.createSender(process.env.QUEUE_NAME);

  try {
    const user: User = {
      firstname: 'John',
      lastname: 'Deer',
      age: 69,
    };

    await sender.sendMessages({
      body: user,
      contentType: 'application/json',
    });
    await sender.close();
  } catch (error) {
    //handle errors
  } finally {
    await sbClient.close();
  }
```

Now I am looking at unittesting my code, but I have not found a solution online after quite some digging. For axios calls you can stub them and mock the response for example, but I have found nothing of the sort for Azure Service Bus. Do any of you have experience with this? How do I approach this? Is there a way to Mock the ServiceBusClient?

Body:
So I have this simple bit of code to put messages on a azure queue:

  const sbClient = new ServiceBusClient(process.env.QUEUE_CONNECTION_STRING);
  const sender = sbClient.createSender(process.env.QUEUE_NAME);

  try {
    const user: User = {
      firstname: 'John',
      lastname: 'Deer',
      age: 69,
    };

    await sender.sendMessages({
      body: user,
      contentType: 'application/json',
    });
    await sender.close();
  } catch (error) {
    //handle errors
  } finally {
    await sbClient.close();
  }

Now I am looking at unittesting my code, but I have not found a solution online after quite some digging. For axios calls you can stub them and mock the response for example, but I have found nothing of the sort for Azure Service Bus. Do any of you have experience with this? How do I approach this? Is there a way to Mock the ServiceBusClient?


问:
How to enable Element.requestFullscreen on Android WebView?
When opening my page with IOS WKWebview I can use fullscreen in an element by calling requestFullscreen directly from the element.

JS

```<code>var ele = document.getElementByID("myDiv").requestFullscreen()
</code>```

But in order to achieve it I need to enable on my WKWebView this preference:
isElementFullscreenEnabled

This is all the code that I need on IOS
IOS

```<code>struct WebView: UIViewRepresentable {

    var url: URL

    func makeUIView(context: Context) -> WKWebView {
        let configuration = WKWebViewConfiguration()
            configuration.allowsInlineMediaPlayback = true
        return WKWebView(frame: .zero, configuration: configuration)
    }

    func updateUIView(_ webView: WKWebView, context: Context) {
            let request = URLRequest(url: url)
        webView.configuration.allowsInlineMediaPlayback = true
        webView.configuration.preferences.isElementFullscreenEnabled = true
        webView.load(request)
    }
}
</code>```

My question is how can I enable the same javascript feature on Android(kotlin)?

I tried

```<code>// Adding a WebView inside AndroidView
// with layout as full screen
AndroidView(factory = {
    WebView(it).apply {
        layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        webViewClient = WebViewClient()
        webChromeClient= FullScreenClient()

        settings.setDomStorageEnabled(true)
        settings.setJavaScriptEnabled(true)
        settings.setDatabaseEnabled(true)

        loadUrl(mUrl)
    }
}, update = {
    it.loadUrl(mUrl)
})
</code>```

where FullScreenClient is:

```<code>class FullScreenClient : WebChromeClient()
{
    val matchParentLayout: FrameLayout.LayoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.MATCH_PARENT)
    lateinit var content: ViewGroup;
    lateinit var parent: ViewGroup;
    lateinit var customView : View;

    fun FullScreenClient(parent :ViewGroup, content: ViewGroup)
    {
        this.parent = parent;
        this.content = content;
    }

    @Override
    fun OnShowCustomView(view: View, callback: CustomViewCallback)
    {
        customView = view;
        view.layoutParams = matchParentLayout;
        parent.addView(view);
        content.visibility = View.GONE;
    }

    @Override
    fun OnHideCustomView()
    {
        content.visibility = View.VISIBLE;
        parent.removeView(customView)

    }
}
</code>```

How can I enable this feature on Android WebView?
What is the Android equivalent way to:

webView.configuration.preferences.isElementFullscreenEnabled = true

Body:
When opening my page with IOS WKWebview I can use fullscreen in an element by calling requestFullscreen directly from the element.

JS

var ele = document.getElementByID("myDiv").requestFullscreen()

But in order to achieve it I need to enable on my WKWebView this preference:
isElementFullscreenEnabled

This is all the code that I need on IOS
IOS

struct WebView: UIViewRepresentable {

    var url: URL

    func makeUIView(context: Context) -> WKWebView {
        let configuration = WKWebViewConfiguration()
            configuration.allowsInlineMediaPlayback = true
        return WKWebView(frame: .zero, configuration: configuration)
    }

    func updateUIView(_ webView: WKWebView, context: Context) {
            let request = URLRequest(url: url)
        webView.configuration.allowsInlineMediaPlayback = true
        webView.configuration.preferences.isElementFullscreenEnabled = true
        webView.load(request)
    }
}

My question is how can I enable the same javascript feature on Android(kotlin)?

I tried

// Adding a WebView inside AndroidView
// with layout as full screen
AndroidView(factory = {
    WebView(it).apply {
        layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        webViewClient = WebViewClient()
        webChromeClient= FullScreenClient()

        settings.setDomStorageEnabled(true)
        settings.setJavaScriptEnabled(true)
        settings.setDatabaseEnabled(true)

        loadUrl(mUrl)
    }
}, update = {
    it.loadUrl(mUrl)
})

where FullScreenClient is:

class FullScreenClient : WebChromeClient()
{
    val matchParentLayout: FrameLayout.LayoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.MATCH_PARENT)
    lateinit var content: ViewGroup;
    lateinit var parent: ViewGroup;
    lateinit var customView : View;

    fun FullScreenClient(parent :ViewGroup, content: ViewGroup)
    {
        this.parent = parent;
        this.content = content;
    }

    @Override
    fun OnShowCustomView(view: View, callback: CustomViewCallback)
    {
        customView = view;
        view.layoutParams = matchParentLayout;
        parent.addView(view);
        content.visibility = View.GONE;
    }

    @Override
    fun OnHideCustomView()
    {
        content.visibility = View.VISIBLE;
        parent.removeView(customView)

    }
}

How can I enable this feature on Android WebView?
What is the Android equivalent way to:

webView.configuration.preferences.isElementFullscreenEnabled = true


问:
javascript proxy - How to trigger the proxy set method when updating original object
This is my code

const obj = {
  history: [],
  update: ''
}
window.dataSubscriber = new Proxy(obj, {
  set: function (target, key, value) {
    // This does not get called.
    window.dataSubscriber.history.push(value);
    target[key] = value;
    return value;
  }
});

obj.update = 'Mike';

console.log(window.dataSubscriber)
```
<blockquote>
<p>output:</p>
</blockquote>
<pre class="lang-js prettyprint-override"><code> {
  "history": [], // Expecting this to be populated, but the proxy 'set' method doesn't get called.
  "update": "Mike"
}
</code>```

The subscriber picks up the original value but the proxy 'set' method never gets called.

Note: I know I can trigger the 'set' with window.dataSubscriber.update = 'john', but I need to trigger it directly by the original object.

Body:
This is my code

const obj = {
  history: [],
  update: ''
}
window.dataSubscriber = new Proxy(obj, {
  set: function (target, key, value) {
    // This does not get called.
    window.dataSubscriber.history.push(value);
    target[key] = value;
    return value;
  }
});

obj.update = 'Mike';

console.log(window.dataSubscriber)

output:

 {
  "history": [], // Expecting this to be populated, but the proxy 'set' method doesn't get called.
  "update": "Mike"
}

The subscriber picks up the original value but the proxy 'set' method never gets called.

Note: I know I can trigger the 'set' with window.dataSubscriber.update = 'john', but I need to trigger it directly by the original object.


问:
Digital signature with gnostice pdftoolkit vcl
I'm trying to sign multiple documents with Embarcadero C++ Builder 11.2 and Gnostice PDFToolkit VCL, but it only signs the first one. In the second it gives an error that I attach. Does somebody knows why it could be?
This is the code:

```<code>for(int i=0; i<FileListBox1->Items->Count; i++){
        if(FileExists(FileListBox1->Items->Strings[i])){
            FileListBox1->Selected[i] =  true;
            try{
                gtPDFDocumento->LoadFromFile(FileListBox1->Items->Strings[i]);
                gtPDFDocumento->AddSignature("firma.pfx", "pass", Now(), "texto", "Toledo", "925.28.39.50", 2 , "Firma Digital IACLM", gtRect(365, 935, 760, 990), LDisplayOptions, c, FT);
                gtPDFDocumento->SaveToFile("firmado."+FileListBox1->Items->Strings[i]);

                //Liberar recursos
                gtPDFDocumento->Reset();

                FreeAndNil(gtPDFDocumento);
            }
            catch(Exception *e){
                ShowMessage("Ha ocurrido el error: "+e->Message+", avise a infórmatica.");
                ShowMessage("Error. No se ha podido firmar la liquidación, hable con informática.");
                return;
            }
        }
        else{
            ShowMessage("Error. No se encuentra el PDF, hable con informática.");
            return;
        }
}
</code>```

Thanks.

I'm trying to sign multiple documents with Embarcadero C++ Builder 11.2 and Gnostice PDFToolkit VCL, but it only signs the first one. In the second it gives an error that I attach

Body:
I'm trying to sign multiple documents with Embarcadero C++ Builder 11.2 and Gnostice PDFToolkit VCL, but it only signs the first one. In the second it gives an error that I attach. Does somebody knows why it could be?
This is the code:

for(int i=0; i<FileListBox1->Items->Count; i++){
        if(FileExists(FileListBox1->Items->Strings[i])){
            FileListBox1->Selected[i] =  true;
            try{
                gtPDFDocumento->LoadFromFile(FileListBox1->Items->Strings[i]);
                gtPDFDocumento->AddSignature("firma.pfx", "pass", Now(), "texto", "Toledo", "925.28.39.50", 2 , "Firma Digital IACLM", gtRect(365, 935, 760, 990), LDisplayOptions, c, FT);
                gtPDFDocumento->SaveToFile("firmado."+FileListBox1->Items->Strings[i]);

                //Liberar recursos
                gtPDFDocumento->Reset();

                FreeAndNil(gtPDFDocumento);
            }
            catch(Exception *e){
                ShowMessage("Ha ocurrido el error: "+e->Message+", avise a infórmatica.");
                ShowMessage("Error. No se ha podido firmar la liquidación, hable con informática.");
                return;
            }
        }
        else{
            ShowMessage("Error. No se encuentra el PDF, hable con informática.");
            return;
        }
}

Thanks.

I'm trying to sign multiple documents with Embarcadero C++ Builder 11.2 and Gnostice PDFToolkit VCL, but it only signs the first one. In the second it gives an error that I attach


问:
Is it possible to create an OData query from a nested SQL query without 'ANY' function?
I want to convert the below SQL query into OData query. Is it even possible with nested query and without any function?

SELECT distinct mid, iid
FROM test_table
where mid not in (
    SELECT mid
    FROM test_table
    WHERE resp IS NOT NULL
) AND iid not in (
    SELECT iid
    FROM test_table
    WHERE resp IS NOT NULL
)
```

I can't use any function because it is not supported by Azure Logic App.

Body:
I want to convert the below SQL query into OData query. Is it even possible with nested query and without any function?

SELECT distinct mid, iid
FROM test_table
where mid not in (
    SELECT mid
    FROM test_table
    WHERE resp IS NOT NULL
) AND iid not in (
    SELECT iid
    FROM test_table
    WHERE resp IS NOT NULL
)

I can't use any function because it is not supported by Azure Logic App.


问:
Using Serenity Screenplay pattern waiting an element causes problems locating it
First of all i need to locate this element:

<input aria-checked="false" id="input-190" role="switch" type="checkbox" aria-disabled="false" value="">

so i have created this Target:

```<code>public class Page  {
      public static final Target SWITCH_INPUT = Target.the("switch input")
            .locatedBy("//input[@role='switch']")
            .waitingForNoMoreThan(Duration.ofSeconds(20));
}
</code>```

and in another class need to locate this target and get the attribute aria-checked

```<code>var ariaChecked = actor.asksFor(Attribute.of(SWITCH_INPUT, "aria-checked"));
</code>```

and here occurs something too odd to me, if i remove the waitingForNoMoreThan(Duration.ofSeconds(20)) from my target definition, the actor can locate that target but by having the waitingForNoMoreThan in place, it returns empty string because the element is null.

Is this normal? I feel that the opposite is a legit scenario.

Body:
First of all i need to locate this element:

<input aria-checked="false" id="input-190" role="switch" type="checkbox" aria-disabled="false" value="">

so i have created this Target:

public class Page  {
      public static final Target SWITCH_INPUT = Target.the("switch input")
            .locatedBy("//input[@role='switch']")
            .waitingForNoMoreThan(Duration.ofSeconds(20));
}

and in another class need to locate this target and get the attribute aria-checked

var ariaChecked = actor.asksFor(Attribute.of(SWITCH_INPUT, "aria-checked"));

and here occurs something too odd to me, if i remove the waitingForNoMoreThan(Duration.ofSeconds(20)) from my target definition, the actor can locate that target but by having the waitingForNoMoreThan in place, it returns empty string because the element is null.

Is this normal? I feel that the opposite is a legit scenario.


问:
How to prevent that CronJob is not run more than once
I have a plan to check the table if it has records, the python program process them.So, I must use CronJob to check the table in every two hours.
I wrote the bash script which is in following:

```<code> #!/bin/bash
 if [ -f "/tmp/process.is.running" ]
    then
       echo "Another instance of the script is running. Aborting."
       exit
 fi;
 if [ ! -f "/tmp/process.is.running" ]
    then
       echo "File is Created."
       touch  "/tmp/process.is.running"
       echo "File Created Done."
       cd /root/process
       /usr/bin/python3.8 function.py
       cd /root/Desktop
       echo > logFile.txt
       rm "/tmp/process.is.running"
       echo "File is Deleted."
    fi;
</code>```

I saved that bash file as "process.sh". Also,I already created "logFile.txt" to show the print messages.
Also, the crontab file is like this:

```<code>    SHELL=/bin/bash
    BASH_ENV=~/.bashrc
    0  */2 * * *  /usr/bin/bash /root/Desktop/process.sh >> /root/Desktop/logFile.txt
</code>```

I use "/tmp/process.is.running" to be sure that the program not run more than once. However, when I run this code, see two instance of the cronjob.

```<code>   ps -A | grep cron
</code>```

Result is here:

```<code>   3232323 ?  00:00:01 crond
   2121212 ?  00:00:00 crond
</code>```

Would you please guid me how to prevent cronjob not to run more than once?

Any help is really appreciated.

Body:
I have a plan to check the table if it has records, the python program process them.So, I must use CronJob to check the table in every two hours.
I wrote the bash script which is in following:

 #!/bin/bash
 if [ -f "/tmp/process.is.running" ]
    then
       echo "Another instance of the script is running. Aborting."
       exit
 fi;
 if [ ! -f "/tmp/process.is.running" ]
    then
       echo "File is Created."
       touch  "/tmp/process.is.running"
       echo "File Created Done."
       cd /root/process
       /usr/bin/python3.8 function.py
       cd /root/Desktop
       echo > logFile.txt
       rm "/tmp/process.is.running"
       echo "File is Deleted."
    fi;

I saved that bash file as "process.sh". Also,I already created "logFile.txt" to show the print messages.
Also, the crontab file is like this:

    SHELL=/bin/bash
    BASH_ENV=~/.bashrc
    0  */2 * * *  /usr/bin/bash /root/Desktop/process.sh >> /root/Desktop/logFile.txt

I use "/tmp/process.is.running" to be sure that the program not run more than once. However, when I run this code, see two instance of the cronjob.

   ps -A | grep cron

Result is here:

   3232323 ?  00:00:01 crond
   2121212 ?  00:00:00 crond

Would you please guid me how to prevent cronjob not to run more than once?

Any help is really appreciated.


问:
Need to run powershell script asynchronously on remote when a request hits webapi
I am using System.Management.Automation assembly for this

Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
                try
                {
                  runspace.Open();
                }
                catch (Exception ex)
                {
                    Logger.Error("Unable to connect to remote machine" + ex.Message);
                    //Console.WriteLine("Unable to connect to remote machine");
                }

                    Pipeline pipeline;
                    using (PowerShell ps = PowerShell.Create())
                    {
                        try
                        {
                            ps.Runspace = runspace;
                            pipeline = ps.Runspace.CreatePipeline();
                            Command command = new       Command(ConfigurationManager.AppSettings["ScriptPath"].ToString());
                            command.Parameters.Add("inputobj", ConvertModeltoPsobject(obj));
                            pipeline.Commands.Add(command);
                            pipeline.Input.Close();
                            pipeline.InvokeAsync();
                             while (pipeline.PipelineStateInfo.State != PipelineState.Running)
                        {
                            await Task.Delay(100);
                        }}
                        catch (Exception e)
                        {
                            //problem running script
                            Logger.Error(e.Message);
                        }

                    }
                runspace.Close();
```

This is working when single request hits the api but when multiple requests hit its only processing the first one.

The powershell script on the remote copy files from that server other server.that's why it is taking time and we are checking the condition pipeline.PipelineStateInfo.State != PipelineState.Running

I have tried creating RunspacePool but facing an error that method is not supported.
RunspaceFactory.CreateRunspacePool(minRunspaces, maxRunspaces, connectionInfo)

Is there any reason why RunspaceFactory.CreateRunspacePool(minRunspaces, maxRunspaces, connectionInfo) is not supporting.

Body:
I am using System.Management.Automation assembly for this

Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
                try
                {
                  runspace.Open();
                }
                catch (Exception ex)
                {
                    Logger.Error("Unable to connect to remote machine" + ex.Message);
                    //Console.WriteLine("Unable to connect to remote machine");
                }

                    Pipeline pipeline;
                    using (PowerShell ps = PowerShell.Create())
                    {
                        try
                        {
                            ps.Runspace = runspace;
                            pipeline = ps.Runspace.CreatePipeline();
                            Command command = new       Command(ConfigurationManager.AppSettings["ScriptPath"].ToString());
                            command.Parameters.Add("inputobj", ConvertModeltoPsobject(obj));
                            pipeline.Commands.Add(command);
                            pipeline.Input.Close();
                            pipeline.InvokeAsync();
                             while (pipeline.PipelineStateInfo.State != PipelineState.Running)
                        {
                            await Task.Delay(100);
                        }}
                        catch (Exception e)
                        {
                            //problem running script
                            Logger.Error(e.Message);
                        }

                    }
                runspace.Close();

This is working when single request hits the api but when multiple requests hit its only processing the first one.

The powershell script on the remote copy files from that server other server.that's why it is taking time and we are checking the condition pipeline.PipelineStateInfo.State != PipelineState.Running

I have tried creating RunspacePool but facing an error that method is not supported.
RunspaceFactory.CreateRunspacePool(minRunspaces, maxRunspaces, connectionInfo)

Is there any reason why RunspaceFactory.CreateRunspacePool(minRunspaces, maxRunspaces, connectionInfo) is not supporting.


问:
how to avoid overlapping requests when creating new objects?
```<code>def artist(request):
    print("START")
    if request.method == "GET":
        try:
            artist = Artist.objects.get(user=request.user)
            print("artist exists")
        except Artist.DoesNotExist:
            print("artist doesn't exist")
            artist = Artist.objects.get_or_create(user=request.user)[0]
            print("a new artist object has been created")

        return HttpResponse(status=200)
</code>```

Console:

```<code>START
artist doesn't exist
START
artist doesn't exist
a new artist object has been created
[15/Dec/2022 12:40:23] "GET /artist/ HTTP/1.1" 200 0
a new artist object has been created
[15/Dec/2022 12:40:23] "GET /artist/ HTTP/1.1" 200 0
</code>```

on the client side, there is a button on the screen that sends a request that returns to the user their artist page, or if they don't have one, it will be created for them. And suppose he double clicks the button, then two objects will be created.  The user field in the Artist is not unique, we ignore the fact that we can solve the problem on the client side with javascript and we assume that the server is a bit slow, so it doesn't have time to process two requests in such a short time.

The Artist model has a field that at the time of creation must be populated with some information based on their profile picture, i.e. i extract the dominant color from their picture to use it later on the page, it's irrelevant, we just assume it takes a bit longer to create

I also want to create the object without a form, I will use a form later to update the profile if the user wants. Also ignore creating the Artist object once the user is created ( using the signal thing)

Body:
def artist(request):
    print("START")
    if request.method == "GET":
        try:
            artist = Artist.objects.get(user=request.user)
            print("artist exists")
        except Artist.DoesNotExist:
            print("artist doesn't exist")
            artist = Artist.objects.get_or_create(user=request.user)[0]
            print("a new artist object has been created")

        return HttpResponse(status=200)

Console:

START
artist doesn't exist
START
artist doesn't exist
a new artist object has been created
[15/Dec/2022 12:40:23] "GET /artist/ HTTP/1.1" 200 0
a new artist object has been created
[15/Dec/2022 12:40:23] "GET /artist/ HTTP/1.1" 200 0

on the client side, there is a button on the screen that sends a request that returns to the user their artist page, or if they don't have one, it will be created for them. And suppose he double clicks the button, then two objects will be created.  The user field in the Artist is not unique, we ignore the fact that we can solve the problem on the client side with javascript and we assume that the server is a bit slow, so it doesn't have time to process two requests in such a short time.

The Artist model has a field that at the time of creation must be populated with some information based on their profile picture, i.e. i extract the dominant color from their picture to use it later on the page, it's irrelevant, we just assume it takes a bit longer to create

I also want to create the object without a form, I will use a form later to update the profile if the user wants. Also ignore creating the Artist object once the user is created ( using the signal thing)


问:
How to iterate Record type correctly
I have some predefined values that I want to use as keys in my Record object

```<code>export type Products =
  typeof CAR
  | typeof TRUCK
  | typeof MOTORCYCLE;
</code>```

I have another type that's using the Products type as such:

```<code>export type Status =
  Record<Products, {
    active: boolean,
    display: boolean
  }>
</code>```

I want to get from my Status object only those that have active property set to true

I tried something like that:

```<code> Object.keys(data).filter((key) => status[key].active); // data is of Status type
</code>```

I'm getting this error, that I would like to get rid of:

```<code>Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Status'.
</code>```

Am I doing filtering correctly or is there a better approach I can use?

Title: How to iterate Record type correctly

Body:
I have some predefined values that I want to use as keys in my Record object

export type Products =
  typeof CAR
  | typeof TRUCK
  | typeof MOTORCYCLE;

I have another type that's using the Products type as such:

export type Status =
  Record<Products, {
    active: boolean,
    display: boolean
  }>

I want to get from my Status object only those that have active property set to true

I tried something like that:

 Object.keys(data).filter((key) => status[key].active); // data is of Status type

I'm getting this error, that I would like to get rid of:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Status'.

Am I doing filtering correctly or is there a better approach I can use?


问:
JaCoCo coverage reports in multi module project with surefire
I have a project with multiple modules.

module1

module2

module3

testModule:

src/main/java:

com.example.test

some legacy I cannot get rid of

src/test/java:

com.example.test:

actual test classes
pom.xml (in testModule)

pom.xml(root pom)

content of testModule pom:

```<code><build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.sonarsource.scanner.maven</groupId>
                    <artifactId>sonar-maven-plugin</artifactId>
                    <version>${versionSonarMavenPlugin}</version>
                </plugin>
                <plugin>
                    <groupId>org.jacoco</groupId>
                    <artifactId>jacoco-maven-plugin</artifactId>
                    <version>${versionJacoco}</version>
                    <configuration>
                        <skip>${skipCoverage}</skip>
                        <destFile>${sonar.jacoco.reportPath}</destFile>
                        <append>true</append>
                    </configuration>
                    <executions>
                        <execution>
                            <id>jacoco-init</id>
                            <goals>
                                <goal>prepare-agent</goal>
                            </goals>
                        </execution>
                        <execution>
                            <id>jacoco-report</id>
                            <phase>verify</phase>
                            <goals>
                                <goal>report</goal>
                            </goals>
                            <configuration>
                                <formats>HTML,XML,CSV</formats>
                                <outputDirectory>my-output-path/target</outputDirectory>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>${versionSurefirePlugin}</version>
                    <configuration>
                        <argLine>${surefireArgLine} -Xms256m -Xmx2048m</argLine>
                        <includes>
                            <include>**/*Test.java</include>
                        </includes>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>

    </build>
</code>```

A coverage report is generated, but only containing the tests in testModule/src/main/java. The tests in
testModule/src/test/java are not part of the report.

Does anyone know how I can add this folder so the reports cover all the tests?

versionJacoco: 0.8.8
surfire: v3.0.0-M7

I tried using

```<code>testSourceDirectory
</code>```

and

```<code>includes
</code>```

Body:
I have a project with multiple modules.

module1

module2

module3

testModule:

src/main/java:

com.example.test

some legacy I cannot get rid of

src/test/java:

com.example.test:

actual test classes
pom.xml (in testModule)

pom.xml(root pom)

content of testModule pom:

<build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.sonarsource.scanner.maven</groupId>
                    <artifactId>sonar-maven-plugin</artifactId>
                    <version>${versionSonarMavenPlugin}</version>
                </plugin>
                <plugin>
                    <groupId>org.jacoco</groupId>
                    <artifactId>jacoco-maven-plugin</artifactId>
                    <version>${versionJacoco}</version>
                    <configuration>
                        <skip>${skipCoverage}</skip>
                        <destFile>${sonar.jacoco.reportPath}</destFile>
                        <append>true</append>
                    </configuration>
                    <executions>
                        <execution>
                            <id>jacoco-init</id>
                            <goals>
                                <goal>prepare-agent</goal>
                            </goals>
                        </execution>
                        <execution>
                            <id>jacoco-report</id>
                            <phase>verify</phase>
                            <goals>
                                <goal>report</goal>
                            </goals>
                            <configuration>
                                <formats>HTML,XML,CSV</formats>
                                <outputDirectory>my-output-path/target</outputDirectory>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>${versionSurefirePlugin}</version>
                    <configuration>
                        <argLine>${surefireArgLine} -Xms256m -Xmx2048m</argLine>
                        <includes>
                            <include>**/*Test.java</include>
                        </includes>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>

    </build>

A coverage report is generated, but only containing the tests in testModule/src/main/java. The tests in
testModule/src/test/java are not part of the report.

Does anyone know how I can add this folder so the reports cover all the tests?

versionJacoco: 0.8.8
surfire: v3.0.0-M7

I tried using

testSourceDirectory

and

includes