问:
C# generate certificate based on template from Active Directory Certificate Services
Using the CA web page https://{CAServerName}/certsrv/certrqma.asp, I can manually create a request based on the template and install the certificate after approval.

How to do the same but in c#?

答:
This is my first time working with certificates and this is what I got.

While searching, I found 2 useful articles:

How to work with certreq

How to create a certificate request with CertEnroll and .NET (C#)

In the first case, I understood how to form a request.

Here is an example:

req.inf

[NewRequest]

Subject = ""

KeyLength = 2048

RequestType = PKCS10

ProviderName = "Microsoft Enhanced Cryptographic Provider v1.0"

[RequestAttributes]

CertificateTemplate = ""

Subject - Certificate-Details-Subject.

CertificateTemplate - get frendly name from Certificate-Details-Subject, search TemplatePropFriendlyName in "certutil.exe -Template" and get  TemplatePropCommonName.

```<code>certreq -q -new req.inf req.req
certreq -config "CAHostName.domain.local\CAName" -submit "req.req" "cert.cer"
certreq -accept "cert.cer"
</code>```

In the second case, I took example and reduced it a bit.

```<code>public class TestCertManager
{
    private const int CC_DEFAULTCONFIG = 0;
    private const int CC_UIPICKCONFIG = 0x1;
    private const int CR_IN_BASE64 = 0x1;
    private const int CR_IN_FORMATANY = 0;
    private const int CR_IN_PKCS10 = 0x100;
    private const int CR_DISP_ISSUED = 0x3;
    private const int CR_DISP_UNDER_SUBMISSION = 0x5;
    private const int CR_OUT_BASE64 = 0x1;
    private const int CR_OUT_CHAIN = 0x100;
    // Create request
    public string CreateRequest()
    {
        string subject = "<subject>";
        string templateName = "<templateName>";
        //  Create all the objects that will be required
        CX509CertificateRequestPkcs10 objPkcs10 = new CX509CertificateRequestPkcs10();
        CX509PrivateKey objPrivateKey = new CX509PrivateKey();
        CCspInformation objCSP = new CCspInformation();
        CCspInformations objCSPs = new CCspInformations();
        CX500DistinguishedName objDN = new CX500DistinguishedName();
        CX509Enrollment objEnroll = new CX509Enrollment();
        //  Initialize the csp object using the desired Cryptograhic Service Provider (CSP)
        objCSP.InitializeFromName("Microsoft Enhanced Cryptographic Provider v1.0");
        //  Add this CSP object to the CSP collection object
        objCSPs.Add(objCSP);
        objPrivateKey.Length = 2048;
        objPrivateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE;
        objPrivateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES;
        objPrivateKey.MachineContext = false;
        //  Provide the CSP collection object (in this case containing only 1 CSP object)
        //  to the private key object
        objPrivateKey.CspInformations = objCSPs;
        //  Create the actual key pair
        objPrivateKey.Create();
        //  provide a template name
    objPkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser,objPrivateKey, templateName);
        //  Encode the name in using the Distinguished Name object
        objDN.Encode(
            subject,
            X500NameFlags.XCN_CERT_NAME_STR_NONE
        );
        //  Assing the subject name by using the Distinguished Name object initialized above
        objPkcs10.Subject = objDN;
        // Create enrollment request
        objEnroll.InitializeFromRequest(objPkcs10);
        string strRequest = objEnroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64);
        return strRequest;
    }
    // Submit request to CA and get response
    public string SendRequest(string strRequest)
    {
        //  Create all the objects that will be required
        CCertConfig objCertConfig = new CCertConfig();
        CCertRequest objCertRequest = new CCertRequest();
        string strCAConfig = @"CAHostName\CAName";
        int iDisposition;
        string strDisposition;
        string strCert;
        // Submit the request
        iDisposition = objCertRequest.Submit(CR_IN_BASE64 | CR_IN_FORMATANY, strRequest, null, strCAConfig);
        // Check the submission status
        if (CR_DISP_ISSUED != iDisposition) // Not enrolled
        {
            strDisposition = objCertRequest.GetDispositionMessage();
            if (CR_DISP_UNDER_SUBMISSION == iDisposition) // Pending
            {
                Console.WriteLine("The submission is pending: " + strDisposition);
                return "";
            }
            else // Failed
            {
                Console.WriteLine("The submission failed: " + strDisposition);
                Console.WriteLine("Last status: " + objCertRequest.GetLastStatus().ToString());
                return "";
            }

        }
        // Get the certificate
        strCert = objCertRequest.GetCertificate(CR_OUT_BASE64 | CR_OUT_CHAIN);
        return strCert;
    }
    // Install response from CA
    public void AcceptPKCS7(string strCert)
    {
        //  Create all the objects that will be required
        CX509Enrollment objEnroll = new CX509Enrollment();
        // Install the certificate
        objEnroll.Initialize(X509CertificateEnrollmentContext.ContextUser);

        objEnroll.InstallResponse(
            InstallResponseRestrictionFlags.AllowUntrustedRoot,
            strCert,
            EncodingType.XCN_CRYPT_STRING_BASE64,
            null
        );
        Console.WriteLine("Certificate installed!");
    }
}
</code>```

I'm still looking for the best solution, but at least I have 2 working options.

Body:
This is my first time working with certificates and this is what I got.

While searching, I found 2 useful articles:

How to work with certreq

How to create a certificate request with CertEnroll and .NET (C#)

In the first case, I understood how to form a request.

Here is an example:

req.inf

[NewRequest]

Subject = ""

KeyLength = 2048

RequestType = PKCS10

ProviderName = "Microsoft Enhanced Cryptographic Provider v1.0"

[RequestAttributes]

CertificateTemplate = ""

Subject - Certificate-Details-Subject.

CertificateTemplate - get frendly name from Certificate-Details-Subject, search TemplatePropFriendlyName in "certutil.exe -Template" and get  TemplatePropCommonName.

certreq -q -new req.inf req.req
certreq -config "CAHostName.domain.local\CAName" -submit "req.req" "cert.cer"
certreq -accept "cert.cer"

In the second case, I took example and reduced it a bit.

public class TestCertManager
{
    private const int CC_DEFAULTCONFIG = 0;
    private const int CC_UIPICKCONFIG = 0x1;
    private const int CR_IN_BASE64 = 0x1;
    private const int CR_IN_FORMATANY = 0;
    private const int CR_IN_PKCS10 = 0x100;
    private const int CR_DISP_ISSUED = 0x3;
    private const int CR_DISP_UNDER_SUBMISSION = 0x5;
    private const int CR_OUT_BASE64 = 0x1;
    private const int CR_OUT_CHAIN = 0x100;
    // Create request
    public string CreateRequest()
    {
        string subject = "<subject>";
        string templateName = "<templateName>";
        //  Create all the objects that will be required
        CX509CertificateRequestPkcs10 objPkcs10 = new CX509CertificateRequestPkcs10();
        CX509PrivateKey objPrivateKey = new CX509PrivateKey();
        CCspInformation objCSP = new CCspInformation();
        CCspInformations objCSPs = new CCspInformations();
        CX500DistinguishedName objDN = new CX500DistinguishedName();
        CX509Enrollment objEnroll = new CX509Enrollment();
        //  Initialize the csp object using the desired Cryptograhic Service Provider (CSP)
        objCSP.InitializeFromName("Microsoft Enhanced Cryptographic Provider v1.0");
        //  Add this CSP object to the CSP collection object
        objCSPs.Add(objCSP);
        objPrivateKey.Length = 2048;
        objPrivateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE;
        objPrivateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES;
        objPrivateKey.MachineContext = false;
        //  Provide the CSP collection object (in this case containing only 1 CSP object)
        //  to the private key object
        objPrivateKey.CspInformations = objCSPs;
        //  Create the actual key pair
        objPrivateKey.Create();
        //  provide a template name
    objPkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser,objPrivateKey, templateName);
        //  Encode the name in using the Distinguished Name object
        objDN.Encode(
            subject,
            X500NameFlags.XCN_CERT_NAME_STR_NONE
        );
        //  Assing the subject name by using the Distinguished Name object initialized above
        objPkcs10.Subject = objDN;
        // Create enrollment request
        objEnroll.InitializeFromRequest(objPkcs10);
        string strRequest = objEnroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64);
        return strRequest;
    }
    // Submit request to CA and get response
    public string SendRequest(string strRequest)
    {
        //  Create all the objects that will be required
        CCertConfig objCertConfig = new CCertConfig();
        CCertRequest objCertRequest = new CCertRequest();
        string strCAConfig = @"CAHostName\CAName";
        int iDisposition;
        string strDisposition;
        string strCert;
        // Submit the request
        iDisposition = objCertRequest.Submit(CR_IN_BASE64 | CR_IN_FORMATANY, strRequest, null, strCAConfig);
        // Check the submission status
        if (CR_DISP_ISSUED != iDisposition) // Not enrolled
        {
            strDisposition = objCertRequest.GetDispositionMessage();
            if (CR_DISP_UNDER_SUBMISSION == iDisposition) // Pending
            {
                Console.WriteLine("The submission is pending: " + strDisposition);
                return "";
            }
            else // Failed
            {
                Console.WriteLine("The submission failed: " + strDisposition);
                Console.WriteLine("Last status: " + objCertRequest.GetLastStatus().ToString());
                return "";
            }

        }
        // Get the certificate
        strCert = objCertRequest.GetCertificate(CR_OUT_BASE64 | CR_OUT_CHAIN);
        return strCert;
    }
    // Install response from CA
    public void AcceptPKCS7(string strCert)
    {
        //  Create all the objects that will be required
        CX509Enrollment objEnroll = new CX509Enrollment();
        // Install the certificate
        objEnroll.Initialize(X509CertificateEnrollmentContext.ContextUser);

        objEnroll.InstallResponse(
            InstallResponseRestrictionFlags.AllowUntrustedRoot,
            strCert,
            EncodingType.XCN_CRYPT_STRING_BASE64,
            null
        );
        Console.WriteLine("Certificate installed!");
    }
}

I'm still looking for the best solution, but at least I have 2 working options.


来源: stackexchange

问:
Powershell- how to get a one-line command to find a string and replace it by adding 2 new lines
Is it possible in Powershell to get a single line command to find a string and replace it by adding 2 new lines with a different value leaving the beginning and end of the file unchanged?

(Get-Content -Path C:\test.txt) -replace 'aaa=0','aaa=20 \n\r g=11111 \n\r g=2222' | Set-Content -Path C:\test.txt)

source file:

test=txt

dds=1aa

ab=test

aaa=0

bbb=4444

target file:

test=txt

dds=1aa

aaa=20

g=11111

g=2222

bbb=4444

答:
To insert CRLF without adding literal newlines in the source code, use the `r</code> and <code>`n escape sequences in an expandable string:

```<code>... -replace 'aaa=0',"aaa=20 `r`ng=11111 `r`ng=2222"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
To insert CRLF without adding literal newlines in the source code, use the `r</code> and <code>`n escape sequences in an expandable string:

... -replace 'aaa=0',"aaa=20 `r`ng=11111 `r`ng=2222"


问:
How to add kaleido package to poetry.lock file?
When attempting to install "kaleido" via Poetry, I receive the following error message:

```<code>~ poetry add kaleido
Using version ^0.2.1 for kaleido

Updating dependencies
Resolving dependencies... (3.1s)

Package operations: 1 install, 0 updates, 0 removals

  • Installing kaleido (0.2.1.post1): Failed

  RuntimeError

  Unable to find installation candidates for kaleido (0.2.1.post1)

  at ~/.poetry/lib/poetry/installation/chooser.py:72 in choose_for
       68│
       69│             links.append(link)
       70│
       71│         if not links:
    →  72│             raise RuntimeError(
       73│                 "Unable to find installation candidates for {}".format(package)
       74│             )
       75│
       76│         # Get the best link
</code>```

However, the "kaleido" appears in the poetry.lock file:

```<code>[[package]]
name = "kaleido"
version = "0.2.1.post1"
description = "Static image export for web-based visualization libraries with zero dependencies"
category = "main"
optional = false
python-versions = "*"
</code>```

If I try to export an image, I unsurprisingly receive the following error message:

```<code>ValueError:
Image export using the "kaleido" engine requires the kaleido package,
which can be installed using pip:
    $ pip install -U kaleido
</code>```

Does anyone know how to install this package via poetry (or amend the .lock file to do it manually)?

答:
Firstly try to use a master version of poetry as advised in Github issue

or upgrade it to the latest version

pip3 install --upgrade poetry
```
<p>Then try to install with <code>kaleido</code> with locked version:</p>
<pre class="lang-sh prettyprint-override"><code>poetry add kaleido==0.2.1
</code>```

That worked in my case.

Body:
When attempting to install "kaleido" via Poetry, I receive the following error message:

~ poetry add kaleido
Using version ^0.2.1 for kaleido

Updating dependencies
Resolving dependencies... (3.1s)

Package operations: 1 install, 0 updates, 0 removals

  • Installing kaleido (0.2.1.post1): Failed

  RuntimeError

  Unable to find installation candidates for kaleido (0.2.1.post1)

  at ~/.poetry/lib/poetry/installation/chooser.py:72 in choose_for
       68│
       69│             links.append(link)
       70│
       71│         if not links:
    →  72│             raise RuntimeError(
       73│                 "Unable to find installation candidates for {}".format(package)
       74│             )
       75│
       76│         # Get the best link

However, the "kaleido" appears in the poetry.lock file:

[[package]]
name = "kaleido"
version = "0.2.1.post1"
description = "Static image export for web-based visualization libraries with zero dependencies"
category = "main"
optional = false
python-versions = "*"

If I try to export an image, I unsurprisingly receive the following error message:

ValueError:
Image export using the "kaleido" engine requires the kaleido package,
which can be installed using pip:
    $ pip install -U kaleido

Does anyone know how to install this package via poetry (or amend the .lock file to do it manually)?

Body:
Firstly try to use a master version of poetry as advised in Github issue

or upgrade it to the latest version

pip3 install --upgrade poetry

Then try to install with kaleido with locked version:

poetry add kaleido==0.2.1

That worked in my case.


问:
how to use grpc proto type Struct in nest.js
hey i am trying to implement nest js microservice with grpc.
it looks impossible to use nestjs microservice with struct type for plain objects.

how can i use compiled protos with nestjs ?

imports: [
  ClientsModule.register([
    {
      name: 'HERO_PACKAGE',
      transport: Transport.GRPC,
      options: {
        package: 'hero',
        protoPath: join(__dirname, 'hero/hero.proto'),
      },
    },
  ]),
];```

how can i load the compiled protos. something like https://medium.com/@waynelpu/how-to-pass-plain-javascript-object-with-gprc-94a91906ab1c

答:
I'm maybe late but I found an answer.

Imagine you have the following protobuf

// task.proto
syntax = "proto3";

// Area API
package task;

// Imports
import "google/protobuf/struct.proto";
import "google/protobuf/empty.proto";

message Task {
    string name = 1;

    // Any additional metadata required to execute the task
    google.protobuf.Struct params = 2;
}

service TaskService {
   rpc CreateTask(CreateTaskRequest) returns (Task)
}

message CreateTaskRequest {
  string name = 1;

  google.protobuf.Struct params = 2;
}
```
<p>You will need to add an option in your module to correctly load object</p>
<pre class="lang-js prettyprint-override"><code>    await app.connectMicroservice<MicroserviceOptions>({
        transport: Transport.GRPC,
        options: {
            package: [ 'task' ],
            protoPath: [ __dirname + '/protos/task.proto' ],
            url: `${host}:${port}`,
            loader: {
                objects: true // This property
            }
        },
    });
</code>```

And then in the resolver, you will retrieve a structure that his gRPC Struct compliant, you can find more information here.

Now imagine that you execute a rpc call to CreateTask (Postman has a great beta client for example)

{
  "name": "fugiat qui laboris dolore",
  "params": {
    "fields": {
      "foo": {
        "stringValue": "bar"
      },
      "bar": {
        "numberValue": 4
      },
      "baz": {
        "boolValue": false
      }
    }
  }
}
```
<p>You will correctly retrieve it in your handler</p>
<pre class="lang-js prettyprint-override"><code>    async createTask(@Payload(new ValidationPipe({ whitelist: true })) req: CreateTaskRequest): Promise<Task> {
        console.log(req.params)
...
}
</code>```

Result

[Nest] 36410  - 02/09/2022, 3:33:33 PM     LOG [NestMicroservice] Nest microservice successfully started +55ms
[Nest] 36410  - 02/09/2022, 3:33:33 PM     LOG Workflow gRPC service listening on localhost:8000
[Nest] 36410  - 02/09/2022, 3:33:36 PM     LOG Received rpc call to /area.task.TaskService/CreateTask with data: '{"workflowId":"1f5a0501-ce63-437d-b70f-a0ea3c22f0ff","name":"fugiat qui laboris dolore","type":0,"action":0,"nextTask":"Ut mollit","params":{"fields":{"foo":{"stringValue":"bar"},"bar":{"numberValue":4},"baz":{"boolValue":false}}}}'
{
  fields: {
    foo: { stringValue: 'bar' },
    bar: { numberValue: 4 },
    baz: { boolValue: false }
  }
}
```

The only thing you have to do now is creating a simple function to correctly wrap struct send by your client.
You can find more information with a real example on that repository.

Don't hesitate if you need anything else or if you found a better way to do it :D

Body:
hey i am trying to implement nest js microservice with grpc.
it looks impossible to use nestjs microservice with struct type for plain objects.

how can i use compiled protos with nestjs ?

imports: [
  ClientsModule.register([
    {
      name: 'HERO_PACKAGE',
      transport: Transport.GRPC,
      options: {
        package: 'hero',
        protoPath: join(__dirname, 'hero/hero.proto'),
      },
    },
  ]),
];

how can i load the compiled protos. something like https://medium.com/@waynelpu/how-to-pass-plain-javascript-object-with-gprc-94a91906ab1c

Body:
I'm maybe late but I found an answer.

Imagine you have the following protobuf

// task.proto
syntax = "proto3";

// Area API
package task;

// Imports
import "google/protobuf/struct.proto";
import "google/protobuf/empty.proto";

message Task {
    string name = 1;

    // Any additional metadata required to execute the task
    google.protobuf.Struct params = 2;
}

service TaskService {
   rpc CreateTask(CreateTaskRequest) returns (Task)
}

message CreateTaskRequest {
  string name = 1;

  google.protobuf.Struct params = 2;
}

You will need to add an option in your module to correctly load object

    await app.connectMicroservice<MicroserviceOptions>({
        transport: Transport.GRPC,
        options: {
            package: [ 'task' ],
            protoPath: [ __dirname + '/protos/task.proto' ],
            url: `${host}:${port}`,
            loader: {
                objects: true // This property
            }
        },
    });

And then in the resolver, you will retrieve a structure that his gRPC Struct compliant, you can find more information here.

Now imagine that you execute a rpc call to CreateTask (Postman has a great beta client for example)

{
  "name": "fugiat qui laboris dolore",
  "params": {
    "fields": {
      "foo": {
        "stringValue": "bar"
      },
      "bar": {
        "numberValue": 4
      },
      "baz": {
        "boolValue": false
      }
    }
  }
}

You will correctly retrieve it in your handler

    async createTask(@Payload(new ValidationPipe({ whitelist: true })) req: CreateTaskRequest): Promise<Task> {
        console.log(req.params)
...
}

Result

[Nest] 36410  - 02/09/2022, 3:33:33 PM     LOG [NestMicroservice] Nest microservice successfully started +55ms
[Nest] 36410  - 02/09/2022, 3:33:33 PM     LOG Workflow gRPC service listening on localhost:8000
[Nest] 36410  - 02/09/2022, 3:33:36 PM     LOG Received rpc call to /area.task.TaskService/CreateTask with data: '{"workflowId":"1f5a0501-ce63-437d-b70f-a0ea3c22f0ff","name":"fugiat qui laboris dolore","type":0,"action":0,"nextTask":"Ut mollit","params":{"fields":{"foo":{"stringValue":"bar"},"bar":{"numberValue":4},"baz":{"boolValue":false}}}}'
{
  fields: {
    foo: { stringValue: 'bar' },
    bar: { numberValue: 4 },
    baz: { boolValue: false }
  }
}

The only thing you have to do now is creating a simple function to correctly wrap struct send by your client.
You can find more information with a real example on that repository.

Don't hesitate if you need anything else or if you found a better way to do it :D


问:
Slide in child element on parent hover
I'm having an issue with a button animation I'm trying to make. I want a description box to slide out from behind a button when the button is hovered over, but in the way that I'm doing it, it has no transition and just snaps to its position. My setup is below:

.button {
    position: absolute;
    display: flex;
    padding:7px;
    margin: 20px;
    background-color: red;
}
.button > .popout {
    display: none;
    position: absolute;
    padding: 2px;
    background-color: blue;
    color: white;
    transition: 1s;
}
.button:hover > .popout {
    display: block;
    transform: translateX(20px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="button">
  <div class="icon">
    O
  </div>
  <div class="popout">
    email
  </div>
</div></code>```

when what I really want is the "email" text to glide out from beneath the O background without showing any blue or text on the left of the O. Sorry if I didn't do this right or provide enough info, I'm very new to stack overflow and just getting back into HTML and CSS after leaving it alone for a while

答:
Animations don't work with display: none/block, you have to use visibility: hidden/visible:

.button {
    position: absolute;
    display: flex;
    padding:7px;
    margin: 20px;
    background-color: red;
}
.button > .popout {
    visibility: hidden;
    position: absolute;
    padding: 2px;
    background-color: blue;
    color: white;
    transition: 1s;
}
.button:hover > .popout {
    visibility: visible;
    transform: translateX(20px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="button">
  <div class="icon">
    O
  </div>
  <div class="popout">
    email
  </div>
</div></code>```

Title: Slide in child element on parent hover

Body:
I'm having an issue with a button animation I'm trying to make. I want a description box to slide out from behind a button when the button is hovered over, but in the way that I'm doing it, it has no transition and just snaps to its position. My setup is below:

.button {
    position: absolute;
    display: flex;
    padding:7px;
    margin: 20px;
    background-color: red;
}
.button > .popout {
    display: none;
    position: absolute;
    padding: 2px;
    background-color: blue;
    color: white;
    transition: 1s;
}
.button:hover > .popout {
    display: block;
    transform: translateX(20px);
}

    O

    email

when what I really want is the "email" text to glide out from beneath the O background without showing any blue or text on the left of the O. Sorry if I didn't do this right or provide enough info, I'm very new to stack overflow and just getting back into HTML and CSS after leaving it alone for a while

Body:
Animations don't work with display: none/block, you have to use visibility: hidden/visible:

.button {
    position: absolute;
    display: flex;
    padding:7px;
    margin: 20px;
    background-color: red;
}
.button > .popout {
    visibility: hidden;
    position: absolute;
    padding: 2px;
    background-color: blue;
    color: white;
    transition: 1s;
}
.button:hover > .popout {
    visibility: visible;
    transform: translateX(20px);
}

<div class="button">
  <div class="icon">
    O
  </div>
  <div class="popout">
    email
  </div>
</div>


问:
How do I use the user home directory in a Github actions workflow that runs on Windows?
I'm using the Github actions workflow that runs on windows-latest and I'd like to use the user home directory variable instead of using an hardcoded path C:\Users\runneradmin. On windows this is normally available in a cmd as %USERPROFILE%.
But using %USERPROFILE% fails in the Github actions as the syntax seems unsupported.
Also tried : ${{ env.USERPROFILE }} which was empty.
and $env:USERPROFILE which resulted in syntax error.

答:
The answer is $HOME :

```<code>steps:
- name: Echo home
  run:
    echo $HOME
</code>```

Log:

```<code>Run echo $HOME
C:\Users\runneradmin
</code>```

Body:
The answer is $HOME :

steps:
- name: Echo home
  run:
    echo $HOME

Log:

Run echo $HOME
C:\Users\runneradmin


问:
Visual Studio Code shortcut to display autocomplete list before typing on macOS
I am trying to display all possible words after putting the cursor in certain place in the code.

The autocomplete list appears when I start writing/typing:

However, I would like to see all suggested words even before typing.

I tried command + space, however it was a system shortcut for Search in macOS:

Any thoughts?

答:
You can use the following alternative keyboard shortcuts:

⌘+I (mentioned in the official VS Code documentation for "Trigger suggestion")

⌥+esc

fn+control+space


问:
IHostBuilder configuration cannot load xml files
I have a co-worker who have a problem with posting here, he will be the one answering comments and validating answer. Here is his question:

I'm using Net5 with Microsoft.Extensions.Hosting. Instead of appsettings.json, I need to use xml files. I have App.config to specify common app settings (log4net config, etc.) and AcquisitionManagerConfiguration.xml for the settings on each installation (hardware stuff).

I went like this :
Program.cs

```<code>public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            IHostBuilder ihb = Host.CreateDefaultBuilder(args);
            ihb.ConfigureAppConfiguration((hostingContext, configuration) =>
            {

                //configuration.Sources.Clear();
                configuration.SetBasePath(AppContext.BaseDirectory);
                configuration.AddXmlFile("AcquisitionManagerConfiguration.xml", optional: false, reloadOnChange: true)
                   .AddXmlFile("App.config", optional: false, reloadOnChange: true);

                configuration.AddEnvironmentVariables();

            }).ConfigureServices((hostingContext, services) =>
            {

                services.AddHttpClient();
                services.Configure<AcquisitionManagerConfiguration>(hostingContext.Configuration.GetSection("AcquisitionManagerConfiguration"));
                services.AddTransient<AcquisitionManager.AcquisitionManager>();
                services.AddTransient<IServiceClient, ServiceClient>();
                services.AddHostedService<Worker>();
            });
            return ihb;
        }
    }
</code>```

AcquisitionManager.cs

```<code>public AcquisitionManager(IServiceClient serviceClient, IOptions<AcquisitionManagerConfiguration> config)
{
client = serviceClient;
configuration = config.Value;
}
</code>```

and the first xml

```<code>    <?xml version="1.0" encoding="utf-8" ?>
    <AcquisitionManagerConfiguration>
        <val>1</val>
    </AcquisitionManagerConfiguration>
</code>```

AcquisitionManagerConfiguration.cs matches exactly the xml, it worked fine if I manually deserialize.

But using the hosting system, I never have anything in config.Value.

Any idea what I'm doing wrong ?
I didn't find the solution so I posted here.
Thanks for the help.

答:
It looks like you are just missing the Bind part in your services registration.

services.Configure<AcquisitionManagerConfiguration>(options => Configuration.GetSection("AcquisitionManagerConfiguration"));

should be

services.Configure<AcquisitionManagerConfiguration>(options => Configuration.GetSection("AcquisitionManagerConfiguration").Bind(options));

Body:
I have a co-worker who have a problem with posting here, he will be the one answering comments and validating answer. Here is his question:

I'm using Net5 with Microsoft.Extensions.Hosting. Instead of appsettings.json, I need to use xml files. I have App.config to specify common app settings (log4net config, etc.) and AcquisitionManagerConfiguration.xml for the settings on each installation (hardware stuff).

I went like this :
Program.cs

public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            IHostBuilder ihb = Host.CreateDefaultBuilder(args);
            ihb.ConfigureAppConfiguration((hostingContext, configuration) =>
            {

                //configuration.Sources.Clear();
                configuration.SetBasePath(AppContext.BaseDirectory);
                configuration.AddXmlFile("AcquisitionManagerConfiguration.xml", optional: false, reloadOnChange: true)
                   .AddXmlFile("App.config", optional: false, reloadOnChange: true);

                configuration.AddEnvironmentVariables();

            }).ConfigureServices((hostingContext, services) =>
            {

                services.AddHttpClient();
                services.Configure<AcquisitionManagerConfiguration>(hostingContext.Configuration.GetSection("AcquisitionManagerConfiguration"));
                services.AddTransient<AcquisitionManager.AcquisitionManager>();
                services.AddTransient<IServiceClient, ServiceClient>();
                services.AddHostedService<Worker>();
            });
            return ihb;
        }
    }

AcquisitionManager.cs

public AcquisitionManager(IServiceClient serviceClient, IOptions<AcquisitionManagerConfiguration> config)
{
client = serviceClient;
configuration = config.Value;
}

and the first xml

    <?xml version="1.0" encoding="utf-8" ?>
    <AcquisitionManagerConfiguration>
        <val>1</val>
    </AcquisitionManagerConfiguration>

AcquisitionManagerConfiguration.cs matches exactly the xml, it worked fine if I manually deserialize.

But using the hosting system, I never have anything in config.Value.

Any idea what I'm doing wrong ?
I didn't find the solution so I posted here.
Thanks for the help.


问:
SQL query - converting seconds to HH:MM:SS
I have the following query that returns a total seconds value (up to 86400 seconds (1 day))

I want to convert this to an HH:MM:SS value. Any help is appreciated.

```<code>(SELECT FIRST TSS.TotalDrivingTime
 FROM HLG01_TR_TachographShiftSummary TSS
 WHERE TSS.DriverID = TRD.DriverID
   AND (CONVERT(date, TSS.PeriodStart)) = S.LoadDate)
</code>```

答:
in sqlserver you can use:

```<code>declare @Seconds as int = 86400; SELECT CONVERT(time(0), DATEADD(SECOND, @Seconds, 0)) as 'hh:mm:ss'
</code>```

and in mysql

```<code>SELECT SEC_TO_TIME(test_duration) as `Time` FORM YOUR_TABLE;
</code>```

or

```<code>FROM_UNIXTIME(unix_timestamp, '%h:%i:%s')
</code>```

How to convert time in seconds to HH:MM:SS format in MySQL?

https://www.sqlservercentral.com/forums/reply/1459738

Body:
I have the following query that returns a total seconds value (up to 86400 seconds (1 day))

I want to convert this to an HH:MM:SS value. Any help is appreciated.

(SELECT FIRST TSS.TotalDrivingTime
 FROM HLG01_TR_TachographShiftSummary TSS
 WHERE TSS.DriverID = TRD.DriverID
   AND (CONVERT(date, TSS.PeriodStart)) = S.LoadDate)

Body:
in sqlserver you can use:

declare @Seconds as int = 86400; SELECT CONVERT(time(0), DATEADD(SECOND, @Seconds, 0)) as 'hh:mm:ss'

and in mysql

SELECT SEC_TO_TIME(test_duration) as `Time` FORM YOUR_TABLE;

or

FROM_UNIXTIME(unix_timestamp, '%h:%i:%s')

How to convert time in seconds to HH:MM:SS format in MySQL?

https://www.sqlservercentral.com/forums/reply/1459738


问:
Uncaught SyntaxErrror: Unexpected token ILLEGAL in chrome
I'm having a problem within the jQuery ajax function. The following code works fine in Mozilla but doesn't work in IE or Chrome, when I try to identify the problem using Developer Tools in chrome I get the error:

```<code>Uncaught SyntaxError: Unexpected token ILLEGAL \n
$.ajax.success
</code>```

and when I click on it it directs me to the var obj = JSON.parse(data); line.

```<code>function getdata(){
    $.ajax({
        type:"GET",
        url: "https://gdata.youtube.com/feeds/api/users/TheSyndicateProject/playlists?v=2&alt=jsonc",
        data: "",
        success: function(data) {
            var obj = JSON.parse(data);
            displayPlaylists(obj);
        }

    });
}
</code>```

EDIT:
Ive found a solution that works in chrome but still not in IE

```<code>function getdata(){
        $.ajax({
                type:"GET",
                url: "https://gdata.youtube.com/feeds/api/users/TheSyndicateProject/playlists?v=2&alt=jsonc",
                dataType:"json",
                success: function(data) {
                    displayPlaylists(data);
                }

            });
    }
</code>```

the addition of dataType:"json" means that the function expects json data to be returned and therefore parses it on arrival (it is equivalent to using jQuery.parseJSON), however as i said this solution still doesn't work in IE

答:
My javascript linter indicates that there's a unicode character in the JSON data which it chokes on. This shouldn't be the case as it's valid JSON but this bit:

```<code>"The Syndicate Challenge #4 World At War\r\nhttp://www.youtube.com/watch?v\u003d49g7f5lkvQ8"
</code>```

Seems to be the trouble causer. I'm not a 100% sure tho, as firefox seems to be able to parse the data anyway. The unicode character also seems out of place, but that could be me.

ContentLicense: CC BY-SA 3.0

Body:
I'm having a problem within the jQuery ajax function. The following code works fine in Mozilla but doesn't work in IE or Chrome, when I try to identify the problem using Developer Tools in chrome I get the error:

Uncaught SyntaxError: Unexpected token ILLEGAL \n
$.ajax.success

and when I click on it it directs me to the var obj = JSON.parse(data); line.

function getdata(){
    $.ajax({
        type:"GET",
        url: "https://gdata.youtube.com/feeds/api/users/TheSyndicateProject/playlists?v=2&alt=jsonc",
        data: "",
        success: function(data) {
            var obj = JSON.parse(data);
            displayPlaylists(obj);
        }

    });
}

EDIT:
Ive found a solution that works in chrome but still not in IE

function getdata(){
        $.ajax({
                type:"GET",
                url: "https://gdata.youtube.com/feeds/api/users/TheSyndicateProject/playlists?v=2&alt=jsonc",
                dataType:"json",
                success: function(data) {
                    displayPlaylists(data);
                }

            });
    }

the addition of dataType:"json" means that the function expects json data to be returned and therefore parses it on arrival (it is equivalent to using jQuery.parseJSON), however as i said this solution still doesn't work in IE

Body:
My javascript linter indicates that there's a unicode character in the JSON data which it chokes on. This shouldn't be the case as it's valid JSON but this bit:

"The Syndicate Challenge #4 World At War\r\nhttp://www.youtube.com/watch?v\u003d49g7f5lkvQ8"

Seems to be the trouble causer. I'm not a 100% sure tho, as firefox seems to be able to parse the data anyway. The unicode character also seems out of place, but that could be me.


问:
Recursive Function Uncaught RangeError: Maximum call stack size exceeded
This function which will execute when you enter on input field then it will calculate how much money do you have to return with x type to customer.

But getting stack size error sometime for 6 digit and everytime for 7 digit.

Reproduce: put 1234567 in input box and check the console.

Function:

```<code>let returnList = [];
let predictorList = [
    100, 50, 20, 10, 5, 1, 0.5, 0.25, 0.1, 0.05, 0.01,
  ];
let total = 11.23

function isRemainingMoney(value) {
    let remainingValue = value;

    // when remaning value becomes zero then return the returnlist
    if (remainingValue == 0) {
      return returnList;
    }

    for (let pRed of predictorList) {
      /* remainingValue is greater than predictor value then push it
      eg:  41.33 > 20
           21.33 > 20
           1.33 > 1
           0.33 > 0.25
           0.08 > 0.05
           0.03 > 0.01 * 3 times
      */
      if (remainingValue >= pRed) {
        const isPredExist = returnList.find(
          (pItem) => +pItem.money == +pRed
        );
        if (!!isPredExist) {
          isPredExist.count += 1;
          isPredExist.total = isPredExist.total + +pRed;
        } else {
          returnList.push({
            type: pRed,
            money: pRed,
            count: 1,
            total: pRed,
          });
        }
        remainingValue = +remainingValue.toFixed(2) - pRed;
        break;
      }
    }
    // recursive call the same method untill remainivalue becomes zero.
    return isRemainingMoney(+remainingValue.toFixed(2));
  }

document.querySelector('input').addEventListener('change', (event) => {
   if(!!event.target.value) {
        returnList.length = 0;
        returnList = isRemainingMoney(+event.target.value - total);
        console.log(returnList, 'returnList');
   }

})
</code>```

Playground: https://jsbin.com/kuwomalare/edit?html,js,console,output

Current Output From real application:

答:
You end up having way too many recursive calls when the input value is large. It should be fairly straight forward to convert from recursive to iterative using a while loop. The only issue I ran into was floating point not getting down to 0 (like mentioned in the comment by @Keith). When doing money calculations, it is usually best to use integers. Use the smallest denomination in the currency. For example, in US currency, that would be cents. Only convert to decimal (or dollars in this case) when displaying the values.

I have also simplified your calculations a bit. Because of these changes, you could actually use recursion now, if you want since the maximum level of recursion now is predictorList.length.

let predictorList = [
  10000, 5000, 2000, 1000, 500, 100, 50, 25, 10, 5, 1
];
let total = 709;

function isRemainingMoney(value) {
  let returnList = [];

  // when remaning value becomes zero then return the returnlist
  while (value != 0) {
    for (let pRed of predictorList) {
      if (value >= pRed) {
        returnList.push({
            money: pRed / 100,
            count: Math.floor(value / pRed),
          });
        value %= pRed;
      }
    }
  }
  return returnList;
}
document.querySelector('input').addEventListener('change', (event) => {
  if (!!event.target.value) {
    let returnList = isRemainingMoney(+event.target.value * 100 - total);
    console.log(returnList, 'returnList');
  }

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number"></code>```

Body:
This function which will execute when you enter on input field then it will calculate how much money do you have to return with x type to customer.

But getting stack size error sometime for 6 digit and everytime for 7 digit.

Reproduce: put 1234567 in input box and check the console.

Function:

let returnList = [];
let predictorList = [
    100, 50, 20, 10, 5, 1, 0.5, 0.25, 0.1, 0.05, 0.01,
  ];
let total = 11.23

function isRemainingMoney(value) {
    let remainingValue = value;

    // when remaning value becomes zero then return the returnlist
    if (remainingValue == 0) {
      return returnList;
    }

    for (let pRed of predictorList) {
      /* remainingValue is greater than predictor value then push it
      eg:  41.33 > 20
           21.33 > 20
           1.33 > 1
           0.33 > 0.25
           0.08 > 0.05
           0.03 > 0.01 * 3 times
      */
      if (remainingValue >= pRed) {
        const isPredExist = returnList.find(
          (pItem) => +pItem.money == +pRed
        );
        if (!!isPredExist) {
          isPredExist.count += 1;
          isPredExist.total = isPredExist.total + +pRed;
        } else {
          returnList.push({
            type: pRed,
            money: pRed,
            count: 1,
            total: pRed,
          });
        }
        remainingValue = +remainingValue.toFixed(2) - pRed;
        break;
      }
    }
    // recursive call the same method untill remainivalue becomes zero.
    return isRemainingMoney(+remainingValue.toFixed(2));
  }

document.querySelector('input').addEventListener('change', (event) => {
   if(!!event.target.value) {
        returnList.length = 0;
        returnList = isRemainingMoney(+event.target.value - total);
        console.log(returnList, 'returnList');
   }

})

Playground: https://jsbin.com/kuwomalare/edit?html,js,console,output

Current Output From real application:

Body:
You end up having way too many recursive calls when the input value is large. It should be fairly straight forward to convert from recursive to iterative using a while loop. The only issue I ran into was floating point not getting down to 0 (like mentioned in the comment by @Keith). When doing money calculations, it is usually best to use integers. Use the smallest denomination in the currency. For example, in US currency, that would be cents. Only convert to decimal (or dollars in this case) when displaying the values.

I have also simplified your calculations a bit. Because of these changes, you could actually use recursion now, if you want since the maximum level of recursion now is predictorList.length.

let predictorList = [
  10000, 5000, 2000, 1000, 500, 100, 50, 25, 10, 5, 1
];
let total = 709;

function isRemainingMoney(value) {
  let returnList = [];

  // when remaning value becomes zero then return the returnlist
  while (value != 0) {
    for (let pRed of predictorList) {
      if (value >= pRed) {
        returnList.push({
            money: pRed / 100,
            count: Math.floor(value / pRed),
          });
        value %= pRed;
      }
    }
  }
  return returnList;
}
document.querySelector('input').addEventListener('change', (event) => {
  if (!!event.target.value) {
    let returnList = isRemainingMoney(+event.target.value * 100 - total);
    console.log(returnList, 'returnList');
  }

})

<input type="number">


问:
How can i merge two mysql databases of same characteristics with out losing any data
Here is the issue. I have an app that was installed on two different servers with DB 1 and DB2. Each has the same schema and auto incremental key. but DB2 has more data input than DB1 while DB1 has some important data that is not in DB2.

How can I merge the two databases without losing my data in any of them?

I have searched and come across a guide that suggested this

```<code>INSERT INTO DB1.TABLE1 SELECT * FROM DB2.TABLE1
</code>```

But my problem is that the databases have up to 106 tables.

is there a way to merge all the tables at once?

答:
No, there is no easy button tool or procedure to merge rows from tables from  two schemas.

We can envision the special case of a table that is guaranteed not to have any conflicting rows, where rows can be simply copied from one table to the other.

But in the more general case (a typical entity-relationship model implemented as tables in a relational database), we can't avoid data conflict issues due to UNIQUE KEY constraints, FOREIGN KEY constraints, et al.

For examle,

If table (id,name) in DB1 has row (3,'amigos') and in DB2 has row (3,'blind mice')

When we attempt to INSERT the row from DB2 into the table in DB1, and we get a unique key constraint violation on id=3, how do we handle that? Do we just not copy the row from DB2? Do we modify the id value on the row from DB2 to be (1113,'blind mice') when its copied into DB1?

How we handle these types of issues will depend. Is this a lookup table that is relatively static (a "domain" or "list of values" table), if the contents of the tables are the same in both databases, we would expect the contents of the merged table to be the same.

But we will handle that differently for a table of transactions where we expect the merged table to contain all the rows from DB1 and all the rows from DB2.

Q: "Is there a way to merge all the tables at once?"

A: No. If there was a tool do that kind of merge (if it did happen to do the right thing in a special case), with no doubt it will do the wrong thing on some of the 100+ tables.

Body:
Here is the issue. I have an app that was installed on two different servers with DB 1 and DB2. Each has the same schema and auto incremental key. but DB2 has more data input than DB1 while DB1 has some important data that is not in DB2.

How can I merge the two databases without losing my data in any of them?

I have searched and come across a guide that suggested this

INSERT INTO DB1.TABLE1 SELECT * FROM DB2.TABLE1

But my problem is that the databases have up to 106 tables.

is there a way to merge all the tables at once?


问:
how to use a django variable in an  tag's href?
I want to create a list of entries in which each entry is linked to its page like this: wiki/entry-title. I'm using a for loop to add
s to HTML. here's the code:

```<code><ul>
  {% for entry in entries %}
    <li><a href="">{{ entry }}</a></li>
  {% endfor %}
</ul>
</code>```

urlpattern:

```<code>path('wiki/<str:title>', views.entry, name='entry')
</code>```

what should I type in href to link the
 to wiki/entry?

答:
In django, the template parser always handles django code first, then html/javascript. So you would insert a django variable into an anchor tag the same way you'd insert it anywhere in the template and the parser will replace it before it tries to render the html. If it's a django url, you can use the {% %} format as referenced in the previous answer, and if it's a url that's perhaps stored on the object, you can just use {{ }} (like {{ entry.wiki_url }}). You can also use text for some of the url and a variable for part. So if you have a wiki site that has a base url of, for instance, https://mywiki.com you'd write the href like:

```<code><ul>
  {% for entry in entries %}
    <a href="https://mywiki.com/{{entry.title}}"><li>{{ entry.title }}</li></a>
  {% endfor %}
</ul>
</code>```

Title: how to use a django variable in an <a> tag's href?

Body:
I want to create a list of entries in which each entry is linked to its page like this: wiki/entry-title. I'm using a for loop to add
s to HTML. here's the code:

  {% for entry in entries %}

{{ entry }}

  {% endfor %}

urlpattern:

path('wiki/<str:title>', views.entry, name='entry')

what should I type in href to link the
 to wiki/entry?

Body:
In django, the template parser always handles django code first, then html/javascript. So you would insert a django variable into an anchor tag the same way you'd insert it anywhere in the template and the parser will replace it before it tries to render the html. If it's a django url, you can use the {% %} format as referenced in the previous answer, and if it's a url that's perhaps stored on the object, you can just use {{ }} (like {{ entry.wiki_url }}). You can also use text for some of the url and a variable for part. So if you have a wiki site that has a base url of, for instance, https://mywiki.com you'd write the href like:

<ul>
  {% for entry in entries %}
    <a href="https://mywiki.com/{{entry.title}}"><li>{{ entry.title }}</li></a>
  {% endfor %}
</ul>


问:
remove body content of index.html using gulp
I can able to rename file name from index. using following configuration

Gulp.js

```<code>var rename = require("gulp-rename");

gulp.task('modify-html', function () {
  gulp.src('reports/index.html')
    .pipe(rename('/app.html'))
    .pipe(gulp.dest('reports/'));
});
</code>```

Does anyone know how to delete the body content of my html file using gulp

index.html

```<code><html>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>

</body>
</html>
</code>```

答:
Use gulp-string-replace

```<code>var replace = require('gulp-string-replace');

gulp.task('clearBody', function (done) {

    gulp.src('file.html')
    .pipe(replace(new RegExp('<body>(.*?)<\/body>', 'm'), '<body><\/body>'))
    .pipe(gulp.dest('newFile.html'));

    done();
});
</code>```

Body:
I can able to rename file name from index. using following configuration

Gulp.js

var rename = require("gulp-rename");

gulp.task('modify-html', function () {
  gulp.src('reports/index.html')
    .pipe(rename('/app.html'))
    .pipe(gulp.dest('reports/'));
});

Does anyone know how to delete the body content of my html file using gulp

index.html

My First Heading

My first paragraph.

Body:
Use gulp-string-replace

var replace = require('gulp-string-replace');

gulp.task('clearBody', function (done) {

    gulp.src('file.html')
    .pipe(replace(new RegExp('<body>(.*?)<\/body>', 'm'), '<body><\/body>'))
    .pipe(gulp.dest('newFile.html'));

    done();
});


问:
Need a simple explanation of the inject method
```<code>[1, 2, 3, 4].inject(0) { |result, element| result + element } # => 10
</code>```

I'm looking at this code but my brain is not registering how the number 10 can become the result. Would someone mind explaining what's happening here?

答:
The code iterates over the four elements within the array and adds the previous result to the current element:

1 + 2 = 3

3 + 3 = 6

6 + 4 = 10

OwnerDisplayName: hightide

ContentLicense: CC BY-SA 2.5

Body:
[1, 2, 3, 4].inject(0) { |result, element| result + element } # => 10

I'm looking at this code but my brain is not registering how the number 10 can become the result. Would someone mind explaining what's happening here?

OwnerDisplayName: John Topley


问:
how to restrict to only single file upload in upload documents control in kendo ui
how to restrict to only single file upload in upload documents control in kendo UI.
is there any property to check the number of files uploaded.</p>

答:
You would handle the selected event of the uploader: https://docs.telerik.com/kendo-ui/api/javascript/ui/upload/events/select

In the event, you would get the length of the existing files collection using the getFiles method of the uploader: https://docs.telerik.com/kendo-ui/api/javascript/ui/upload/methods/getfiles

If the length of the existing files collection plus the length of the incoming file collection exceeds 1, then display an error:

$("#my-uploader").kendoUpload({
  select: function(e) {
    var existingFileLength = e.sender.getFiles().length;
    var incomingFileLength = e.files.length;
    if (existingFileLength + incomingFileLength > 1) {
      kendo.alert('You can only upload one file.');
      e.preventDefault();
    }
  }
});
```

Dojo: https://dojo.telerik.com/aDOfICID

Update

Or as DontVoteMeDown suggested, the simpler method would be to set the multiple property to false: https://docs.telerik.com/kendo-ui/api/javascript/ui/upload/configuration/multiple

Body:
You would handle the selected event of the uploader: https://docs.telerik.com/kendo-ui/api/javascript/ui/upload/events/select

In the event, you would get the length of the existing files collection using the getFiles method of the uploader: https://docs.telerik.com/kendo-ui/api/javascript/ui/upload/methods/getfiles

If the length of the existing files collection plus the length of the incoming file collection exceeds 1, then display an error:

$("#my-uploader").kendoUpload({
  select: function(e) {
    var existingFileLength = e.sender.getFiles().length;
    var incomingFileLength = e.files.length;
    if (existingFileLength + incomingFileLength > 1) {
      kendo.alert('You can only upload one file.');
      e.preventDefault();
    }
  }
});

Dojo: https://dojo.telerik.com/aDOfICID

Update

Or as DontVoteMeDown suggested, the simpler method would be to set the multiple property to false: https://docs.telerik.com/kendo-ui/api/javascript/ui/upload/configuration/multiple


问:
BigQury Storage Read API, the user does not have 'bigquery.readsessions.create'
I'm trying to use BigQuery Storage Read API. As far as I can tell, the local script is using the an account, that has Owner role, BigQuery user, and BigQuery read session on the entire project. However, running the code from the local machine yields this error:

google.api_core.exceptions.PermissionDenied: 403 request failed: the user does not have 'bigquery.readsessions.create' permission for 'projects/xyz'

According to the GCP documentation the API is enabled by default. So the only reason I can think of is my script is using the wrong account.

How would you go debugging this issue? Is there a way to know for sure which user/account is running a python code on run time, something like print(user.user_name)

答:
There is a gcloud command to get the current user permissions

$ gcloud projects get-iam-policy [PROJECT_ID]
```
<p>You can also check the <code>user_email</code> field of your job to find out which user it is using to execute your query.</p>
<p><strong>Example</strong>:</p>
<pre class="lang-json prettyprint-override"><code>{
  # ...
  "user_email": "myemail@company.com",
  "configuration": {
  # ...
  "jobType": QUERY
    },
  },
  "jobReference": {
    "projectId": "my-project",
  # ...
}
</code>```

Body:
There is a gcloud command to get the current user permissions

$ gcloud projects get-iam-policy [PROJECT_ID]

You can also check the user_email field of your job to find out which user it is using to execute your query.

Example:

{
  # ...
  "user_email": "myemail@company.com",
  "configuration": {
  # ...
  "jobType": QUERY
    },
  },
  "jobReference": {
    "projectId": "my-project",
  # ...
}


问:
How to add horizontal scroll in paginated Data Table in flutter web
I have used Paginated Data Table in flutter web. On smaller screen, the table adjust it's width but hides the data column, I want to scroll the Data table horizontally, so that I am able to go through the whole data columns, added in the Paginated Data Table. (don't want to use any package)

Thanks in advance

Here is my code

```<code>SingleChildScrollView(
      child: Container(
        padding: EdgeInsets.all(10),
        color: AppColors.grey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
               CustomIconButton(
                buttonText: "Add School",
                onTap: () {}
              ),

            SizedBox(height: 15),

            PaginatedDataTable(
              source: _schoolData,
              dragStartBehavior: DragStartBehavior.start,

              header: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.all(20),
                    child: CustomText(
                      text: "School Overview",
                      fontSize: 20,
                    ),
                  ),
                  Divider(height: 0),
                ],
              ),
              columns:  [
                _createDataColumn("ID"),
                _createDataColumn("Name"),
                _createDataColumn("User Name"),
                _createDataColumn("Email"),
                _createDataColumn("City"),
                _createDataColumn("Country"),
                _createDataColumn("Grading"),
                _createDataColumn("Archive"),
                _createDataColumn("Education Level"),
                _createDataColumn(""),
              ],
              columnSpacing: 100,
              horizontalMargin: 10,
              rowsPerPage: 8,
              showCheckboxColumn: false,
              dataRowHeight: 70,
              arrowHeadColor: AppColors.darkBlue,

            ),
          ],
        ),
      ),
    );
</code>```

答:
put SingleChildScrollView inside SingleChildScrollView with different scrollDirection for example:</p>
```<code>SingleChildScrollView(
            scrollDirection : Axis.vertical
            child: Column(
              children: [
                SingleChildScrollView(
                  scrollDirection : Axis.horizontal,
                  child: Text(''),
                ),
                SingleChildScrollView(
                  scrollDirection : Axis.horizontal,
                  child: Text(''),
                ),
                SingleChildScrollView(
                  scrollDirection : Axis.horizontal,
                  child: Text(''),
                ),
              ],
            ),

          ),
</code>```

Body:
I have used Paginated Data Table in flutter web. On smaller screen, the table adjust it's width but hides the data column, I want to scroll the Data table horizontally, so that I am able to go through the whole data columns, added in the Paginated Data Table. (don't want to use any package)

Thanks in advance

Here is my code

SingleChildScrollView(
      child: Container(
        padding: EdgeInsets.all(10),
        color: AppColors.grey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
               CustomIconButton(
                buttonText: "Add School",
                onTap: () {}
              ),

            SizedBox(height: 15),

            PaginatedDataTable(
              source: _schoolData,
              dragStartBehavior: DragStartBehavior.start,

              header: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.all(20),
                    child: CustomText(
                      text: "School Overview",
                      fontSize: 20,
                    ),
                  ),
                  Divider(height: 0),
                ],
              ),
              columns:  [
                _createDataColumn("ID"),
                _createDataColumn("Name"),
                _createDataColumn("User Name"),
                _createDataColumn("Email"),
                _createDataColumn("City"),
                _createDataColumn("Country"),
                _createDataColumn("Grading"),
                _createDataColumn("Archive"),
                _createDataColumn("Education Level"),
                _createDataColumn(""),
              ],
              columnSpacing: 100,
              horizontalMargin: 10,
              rowsPerPage: 8,
              showCheckboxColumn: false,
              dataRowHeight: 70,
              arrowHeadColor: AppColors.darkBlue,

            ),
          ],
        ),
      ),
    );

Body:
put SingleChildScrollView inside SingleChildScrollView with different scrollDirection for example:

SingleChildScrollView(
            scrollDirection : Axis.vertical
            child: Column(
              children: [
                SingleChildScrollView(
                  scrollDirection : Axis.horizontal,
                  child: Text(''),
                ),
                SingleChildScrollView(
                  scrollDirection : Axis.horizontal,
                  child: Text(''),
                ),
                SingleChildScrollView(
                  scrollDirection : Axis.horizontal,
                  child: Text(''),
                ),
              ],
            ),

          ),


答:
You can set your value in url as

```<code><ul>
    {% for entry in entries %}
        <a href="/wiki/{{entry.value}}"><li>{{ entry }}</li></a>
  {% endfor %}
</ul>
</code>```

Its better to use {% url %} [Django-doc] template tags as

```<code><ul>
    {% for entry in entries %}
        <a href="{% url 'your-url-name' entry.value %}"><li>{{ entry }}</li></a>
  {% endfor %}
</ul>
</code>```

NOTE : change value with your value accordingly. For e.g. {{entry.value}} or {{entry.title}} or {{entry.id}}

Body:
You can set your value in url as

<ul>
    {% for entry in entries %}
        <a href="/wiki/{{entry.value}}"><li>{{ entry }}</li></a>
  {% endfor %}
</ul>

Its better to use {% url %} [Django-doc] template tags as

<ul>
    {% for entry in entries %}
        <a href="{% url 'your-url-name' entry.value %}"><li>{{ entry }}</li></a>
  {% endfor %}
</ul>

NOTE : change value with your value accordingly. For e.g. {{entry.value}} or {{entry.title}} or {{entry.id}}


问:
Which is better to use: $arrayName['literal'] or $arrayName[literal]?
Both are working fine. I'm just curious how php parse the two. Do they have difference on speed, efficiency, etc. Why does php allow us to use both?</p>

答: Difference is that the first ('literal') is a string key and that the second one is undefined constant. PHP allows you to use both because devs tried to fix bad code of people who weren't paying attention while reading the docs. There's a difference in speed since the second one will raise a warning - undefined constant. Basically, don't use the second one.</p>


问:
Add packeto-buildpacks/google-stackdriver to spring boot gradle build
I would like to use the google cloud profiler in one of our projects. Because we use buildpacks to create our docker images, we can not use the standard way of adding the buildpack using a dockerfile.

So i would like to know: How can i add the buildpack to my gradle build?

I've created a standard spring boot app and added the buildpack to task

```<code>...
bootBuildImage {
    verboseLogging = true
    buildpacks = [
        "paketo-buildpacks/google-stackdriver"
    ]
}
</code>```

But if i run the build i get

```<code> > Task :bootBuildImage Building image 'docker.io/library/cnb-add-buildpack:0.0.1-SNAPSHOT'

 > Pulling builder image 'docker.io/paketobuildpacks/builder:base' ..................................................
 > Pulled builder image 'paketobuildpacks/builder@sha256:ac9f318cade49b78c229a8bf7858435514b5573177de2a29d2b30bafd5f0b7ec'
 > Pulling run image 'docker.io/paketobuildpacks/run:base-cnb' ..................................................
 > Pulled run image 'paketobuildpacks/run@sha256:41ea15b4d591c2722543009fbf8267a13019ecdc8c6a2b4f437ed83ed29bf72c'
 > Executing lifecycle version v0.13.3
 > Using build cache volume 'pack-cache-fa9655d690f5.build'

 > Running creator
    [creator]     ===> DETECTING
    [creator]     ======== Results ========
    [creator]     fail: paketo-buildpacks/google-stackdriver@5.3.1
    [creator]     ERROR: No buildpack groups passed detection.
    [creator]     ERROR: Please check that you are running against the correct path.
    [creator]     ERROR: failed to detect: no buildpacks participating

> Task :bootBuildImage FAILED

FAILURE: Build failed with an exception.

 * What went wrong: Execution failed for task ':bootBuildImage'.
 > Builder lifecycle 'creator' failed with status code 100

 * Try:
 > Run with --stacktrace option to get the stack trace.
 > Run with --info or --debug option to get more log output.
 > Run with --scan to get full insights.

 * Get more help at https://help.gradle.org

 BUILD FAILED in 44s
</code>```

Edit 1:

After adding a folder /platform/bindings/google-stackdriver including a file named type with content StackdriverProfiler i still get the same results.

Edit 2:

After removing that buildpacks from build.gradle and adding my project bindings instead -> it worked.

So you only need to create a file called type with content StackdriverProfiler in your project folder platform/bindings/google-stackdriver and reference that binding in your build.gradle

```<code>bootBuildImage {
    verboseLogging = true
    bindings = [ "${project.projectDir}/platform/bindings/google-stackdriver:/platform/bindings/google-stackdriver" ]
}
</code>```

答:
It looks like the preconditions for the paketo-buildpacks/google-stackdriver have not been met. You read about them here:
https://github.com/paketo-buildpacks/google-stackdriver#behavior

In general it requires::

A binding exists with type of StackdriverDebugger

A binding exists with type of StackdriverProfiler

Body:
I would like to use the google cloud profiler in one of our projects. Because we use buildpacks to create our docker images, we can not use the standard way of adding the buildpack using a dockerfile.

So i would like to know: How can i add the buildpack to my gradle build?

I've created a standard spring boot app and added the buildpack to task

...
bootBuildImage {
    verboseLogging = true
    buildpacks = [
        "paketo-buildpacks/google-stackdriver"
    ]
}

But if i run the build i get

 > Task :bootBuildImage Building image 'docker.io/library/cnb-add-buildpack:0.0.1-SNAPSHOT'

 > Pulling builder image 'docker.io/paketobuildpacks/builder:base' ..................................................
 > Pulled builder image 'paketobuildpacks/builder@sha256:ac9f318cade49b78c229a8bf7858435514b5573177de2a29d2b30bafd5f0b7ec'
 > Pulling run image 'docker.io/paketobuildpacks/run:base-cnb' ..................................................
 > Pulled run image 'paketobuildpacks/run@sha256:41ea15b4d591c2722543009fbf8267a13019ecdc8c6a2b4f437ed83ed29bf72c'
 > Executing lifecycle version v0.13.3
 > Using build cache volume 'pack-cache-fa9655d690f5.build'

 > Running creator
    [creator]     ===> DETECTING
    [creator]     ======== Results ========
    [creator]     fail: paketo-buildpacks/google-stackdriver@5.3.1
    [creator]     ERROR: No buildpack groups passed detection.
    [creator]     ERROR: Please check that you are running against the correct path.
    [creator]     ERROR: failed to detect: no buildpacks participating

> Task :bootBuildImage FAILED

FAILURE: Build failed with an exception.

 * What went wrong: Execution failed for task ':bootBuildImage'.
 > Builder lifecycle 'creator' failed with status code 100

 * Try:
 > Run with --stacktrace option to get the stack trace.
 > Run with --info or --debug option to get more log output.
 > Run with --scan to get full insights.

 * Get more help at https://help.gradle.org

 BUILD FAILED in 44s

Edit 1:

After adding a folder /platform/bindings/google-stackdriver including a file named type with content StackdriverProfiler i still get the same results.

Edit 2:

After removing that buildpacks from build.gradle and adding my project bindings instead -> it worked.

So you only need to create a file called type with content StackdriverProfiler in your project folder platform/bindings/google-stackdriver and reference that binding in your build.gradle

bootBuildImage {
    verboseLogging = true
    bindings = [ "${project.projectDir}/platform/bindings/google-stackdriver:/platform/bindings/google-stackdriver" ]
}


问:
HackerRank Staircase Python
I am trying to solve a problem in HackerRank and I am having an issue with my submission. My code works in PyCharm but HackerRank is not accepting my submission.

Here is the problem I am trying to solve: https://www.hackerrank.com/challenges/staircase

Here is my code:

```<code>def staircase(num_stairs):
    n = num_stairs - 1
    for stairs in range(num_stairs):
        print ' ' * n, '#' * stairs
        n -= 1
    print '#' * num_stairs
staircase(12)
</code>```

Any ideas why HackerRank is not accpeting my answer?

答:
one more solution:</p>
```<code>def staircase(n):
    for i in reversed(range(n)):
        print(i*' '+(n-i)*'#')
</code>```

Title: HackerRank Staircase Python

Body:
I am trying to solve a problem in HackerRank and I am having an issue with my submission. My code works in PyCharm but HackerRank is not accepting my submission.

Here is the problem I am trying to solve: https://www.hackerrank.com/challenges/staircase

Here is my code:

def staircase(num_stairs):
    n = num_stairs - 1
    for stairs in range(num_stairs):
        print ' ' * n, '#' * stairs
        n -= 1
    print '#' * num_stairs
staircase(12)

Any ideas why HackerRank is not accpeting my answer?

Body:
one more solution:

def staircase(n):
    for i in reversed(range(n)):
        print(i*' '+(n-i)*'#')


问:
About enable/disable by conditional values in ansible yaml manifest
I want a variable on Ansible to be active or passive depending on the condition.

I am using the role "davidwittman.redis". I'm setting up a redis cluster. I need to run a single yml file by deploying it to 3 servers at the same time. I can't distribute "yml" files separately.

I have a simple setup configuration below. Here, I want to activate the "redis_slaveof" value on all other servers, except the master server, depending on the condition.

In other words, I want the "redis_slaveof" value I selected to not be active on the master server, but to have this value active on the other 2 servers.

How can I do this, do you have any suggestions ?

my main ansible configuration;

```<code>> - name: Redis Replication Slave Installations   hosts: localhost
>
>   pre_tasks:
>   - name: check redis server1
>     shell: "cat /etc/hosts |grep redis |awk '{print $2}' |sed -n 1p"
>     register: server01
>
>   - name: check redis server2
>     shell: "cat /etc/hosts |grep redis |awk '{print $2}' |sed -n 2p"
>     register: server02
>
>   - name: check redis server3
>     shell: "cat /etc/hosts |grep redis |awk '{print $2}' |sed -n 3p"
>     register: server03
>
>   roles:
>     - role: davidwittman.redis
>
>       vars:
>         - redis_version: 6.2.6
>         - redis_bind: 0.0.0.0
>         - redis_port: 6379
>         - redis_service_name: redis-service
>         - redis_protected_mode: "no"
>         - redis_config_file_name: "redis.conf"
>
> #        - redis_slaveof: "{{ server01.stdout }} 6379"
</code>```

I tried the following;

I added extra task and "import_role". I put a when condition in it. If my server01 value and server local hostname value are not the equal, enable this role. Thus, I thought that it would activate this value on other servers except the master server.But it didn't work, added it on all servers. I saw the following error in the logs.
"[WARNING]: flush_handlers task does not support when conditional"

```<code> tasks:
  - name: test
    import_role:
      name: davidwittman.redis
    vars:
      redis_slaveof: "{{ server01.stdout }} 6379"
    when: '"{{ (server01.stdout) }}" != "{{ ansible_hostname }}"'
</code>```

I added the when condition to the main role as above and made it to two different roles in a single yml. This method also failed.

```<code>- role: davidwittman.redis
  when: '"{{ (server01.stdout) }}" != "{{ ansible_hostname }}"'
</code>```

I defined the "if/else" condition as follows in the variable. But although it seems to have worked, it still gave the error "does not support when conditional". Added it to all servers as well.

redis_slaveof: "{%if '{{ (server01.stdout) }} != {{ ansible_hostname }}' %} {{ '{{ (server01.stdout) }} 6379' }} {% else %} {{ '' }} {% endif %}"

答:
So you want to run a role differently, based on variables.

In your playbook do not use

```<code>roles:
  - role: davidwittman.redis
</code>```

but rather do

```<code>tasks:
  - name: Pass variables to role
    include_role:
      name: myrole
    vars:
      rolevar1: value from task
</code>```

This is executed after roles but now you can add when expressions:

```<code>tasks:
  - name: Pass variables to role
    include_role:
      name: myrole
    vars:
      rolevar1: value from task
    when: ansible_hostname = "server1"

  - name: Pass variables to role
    include_role:
      name: myrole
    vars:
      rolevar1: value from task
      additionalrolevar: whatever
    when: ansible_hostname != "server1"
</code>```

Body:
I want a variable on Ansible to be active or passive depending on the condition.

I am using the role "davidwittman.redis". I'm setting up a redis cluster. I need to run a single yml file by deploying it to 3 servers at the same time. I can't distribute "yml" files separately.

I have a simple setup configuration below. Here, I want to activate the "redis_slaveof" value on all other servers, except the master server, depending on the condition.

In other words, I want the "redis_slaveof" value I selected to not be active on the master server, but to have this value active on the other 2 servers.

How can I do this, do you have any suggestions ?

my main ansible configuration;

> - name: Redis Replication Slave Installations   hosts: localhost
>
>   pre_tasks:
>   - name: check redis server1
>     shell: "cat /etc/hosts |grep redis |awk '{print $2}' |sed -n 1p"
>     register: server01
>
>   - name: check redis server2
>     shell: "cat /etc/hosts |grep redis |awk '{print $2}' |sed -n 2p"
>     register: server02
>
>   - name: check redis server3
>     shell: "cat /etc/hosts |grep redis |awk '{print $2}' |sed -n 3p"
>     register: server03
>
>   roles:
>     - role: davidwittman.redis
>
>       vars:
>         - redis_version: 6.2.6
>         - redis_bind: 0.0.0.0
>         - redis_port: 6379
>         - redis_service_name: redis-service
>         - redis_protected_mode: "no"
>         - redis_config_file_name: "redis.conf"
>
> #        - redis_slaveof: "{{ server01.stdout }} 6379"

I tried the following;

I added extra task and "import_role". I put a when condition in it. If my server01 value and server local hostname value are not the equal, enable this role. Thus, I thought that it would activate this value on other servers except the master server.But it didn't work, added it on all servers. I saw the following error in the logs.
"[WARNING]: flush_handlers task does not support when conditional"

 tasks:
  - name: test
    import_role:
      name: davidwittman.redis
    vars:
      redis_slaveof: "{{ server01.stdout }} 6379"
    when: '"{{ (server01.stdout) }}" != "{{ ansible_hostname }}"'

I added the when condition to the main role as above and made it to two different roles in a single yml. This method also failed.

- role: davidwittman.redis
  when: '"{{ (server01.stdout) }}" != "{{ ansible_hostname }}"'

I defined the "if/else" condition as follows in the variable. But although it seems to have worked, it still gave the error "does not support when conditional". Added it to all servers as well.

redis_slaveof: "{%if '{{ (server01.stdout) }} != {{ ansible_hostname }}' %} {{ '{{ (server01.stdout) }} 6379' }} {% else %} {{ '' }} {% endif %}"

Body:
So you want to run a role differently, based on variables.

In your playbook do not use

roles:
  - role: davidwittman.redis

but rather do

tasks:
  - name: Pass variables to role
    include_role:
      name: myrole
    vars:
      rolevar1: value from task

This is executed after roles but now you can add when expressions:

tasks:
  - name: Pass variables to role
    include_role:
      name: myrole
    vars:
      rolevar1: value from task
    when: ansible_hostname = "server1"

  - name: Pass variables to role
    include_role:
      name: myrole
    vars:
      rolevar1: value from task
      additionalrolevar: whatever
    when: ansible_hostname != "server1"


问:
python using sqlalchemy store a list into sql database
The brief code is like this:

```<code>    class Word(Base):
        __tablename__ = 'word'
        eng                 = Column(String(32),primary_key=True)
        chinese             = Column(String(128))

word = Word(eng='art',chinese=[u'艺术',u'美术'])
session.add(word)
session.commit()
</code>```

I'm trying to store word.chinese as a string. And in python it's a list...
Well, when I write sql myself I could str(word.chinese) and then insert into the database.
When need to get it, I could simply eval(result) to get the original python object.
But since I'm using the sqlalchemy to store my objects, I wonder where to change to reach my goal...

答:
This is an old question that deserves newer answers.

As of the year 2022, you can use MutableList from sqlalchemy, as shown in this answer: https://stackoverflow.com/a/64356997/2719980

Body:
The brief code is like this:

    class Word(Base):
        __tablename__ = 'word'
        eng                 = Column(String(32),primary_key=True)
        chinese             = Column(String(128))

word = Word(eng='art',chinese=[u'艺术',u'美术'])
session.add(word)
session.commit()

I'm trying to store word.chinese as a string. And in python it's a list...
Well, when I write sql myself I could str(word.chinese) and then insert into the database.
When need to get it, I could simply eval(result) to get the original python object.
But since I'm using the sqlalchemy to store my objects, I wonder where to change to reach my goal...


问:
Webpack and Jquery - $ is not defined
Working first time on using Webpack in a ASP.Net Core project and running in to an issue bundling jQuery

```<code>$ is not defined
</code>```

webpack.config.json

const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

const bundleFileName = 'bundle';
const dirName = 'wwwroot/dist';

module.exports = (env, argv) => {
    return {
        mode: argv.mode === "production" ? "production" : "development",
        entry: ['./node_modules/bootstrap/dist/js/bootstrap.bundle.js', './wwwroot/js/site.js', './wwwroot/scss/site.scss'],
        output: {
            filename: bundleFileName + '.js',
            path: path.resolve(__dirname, dirName)
        },
        module: {
            rules: [
                {
                    test: /\.s[c|a]ss$/,
                    use:
                        [
                            'style-loader',
                            MiniCssExtractPlugin.loader,
                            'css-loader',
                            'postcss-loader',
                            'sass-loader'
                        ]
                }
            ]
        },
        plugins: [
            new webpack.ProvidePlugin({
                $: "jquery",
                jQuery: "jquery"
            }),
            new CleanWebpackPlugin(),
            new MiniCssExtractPlugin({
                filename: bundleFileName + '.css'
            })
        ]
    };
};
```

I have tried and exhausted all possible variations I could find on the internet without any luck.

Using npm run build during the .Net build process to create the bundles

答: "$ is not defined" means that at the time when your library tried to do something with jQuery, jQuery itself either wasn't loaded or loaded incorrectly. Make sure that jQuery loads correctly first, and only then can the rest of the code use this library. Usually it is enough to put a jQuery call before all other calls.

Title: Webpack and Jquery - $ is not defined

Body:
Working first time on using Webpack in a ASP.Net Core project and running in to an issue bundling jQuery

$ is not defined

webpack.config.json

const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

const bundleFileName = 'bundle';
const dirName = 'wwwroot/dist';

module.exports = (env, argv) => {
    return {
        mode: argv.mode === "production" ? "production" : "development",
        entry: ['./node_modules/bootstrap/dist/js/bootstrap.bundle.js', './wwwroot/js/site.js', './wwwroot/scss/site.scss'],
        output: {
            filename: bundleFileName + '.js',
            path: path.resolve(__dirname, dirName)
        },
        module: {
            rules: [
                {
                    test: /\.s[c|a]ss$/,
                    use:
                        [
                            'style-loader',
                            MiniCssExtractPlugin.loader,
                            'css-loader',
                            'postcss-loader',
                            'sass-loader'
                        ]
                }
            ]
        },
        plugins: [
            new webpack.ProvidePlugin({
                $: "jquery",
                jQuery: "jquery"
            }),
            new CleanWebpackPlugin(),
            new MiniCssExtractPlugin({
                filename: bundleFileName + '.css'
            })
        ]
    };
};

I have tried and exhausted all possible variations I could find on the internet without any luck.

Using npm run build during the .Net build process to create the bundles