问:
Clear beanstalk queue (laravel)
Project on larvel in Kubernetes
I need clear queue
My process

```<code>/var/www $ ps
PID   USER     TIME  COMMAND
    1 www-data  0:41 {supervisord} /usr/bin/python3 /usr/bin/supervisord -c /etc/supervisor/supervisord.conf -n
  346 www-data  0:00 /bin/sh
  393 www-data  0:53 php artisan queue:work --queue=messenger.hook.accept.0
  394 www-data  0:01 php artisan queue:work --queue=bot.run.accept.0

</code>```

When i make

```<code>php artisan queue:clear
</code>```

i get

```<code>Clearing queues is not supported on [BeanstalkdQueue]
</code>```

How clear queue? (some queue or all)

Title: Clear beanstalk queue (laravel)

Body:
Project on larvel in Kubernetes
I need clear queue
My process

/var/www $ ps
PID   USER     TIME  COMMAND
    1 www-data  0:41 {supervisord} /usr/bin/python3 /usr/bin/supervisord -c /etc/supervisor/supervisord.conf -n
  346 www-data  0:00 /bin/sh
  393 www-data  0:53 php artisan queue:work --queue=messenger.hook.accept.0
  394 www-data  0:01 php artisan queue:work --queue=bot.run.accept.0

When i make

php artisan queue:clear

i get

Clearing queues is not supported on [BeanstalkdQueue]

How clear queue? (some queue or all)


来源: stackexchange

问:
Cannot keep current user settings from updates - WPF .NET6 MSIX
I have an application using WPF .NET6 and packaging with MSIX. The application is deployed at a network share drive.

There are default settings build in the application but user will save individual user settings. I am trying to keep the user settings for each software update.

I find some similar questions for WPF clickonce application, but none of the solutions seems working for me. The user settings are overwritten with default settings on every software updates.

Keep user's settings after altering assembly/file version

Settings.Default.Upgrade() does not keep current settings

For example, I added thoes lines to app() on start up. But it does not work.

```<code>// Copy user settings from previous application version if necessary
if (MyApp.Properties.Settings.Default.UpdateSettings)
{
    MyApp.Properties.Settings.Default.Upgrade();
    MyApp.Properties.Settings.Default.UpdateSettings = false;
    MyApp.Properties.Settings.Default.Save();
}
</code>```

So with MSIX package, how to keep the current user settings on each software update?

ContentLicense: CC BY-SA 4.0

Body:
I have an application using WPF .NET6 and packaging with MSIX. The application is deployed at a network share drive.

There are default settings build in the application but user will save individual user settings. I am trying to keep the user settings for each software update.

I find some similar questions for WPF clickonce application, but none of the solutions seems working for me. The user settings are overwritten with default settings on every software updates.

Keep user's settings after altering assembly/file version

Settings.Default.Upgrade() does not keep current settings

For example, I added thoes lines to app() on start up. But it does not work.

// Copy user settings from previous application version if necessary
if (MyApp.Properties.Settings.Default.UpdateSettings)
{
    MyApp.Properties.Settings.Default.Upgrade();
    MyApp.Properties.Settings.Default.UpdateSettings = false;
    MyApp.Properties.Settings.Default.Save();
}

So with MSIX package, how to keep the current user settings on each software update?


问:
unable to add middleware to next.js
I'm new to Nextjs and facing such error. When I add middleware to protect my routes, I'm getting this error:

```<code>error - Error [TypeError]: Class extends value undefined is not a constructor or null
    at ../../node_modules/.pnpm/undici@5.11.0/node_modules/undici/lib/fetch/file.js (evalmachine.<anonymous>:5724:19)
    at __require (evalmachine.<anonymous>:14:50)
    at ../../node_modules/.pnpm/undici@5.11.0/node_modules/undici/lib/fetch/formdata.js (evalmachine.<anonymous>:5881:49)
    at __require (evalmachine.<anonymous>:14:50)
    at ../../node_modules/.pnpm/undici@5.11.0/node_modules/undici/lib/fetch/body.js (evalmachine.<anonymous>:6094:35)
    at __require (evalmachine.<anonymous>:14:50)
    at ../../node_modules/.pnpm/undici@5.11.0/node_modules/undici/lib/fetch/response.js (evalmachine.<anonymous>:6510:49)
    at __require (evalmachine.<anonymous>:14:50)
    at <unknown> (evalmachine.<anonymous>:11635:30)
    at requireFn (file://C:\Users\gelezhinis\Desktop\Web Development\My Projects\Reklaminiai.lt (next.js)\reklaminiai\node_modules\next\dist\compiled\edge-runtime\index.js:1:7079) {
  middleware: true
}
</code>```

When I remove middleware.js file, everything works.

middleware.js

```<code>import { NextResponse } from "next/dist/server/web/spec-extension/response";

export default function(req) {
  let verify = req.cookies.get('authenticated');
  let url = req.url;

  if (!verify && url.includes('/admin')) {
    return NextResponse.redirect('http://localhost:3000/');
  }
}
</code>```

Didn't find the solution online.

Title: unable to add middleware to next.js

Body:
I'm new to Nextjs and facing such error. When I add middleware to protect my routes, I'm getting this error:

error - Error [TypeError]: Class extends value undefined is not a constructor or null
    at ../../node_modules/.pnpm/undici@5.11.0/node_modules/undici/lib/fetch/file.js (evalmachine.<anonymous>:5724:19)
    at __require (evalmachine.<anonymous>:14:50)
    at ../../node_modules/.pnpm/undici@5.11.0/node_modules/undici/lib/fetch/formdata.js (evalmachine.<anonymous>:5881:49)
    at __require (evalmachine.<anonymous>:14:50)
    at ../../node_modules/.pnpm/undici@5.11.0/node_modules/undici/lib/fetch/body.js (evalmachine.<anonymous>:6094:35)
    at __require (evalmachine.<anonymous>:14:50)
    at ../../node_modules/.pnpm/undici@5.11.0/node_modules/undici/lib/fetch/response.js (evalmachine.<anonymous>:6510:49)
    at __require (evalmachine.<anonymous>:14:50)
    at <unknown> (evalmachine.<anonymous>:11635:30)
    at requireFn (file://C:\Users\gelezhinis\Desktop\Web Development\My Projects\Reklaminiai.lt (next.js)\reklaminiai\node_modules\next\dist\compiled\edge-runtime\index.js:1:7079) {
  middleware: true
}

When I remove middleware.js file, everything works.

middleware.js

import { NextResponse } from "next/dist/server/web/spec-extension/response";

export default function(req) {
  let verify = req.cookies.get('authenticated');
  let url = req.url;

  if (!verify && url.includes('/admin')) {
    return NextResponse.redirect('http://localhost:3000/');
  }
}

Didn't find the solution online.


问:
Adaptive cards full page width in Viva Connections?
Folks
Is it possible in Viva connections cards to have the Quick View use the full page width of the parent browser window? Mr Google says goes mum at this . I am using ACE version 1.2


问:
Why there are no compilation errors when using <as> for two classes that cannot be converted directly ？
enter image description here

I read the C # document and said that the as will not throw an runtime exception but will only return null.

Strangely, this code will even report an error directly at the compiler stage (because there is no common parent class) when its using (T)this cast.

But why can we compile successfully by using as in this case(even if the two types have no common parent class)?

...

enter image description here

```<code>return this as T;
</code>```

it can run and the result is correct.
.

```<code>return (T)this;
</code>```

unable to compile (underline error CS0030)

.
What's the matter? Is it true that as only checks whether the conversion is successful at runtime

I can understand that as does not throw exceptions when running,
I can also understand that "two reference types without a common parent class" cannot be cast.

However, two classes that cannot be coerced can be compiled by using the as keyword instead. Why ?# (crazy sweat)

.
When the two types cannot be converted, why doesn't as throw the same compile-time error as (T) this ?

Body:
enter image description here

I read the C # document and said that the as will not throw an runtime exception but will only return null.

Strangely, this code will even report an error directly at the compiler stage (because there is no common parent class) when its using (T)this cast.

But why can we compile successfully by using as in this case(even if the two types have no common parent class)?

...

enter image description here

return this as T;

it can run and the result is correct.
.

return (T)this;

unable to compile (underline error CS0030)

.
What's the matter? Is it true that as only checks whether the conversion is successful at runtime

I can understand that as does not throw exceptions when running,
I can also understand that "two reference types without a common parent class" cannot be cast.

However, two classes that cannot be coerced can be compiled by using the as keyword instead. Why ?# (crazy sweat)

.
When the two types cannot be converted, why doesn't as throw the same compile-time error as (T) this ?


问:
Why the same puppeteer script bypass Cloudfare on a server and not on another?
I have a puppeteer script which scrap a website.
I use some basic rotating proxy from webshare, using username/password authentication.

I have a VPS, the script is running onto it for a long time without a problem.

I wanted to stop the VPS because it cost too much, and run onto my own computer .

So I backup all files from my first VPS including :

package.json

package-lock.json

node_modules

I installed the same version of node on my machine.
And then, I just ran the script with "node myscript.js ...etc"

It runs a little, but a few seconds later, it begins to fail because cloudfare block my scraping activity.

I try to rent another VPS, install the same thing, same result.

The proxy list seems to be well used.

I check the chrome version, exactly the same : HeadlessChrome/103.0.5058.0

So, I ask to re-enable my old VPS, and run the script again.
It continues to run fine !

Is it possible that, because it's old and well known (IP ?), it's not detected by cloudfare ?
But I use proxy, so when I make my request, it pass through the proxy list, not at all from the IP machine no ?


问:
NoSuchMethodError when starting runTest
When I run runTest from org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4, I receive a NoSuchMethodError. Can anybody tell me what I'm doing wrong?

Here is my stacktrace:

```<code>'void kotlin.time.AbstractLongTimeSource.\<init\>(kotlin.time.DurationUnit)'
java.lang.NoSuchMethodError: 'void kotlin.time.AbstractLongTimeSource.\<init\>(kotlin.time.DurationUnit)'   at
kotlinx.coroutines.test.TestCoroutineScheduler$timeSource$1.\<init\>(TestCoroutineScheduler.kt:208)     at
kotlinx.coroutines.test.TestCoroutineScheduler.\<init\>(TestCoroutineScheduler.kt:208)
</code>```

My code:

```<code>@OptIn(ExperimentalCoroutinesApi::class) class MainTest { @Test fun test() { runTest {}     } }
</code>```

And my Build.gradle dependencies:

```<code>dependencies {
  testImplementation  ("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4")
  testImplementation("junit:junit:4.13.2")
  implementation(platform("org.jetbrains.kotlin:kotlin-bom"))
  implementation("org.jetbrains.kotlin:kotlin-stdlib-common:1.8.0")
  implementation("org.jetbrains.kotlin:kotlin-stdlib:1.8.0")
  implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")
  testImplementation("org.jetbrains.kotlin:kotlin-test")
  testImplementation("org.jetbrains.kotlin:kotlin-test-junit")
  implementation("com.google.guava:guava:31.1-jre")

  api("org.apache.commons:commons-math3:3.6.1")
  compileOnly("com.google.android:android:4.1.1.4")
}
</code>```

I tried to change the versions of dependencies.

Title: NoSuchMethodError when starting runTest

Body:
When I run runTest from org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4, I receive a NoSuchMethodError. Can anybody tell me what I'm doing wrong?

Here is my stacktrace:

'void kotlin.time.AbstractLongTimeSource.\<init\>(kotlin.time.DurationUnit)'
java.lang.NoSuchMethodError: 'void kotlin.time.AbstractLongTimeSource.\<init\>(kotlin.time.DurationUnit)'   at
kotlinx.coroutines.test.TestCoroutineScheduler$timeSource$1.\<init\>(TestCoroutineScheduler.kt:208)     at
kotlinx.coroutines.test.TestCoroutineScheduler.\<init\>(TestCoroutineScheduler.kt:208)

My code:

@OptIn(ExperimentalCoroutinesApi::class) class MainTest { @Test fun test() { runTest {}     } }

And my Build.gradle dependencies:

dependencies {
  testImplementation  ("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4")
  testImplementation("junit:junit:4.13.2")
  implementation(platform("org.jetbrains.kotlin:kotlin-bom"))
  implementation("org.jetbrains.kotlin:kotlin-stdlib-common:1.8.0")
  implementation("org.jetbrains.kotlin:kotlin-stdlib:1.8.0")
  implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")
  testImplementation("org.jetbrains.kotlin:kotlin-test")
  testImplementation("org.jetbrains.kotlin:kotlin-test-junit")
  implementation("com.google.guava:guava:31.1-jre")

  api("org.apache.commons:commons-math3:3.6.1")
  compileOnly("com.google.android:android:4.1.1.4")
}

I tried to change the versions of dependencies.


问:
React Native Sound Recorder Play on Browser
I am recording an audio message on React Native app using 'react-native-sound-recorder' and uploaded it to s3 bucket which gives me uploaded URL. Return URL play audio on app perfectly but same URL if I try to open in browser it's not playing.

Content type I am using 'audio/mp3'.

Thanks!
Ankit


问:
32 images saved only at a time when i use the crop option for the image and after deleting 1 image the cropping again works fine for again 32 images
When i use the cropping action on the image in my app it firstly saves it in the gallery at the first instance when i only touch the crop option.After touching the crop option for 32 times and successfully saving image in gallery it starts going back to the main activity when i touch it 33rd time.It does the same behaviour until i delete one image from the gallery, where it has saved those images. After that it again works for 32 clicks but after 32 it shows same behaviour. I have used the library ucrop by ytlantis.

This code is under the onclicklistner for the crop button and i want that the image should not get saved  in the gallery while i touch the crop button and this 32 times touch should get resolved please help somebody.

```<code>    val crop: FloatingActionButton = findViewById(R.id.crop)

    crop.setOnClickListener {

        fun getBitmapAsByteArray(bitmap: Bitmap): ByteArray {
            val outputStream = ByteArrayOutputStream()
            bitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream)
            return outputStream.toByteArray()
        }

        val options = UCrop.Options()
        options.setCompressionFormat(Bitmap.CompressFormat.PNG)
        Glide.with(this)
            .asBitmap()
            .load("$image_url")
            .into(object : CustomTarget<Bitmap>() {
                @RequiresApi(Build.VERSION_CODES.N)
                override fun onResourceReady(
                    resource: Bitmap,
                    transition: com.bumptech.glide.request.transition.Transition<in Bitmap>?
                ) {
                    val inputStream = ByteArrayInputStream(getBitmapAsByteArray(resource))
                    val byteArrayUri = Uri.parse(
                        MediaStore.Images.Media.insertImage(
                            contentResolver,
                            BitmapFactory.decodeStream(inputStream),
                            "Title",
                            null
                        )
                    )
                    val destinationUri = Uri.fromFile(File(cacheDir, "cropped"))
                    val uCrop = UCrop.of(byteArrayUri, destinationUri)
                        .withOptions(options)
                    startActivityForResult(
                        uCrop.getIntent(this@image_full_size_avtivity),
                        UCrop.REQUEST_CROP
                    )
                    val originalFile = File(cacheDir, "original_image.png")
                    originalFile.delete()
                    val croppedFile = File(cacheDir, "cropped.png")
                    croppedFile.delete()
                }

                override fun onLoadCleared(placeholder: Drawable?) {}
            })

    }

}
@RequiresApi(Build.VERSION_CODES.N)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (resultCode == Activity.RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
        val resultUri = UCrop.getOutput(data!!)
        val wallpaperManager = WallpaperManager.getInstance(this)
        val inputStream = resultUri?.let { contentResolver.openInputStream(it) }
        val bitmap = BitmapFactory.decodeStream(inputStream)
        wallpaperManager.setBitmap(bitmap, null, true, WallpaperManager.FLAG_LOCK)
    }
    super.onActivityResult(requestCode, resultCode, data)
}
}
</code>```

Body:
When i use the cropping action on the image in my app it firstly saves it in the gallery at the first instance when i only touch the crop option.After touching the crop option for 32 times and successfully saving image in gallery it starts going back to the main activity when i touch it 33rd time.It does the same behaviour until i delete one image from the gallery, where it has saved those images. After that it again works for 32 clicks but after 32 it shows same behaviour. I have used the library ucrop by ytlantis.

This code is under the onclicklistner for the crop button and i want that the image should not get saved  in the gallery while i touch the crop button and this 32 times touch should get resolved please help somebody.

    val crop: FloatingActionButton = findViewById(R.id.crop)

    crop.setOnClickListener {

        fun getBitmapAsByteArray(bitmap: Bitmap): ByteArray {
            val outputStream = ByteArrayOutputStream()
            bitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream)
            return outputStream.toByteArray()
        }

        val options = UCrop.Options()
        options.setCompressionFormat(Bitmap.CompressFormat.PNG)
        Glide.with(this)
            .asBitmap()
            .load("$image_url")
            .into(object : CustomTarget<Bitmap>() {
                @RequiresApi(Build.VERSION_CODES.N)
                override fun onResourceReady(
                    resource: Bitmap,
                    transition: com.bumptech.glide.request.transition.Transition<in Bitmap>?
                ) {
                    val inputStream = ByteArrayInputStream(getBitmapAsByteArray(resource))
                    val byteArrayUri = Uri.parse(
                        MediaStore.Images.Media.insertImage(
                            contentResolver,
                            BitmapFactory.decodeStream(inputStream),
                            "Title",
                            null
                        )
                    )
                    val destinationUri = Uri.fromFile(File(cacheDir, "cropped"))
                    val uCrop = UCrop.of(byteArrayUri, destinationUri)
                        .withOptions(options)
                    startActivityForResult(
                        uCrop.getIntent(this@image_full_size_avtivity),
                        UCrop.REQUEST_CROP
                    )
                    val originalFile = File(cacheDir, "original_image.png")
                    originalFile.delete()
                    val croppedFile = File(cacheDir, "cropped.png")
                    croppedFile.delete()
                }

                override fun onLoadCleared(placeholder: Drawable?) {}
            })

    }

}
@RequiresApi(Build.VERSION_CODES.N)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (resultCode == Activity.RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
        val resultUri = UCrop.getOutput(data!!)
        val wallpaperManager = WallpaperManager.getInstance(this)
        val inputStream = resultUri?.let { contentResolver.openInputStream(it) }
        val bitmap = BitmapFactory.decodeStream(inputStream)
        wallpaperManager.setBitmap(bitmap, null, true, WallpaperManager.FLAG_LOCK)
    }
    super.onActivityResult(requestCode, resultCode, data)
}
}


问:
I keep getting the location of memory instead of a string
```<code>class Menu:

 def __init__(self, name, items, start_time, end_time):
  self.name = name
  self.items = items
  self.start_time = start_time
  self.end_time = end_time

 def __repr__(self):
return "{name} menu available from {start_time} to {end_time}".format(name = self.name,start_time = self.start_time,end_time = self.end_time)

kids_items={
</code>```

'chicken nuggets': 6.50, 'fusilli with wild mushrooms': 12.00, 'apple juice': 3.00
}

```<code>kids_menu= Menu("Kids Menu", kids_items, 1100, 2100 )

print(kids_menu)
</code>```

I keep getting the location in memory instead of it printing
kids menu available from 1100 to 2100

Body:
class Menu:

 def __init__(self, name, items, start_time, end_time):
  self.name = name
  self.items = items
  self.start_time = start_time
  self.end_time = end_time

 def __repr__(self):
return "{name} menu available from {start_time} to {end_time}".format(name = self.name,start_time = self.start_time,end_time = self.end_time)

kids_items={

'chicken nuggets': 6.50, 'fusilli with wild mushrooms': 12.00, 'apple juice': 3.00
}

kids_menu= Menu("Kids Menu", kids_items, 1100, 2100 )

print(kids_menu)

I keep getting the location in memory instead of it printing
kids menu available from 1100 to 2100


问:
How to disable auto reformat HTML when pushing with IntelliJ?
I use IntelliJ IDEA 2021.1.3.

Every time I push, the HTML refactors things like this:

```<code><input type="text" id="numeroClient" formControlName="numeroClient" maxlength="10" class="form-control"
     [class]="form.get('numeroClient')?.status === 'INVALID' && form.get('numeroClient')?.touched ? 'is-invalid' : ''" placeholder="Numéro client"/>
</code>```

to this:

```<code><input
  type="text"
  id="numeroClient"
  formControlName="numeroClient"
  maxlength="10"
  class="form-control"
  [class]="form.get('numeroClient')?.status === 'INVALID' && form.get('numeroClient')?.touched ? 'is-invalid' : ''"
  placeholder="Numéro client"
/>
</code>```

I checked in the settings (Version control -> commit, and only "Analyze code" and "Check TODO" are checked).

How can I disable this?

Body:
I use IntelliJ IDEA 2021.1.3.

Every time I push, the HTML refactors things like this:

<input type="text" id="numeroClient" formControlName="numeroClient" maxlength="10" class="form-control"
     [class]="form.get('numeroClient')?.status === 'INVALID' && form.get('numeroClient')?.touched ? 'is-invalid' : ''" placeholder="Numéro client"/>

to this:

<input
  type="text"
  id="numeroClient"
  formControlName="numeroClient"
  maxlength="10"
  class="form-control"
  [class]="form.get('numeroClient')?.status === 'INVALID' && form.get('numeroClient')?.touched ? 'is-invalid' : ''"
  placeholder="Numéro client"
/>

I checked in the settings (Version control -> commit, and only "Analyze code" and "Check TODO" are checked).

How can I disable this?


问:
Spring REST Controller Swagger's default response template error
For JSON requests, the response template on Swagger is showing up properly. However, if I have MultiPartFile as request, the template seems to disappear.

This is the code for controller for MultiPartFile request.

```<code>...
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
...

    @ApiOperation(value = "Image Update")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "Patch complete",
                    content = @Content(schema = @Schema(implementation = ProfileDefaultResponseDto.class))),
            ...
            @ApiResponse(responseCode = "500", description = "Server Error")
    })
    @PatchMapping(value = "/img", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<DefaultResponseDto<Object>> updateImage(HttpServletRequest servletRequest,
                                                                  @RequestPart(required = false) MultipartFile image) {
    ...
}
</code>```

This is what the response template should look like. But it is not showing up like this.

Body:
For JSON requests, the response template on Swagger is showing up properly. However, if I have MultiPartFile as request, the template seems to disappear.

This is the code for controller for MultiPartFile request.

...
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
...

    @ApiOperation(value = "Image Update")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "Patch complete",
                    content = @Content(schema = @Schema(implementation = ProfileDefaultResponseDto.class))),
            ...
            @ApiResponse(responseCode = "500", description = "Server Error")
    })
    @PatchMapping(value = "/img", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<DefaultResponseDto<Object>> updateImage(HttpServletRequest servletRequest,
                                                                  @RequestPart(required = false) MultipartFile image) {
    ...
}

This is what the response template should look like. But it is not showing up like this.


问:
Conda SSL certificate error: self signed certificate
My question is in essence same to this one here - I installed Anaconda through Miniforge, and when attempting to install any package, the following error is shown: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate.

Steps that I have tried:

Downloaded the root SSL certificate of my organization from an HTTPS website, saved it as a .crt file in the following path:
"C:\Users\youruser.certificates\certificate.crt", and then used the "conda --set ssl_verify True" and "conda config --set ssl_verify .crt" commands. The error persisted.

Edit the .condarc file and manually add the line "ssl_verify: pathToYourFile.crt", here the error was "ssl_verify value must be a boolean, a path to a certificate bundle file, or a path to a directory containing certificates of trusted CAs"

Saving the root SSL as a .pem file, and adding it to cacert.pem. Didn't work

conda remove certifi
conda install certifi

Didn't work as the first command yielded an error.

Any other things I can try? Really need to get Conda running. The error after number 2 seemed promising, found a git from 2017 with a similar one, but apparently this was long fixed? (This one: https://github.com/conda/conda/issues/5884)

Thanks,

Max


问:
Inline Full row editing does not work when added calendar ag-grid
Before adding Date in this code, If I press on edit, I could edit the whole row.
It is not working now.

Stackblitz - https://stackblitz.com/edit/ag-grid-angular-hello-world-usmgsf?file=src/app/button-renderer.component.ts

```<code>app.component.html:

<ag-grid-angular
  style=" height: 800px; width:1000px"
  class="ag-theme-alpine"
  [rowData]="rowData"
  (gridReady)="onGridReady($event)"
  [editType]="'fullRow'"
  (rowEditingStopped)="(onRowEditingStopped)"
  [frameworkComponents]="frameworkComponents"
  [columnDefs]="columnDefs"
  [suppressClickEdit]="true"
>
</ag-grid-angular>
</code>```
```<code>app.component.ts
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { ButtonRendererComponent } from './button-renderer.component';
import { MyDateEditor } from './my-date-editor.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  frameworkComponents: any;
  api: any;
  rowData$!: Observable<any[]>;
  constructor(private http: HttpClient) {
    this.frameworkComponents = {
      buttonRenderer: ButtonRendererComponent,
      myDateEditor: MyDateEditor,
    };
  }
  rowData = [
    { make: 'Toyota', date: '24/04/1993', model: 'Celica', price: 35000 },
    { make: 'Ford', date: '24/04/1993', model: 'Mondeo', price: 32000 },
    { make: 'Porsche', date: '24/04/1993', model: 'Boxter', price: 72000 },
  ];

  columnDefs = [
    {
      headerName: 'Make',
      field: 'make',
      editable: true,
      resizable: true,
      cellEditor: 'agSelectCellEditor',
      cellEditorParams: {
        //values: this.getUniqueValues,
        values: ['Suzuki', 'Toyota', 'Ford', 'Porsche'],
      },
    },
    { field: 'date', cellEditor: 'myDateEditor', editable: true },
    { headerName: 'Model', field: 'model', editable: true, resizable: true },
    { headerName: 'Price', field: 'price', editable: true, resizable: true },
    {
      headerName: 'Edit',
      cellRenderer: 'buttonRenderer',
      cellRendererParams: {
        onClick: this.onEditButtonClick.bind(this),
        label: 'Edit',
      },
    },
    {
      headerName: 'Save',
      cellRenderer: 'buttonRenderer',
      cellRendererParams: {
        onClick: this.onSaveButtonClick.bind(this),
        label: 'Save',
      },
    },
    {
      headerName: 'Delete',
      cellRenderer: 'buttonRenderer',
      cellRendererParams: {
        onClick: this.onDeleteButtonClick.bind(this),
        label: 'Delete',
      },
    },
  ];

  onRowEditingStopped(params) {
    debugger;
  }

  onEditButtonClick(params) {
    this.api.startEditingCell({
      rowIndex: params.rowIndex,
      colKey: 'make',
    });
  }

  onSaveButtonClick(params) {
    this.api.stopEditing();
  }

  onDeleteButtonClick(params) {
    debugger;
    this.api.updateRowData({ remove: [params.data] });
  }

  onGridReady(params) {
    this.api = params.api;
  }
  getUniqueValues(field: string) {
    //let uniqueValues = this.rowData.forEach;
    //return uniqueValues;
    this.rowData.forEach((row) => {
      console.log(row.make);
    });
  }
}
</code>```
```<code>my-date-editor.component.ts:

import {
  AfterViewInit,
  Component,
  ViewChild,
  ViewContainerRef,
} from '@angular/core';

import { ICellEditorAngularComp } from 'ag-grid-angular';

import { format } from 'date-fns';

@Component({
  selector: 'date-cell',
  template: `
    <mat-form-field>
      <input
        matInput
        [matDatepicker]="picker"
        [value]="selectedDate"
        (dateChange)="onDateChanged($event)" />
      <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
      <mat-datepicker #picker></mat-datepicker>
    </mat-form-field>
  `,
})
export class MyDateEditor implements ICellEditorAngularComp {
  private params: any;
  private selectedDate = null;

  agInit(params: any): void {
    this.params = params;
  }

  getValue = () => {
    let dateString = null;
    if (this.selectedDate) {
      dateString = format(this.selectedDate, 'dd/MM/yyyy');
    }
    return dateString;
  };

  afterGuiAttached = () => {
    if (!this.params.value) {
      return;
    }
    const [_, day, month, year] = this.params.value.match(
      /^(\d{2})\/(\d{2})\/(\d{4})$/
    );
    let selectedDate = new Date(year, month - 1, day);

    this.selectedDate = selectedDate;
  };

  onDateChanged = (event) => {
    let date = event.value;
    if (date) {
      date.setHours(0, 0, 0, 0);
    }
    this.selectedDate = date;
  };
}

</code>```
```<code>button-renderer.component.ts

import { Component } from '@angular/core';
import { ICellRendererAngularComp } from 'ag-grid-angular';

@Component({
  selector: 'app-button-renderer',
  template: `
    <button type="button" (click)="onClick($event)">{{label}}</button>
    `,
})
export class ButtonRendererComponent implements ICellRendererAngularComp {
  params;
  label: string;

  agInit(params): void {
    this.params = params;
    this.label = this.params.label || null;
  }

  refresh(params?: any): boolean {
    return true;
  }

  onClick($event: any) {
    if (this.params.onClick instanceof Function) {
      const params = {
        event: $event,
        rowData: this.params.node.data,
      };
      this.params.onClick(this.params);
    }
  }
}
</code>```

Help me solve this issue. I am stuck at this for a long time and I cannot seem to figure this out

Body:
Before adding Date in this code, If I press on edit, I could edit the whole row.
It is not working now.

Stackblitz - https://stackblitz.com/edit/ag-grid-angular-hello-world-usmgsf?file=src/app/button-renderer.component.ts

app.component.html:

<ag-grid-angular
  style=" height: 800px; width:1000px"
  class="ag-theme-alpine"
  [rowData]="rowData"
  (gridReady)="onGridReady($event)"
  [editType]="'fullRow'"
  (rowEditingStopped)="(onRowEditingStopped)"
  [frameworkComponents]="frameworkComponents"
  [columnDefs]="columnDefs"
  [suppressClickEdit]="true"
>
</ag-grid-angular>

app.component.ts
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { ButtonRendererComponent } from './button-renderer.component';
import { MyDateEditor } from './my-date-editor.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  frameworkComponents: any;
  api: any;
  rowData$!: Observable<any[]>;
  constructor(private http: HttpClient) {
    this.frameworkComponents = {
      buttonRenderer: ButtonRendererComponent,
      myDateEditor: MyDateEditor,
    };
  }
  rowData = [
    { make: 'Toyota', date: '24/04/1993', model: 'Celica', price: 35000 },
    { make: 'Ford', date: '24/04/1993', model: 'Mondeo', price: 32000 },
    { make: 'Porsche', date: '24/04/1993', model: 'Boxter', price: 72000 },
  ];

  columnDefs = [
    {
      headerName: 'Make',
      field: 'make',
      editable: true,
      resizable: true,
      cellEditor: 'agSelectCellEditor',
      cellEditorParams: {
        //values: this.getUniqueValues,
        values: ['Suzuki', 'Toyota', 'Ford', 'Porsche'],
      },
    },
    { field: 'date', cellEditor: 'myDateEditor', editable: true },
    { headerName: 'Model', field: 'model', editable: true, resizable: true },
    { headerName: 'Price', field: 'price', editable: true, resizable: true },
    {
      headerName: 'Edit',
      cellRenderer: 'buttonRenderer',
      cellRendererParams: {
        onClick: this.onEditButtonClick.bind(this),
        label: 'Edit',
      },
    },
    {
      headerName: 'Save',
      cellRenderer: 'buttonRenderer',
      cellRendererParams: {
        onClick: this.onSaveButtonClick.bind(this),
        label: 'Save',
      },
    },
    {
      headerName: 'Delete',
      cellRenderer: 'buttonRenderer',
      cellRendererParams: {
        onClick: this.onDeleteButtonClick.bind(this),
        label: 'Delete',
      },
    },
  ];

  onRowEditingStopped(params) {
    debugger;
  }

  onEditButtonClick(params) {
    this.api.startEditingCell({
      rowIndex: params.rowIndex,
      colKey: 'make',
    });
  }

  onSaveButtonClick(params) {
    this.api.stopEditing();
  }

  onDeleteButtonClick(params) {
    debugger;
    this.api.updateRowData({ remove: [params.data] });
  }

  onGridReady(params) {
    this.api = params.api;
  }
  getUniqueValues(field: string) {
    //let uniqueValues = this.rowData.forEach;
    //return uniqueValues;
    this.rowData.forEach((row) => {
      console.log(row.make);
    });
  }
}

my-date-editor.component.ts:

import {
  AfterViewInit,
  Component,
  ViewChild,
  ViewContainerRef,
} from '@angular/core';

import { ICellEditorAngularComp } from 'ag-grid-angular';

import { format } from 'date-fns';

@Component({
  selector: 'date-cell',
  template: `
    <mat-form-field>
      <input
        matInput
        [matDatepicker]="picker"
        [value]="selectedDate"
        (dateChange)="onDateChanged($event)" />
      <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
      <mat-datepicker #picker></mat-datepicker>
    </mat-form-field>
  `,
})
export class MyDateEditor implements ICellEditorAngularComp {
  private params: any;
  private selectedDate = null;

  agInit(params: any): void {
    this.params = params;
  }

  getValue = () => {
    let dateString = null;
    if (this.selectedDate) {
      dateString = format(this.selectedDate, 'dd/MM/yyyy');
    }
    return dateString;
  };

  afterGuiAttached = () => {
    if (!this.params.value) {
      return;
    }
    const [_, day, month, year] = this.params.value.match(
      /^(\d{2})\/(\d{2})\/(\d{4})$/
    );
    let selectedDate = new Date(year, month - 1, day);

    this.selectedDate = selectedDate;
  };

  onDateChanged = (event) => {
    let date = event.value;
    if (date) {
      date.setHours(0, 0, 0, 0);
    }
    this.selectedDate = date;
  };
}

button-renderer.component.ts

import { Component } from '@angular/core';
import { ICellRendererAngularComp } from 'ag-grid-angular';

@Component({
  selector: 'app-button-renderer',
  template: `
    <button type="button" (click)="onClick($event)">{{label}}</button>
    `,
})
export class ButtonRendererComponent implements ICellRendererAngularComp {
  params;
  label: string;

  agInit(params): void {
    this.params = params;
    this.label = this.params.label || null;
  }

  refresh(params?: any): boolean {
    return true;
  }

  onClick($event: any) {
    if (this.params.onClick instanceof Function) {
      const params = {
        event: $event,
        rowData: this.params.node.data,
      };
      this.params.onClick(this.params);
    }
  }
}

Help me solve this issue. I am stuck at this for a long time and I cannot seem to figure this out


问:
postgresql error User "redacted_user" has no password assigned. NOT USING DOCKER
So I'm editing my original post and reducing it a bit.

I have a server running Ubuntu 22.04LTS and postgresql 10. I have installed an application on it that requires access to the dbase via it's own dbase user, password and the dbase "gitea".

I created a user "gitea" with a password in postrgesql and I can access it locally using the following command:

```<code>psql gitea gitea
</code>```

My pg_hba.conf file is:

```<code># Database administrative login by Unix domain socket
local   all             postgres                                peer
# TYPE  DATABASE        USER            ADDRESS                 METHOD
host    all             bugs            127.0.0.1       255.255.255.255 md5
host    all             gitea           127.0.0.1       255.255.255.255 md5

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            scram-sha-256
# IPv6 local connections:
host    all             all             ::1/128                 scram-sha-256
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            scram-sha-256
host    replication     all             ::1/128                 scram-sha-256
</code>```

So why does this allow me to access the dbase without a password? Is it an easy change to make sure that the user "gitea" always has to use a password whether it's local or remote?

Cheers!!

Body:
So I'm editing my original post and reducing it a bit.

I have a server running Ubuntu 22.04LTS and postgresql 10. I have installed an application on it that requires access to the dbase via it's own dbase user, password and the dbase "gitea".

I created a user "gitea" with a password in postrgesql and I can access it locally using the following command:

psql gitea gitea

My pg_hba.conf file is:

# Database administrative login by Unix domain socket
local   all             postgres                                peer
# TYPE  DATABASE        USER            ADDRESS                 METHOD
host    all             bugs            127.0.0.1       255.255.255.255 md5
host    all             gitea           127.0.0.1       255.255.255.255 md5

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            scram-sha-256
# IPv6 local connections:
host    all             all             ::1/128                 scram-sha-256
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            scram-sha-256
host    replication     all             ::1/128                 scram-sha-256

So why does this allow me to access the dbase without a password? Is it an easy change to make sure that the user "gitea" always has to use a password whether it's local or remote?

Cheers!!


问:
How to give new input again in flutter_form_builder textfield if there is happen any error to submission data in server?
I am using flutter_form_builder package as input field in login screen. I submit data nicely, everything is working fine. But if there is any login failure happens then input field is unable to give new input later on. Could anyone please help me with sharing a solution? Thanks in advance! Here you go with my code-

```<code>FormBuilder(
                key: _formKey,
                enabled: !_isLoading,
                autovalidateMode: AutovalidateMode.disabled,
                onChanged: () {
                  _formKey.currentState!.save();
                },
                child: Column(
                  children: <Widget>[
                    const EmailTextField(
                      name: 'loginEmail',
                      hintText: 'Email',
                      prefixIcon: emailIcon,
                    ),
                    sixteenVerticalSpace,
                     const PasswordInputField(
                      name: 'password',
                      hintText: 'Password',
                    ),
                    Align(
                      alignment: Alignment.centerRight,
                      child: TextButton(
                          onPressed: () {
                            Get.to(()=> const ForgotPasswordScreen());
                          },
                          child: const Text(
                            'Forgot Password?',
                            style: fourteenBlackStyle,
                          )),
                    ),
                    PrimaryButton(
                      buttonTitle: 'Sign in',
                      onTap: () async {

                        if (_formKey.currentState?.saveAndValidate() ?? false) {
                          try{
                            if (!_isLoading) {
                              setState(() {
                                _isLoading = true;
                              });

                              // Send request to server
                              var response = await sendLoginRequest(
                                _formKey.currentState?.value['loginEmail'],
                                _formKey.currentState?.value['password'],
                              );

                              var data = response['data'];

                              if (response['status'] == 'success') {

                                final accessKey = data['access_token'];
                                final userId = data['user']['id'].toString();
                                final levelId = data['user']['level_id'].toString();

                                await localStorage.write(
                                    key: 'access_key',
                                    value: accessKey);
                                await localStorage.write(
                                    key: 'user_id',
                                    value: userId);
                                await localStorage.write(
                                    key: 'level_id',
                                    value: levelId);

                                 Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => const QuoteScreen()));
                                CustomSnack.successSnack('You are logged in Successfully');

                              } else {
                                CustomSnack.warningSnack('${data['message']}');
                              }
                            }
                          } catch(e) {
                            CustomSnack.warningSnack(e.toString());
                          } finally {
                            setState(() {
                              _isLoading = false;
                            });
                           // _formKey.currentState?.reset();
                          }
                        }
                      },
                      buttonColor: primaryColor,
                      isLoading: _isLoading,
                    ),
                    _signUpOption(),
                  ],
                ),
              ),
</code>```

Body:
I am using flutter_form_builder package as input field in login screen. I submit data nicely, everything is working fine. But if there is any login failure happens then input field is unable to give new input later on. Could anyone please help me with sharing a solution? Thanks in advance! Here you go with my code-

FormBuilder(
                key: _formKey,
                enabled: !_isLoading,
                autovalidateMode: AutovalidateMode.disabled,
                onChanged: () {
                  _formKey.currentState!.save();
                },
                child: Column(
                  children: <Widget>[
                    const EmailTextField(
                      name: 'loginEmail',
                      hintText: 'Email',
                      prefixIcon: emailIcon,
                    ),
                    sixteenVerticalSpace,
                     const PasswordInputField(
                      name: 'password',
                      hintText: 'Password',
                    ),
                    Align(
                      alignment: Alignment.centerRight,
                      child: TextButton(
                          onPressed: () {
                            Get.to(()=> const ForgotPasswordScreen());
                          },
                          child: const Text(
                            'Forgot Password?',
                            style: fourteenBlackStyle,
                          )),
                    ),
                    PrimaryButton(
                      buttonTitle: 'Sign in',
                      onTap: () async {

                        if (_formKey.currentState?.saveAndValidate() ?? false) {
                          try{
                            if (!_isLoading) {
                              setState(() {
                                _isLoading = true;
                              });

                              // Send request to server
                              var response = await sendLoginRequest(
                                _formKey.currentState?.value['loginEmail'],
                                _formKey.currentState?.value['password'],
                              );

                              var data = response['data'];

                              if (response['status'] == 'success') {

                                final accessKey = data['access_token'];
                                final userId = data['user']['id'].toString();
                                final levelId = data['user']['level_id'].toString();

                                await localStorage.write(
                                    key: 'access_key',
                                    value: accessKey);
                                await localStorage.write(
                                    key: 'user_id',
                                    value: userId);
                                await localStorage.write(
                                    key: 'level_id',
                                    value: levelId);

                                 Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => const QuoteScreen()));
                                CustomSnack.successSnack('You are logged in Successfully');

                              } else {
                                CustomSnack.warningSnack('${data['message']}');
                              }
                            }
                          } catch(e) {
                            CustomSnack.warningSnack(e.toString());
                          } finally {
                            setState(() {
                              _isLoading = false;
                            });
                           // _formKey.currentState?.reset();
                          }
                        }
                      },
                      buttonColor: primaryColor,
                      isLoading: _isLoading,
                    ),
                    _signUpOption(),
                  ],
                ),
              ),


问:
Node.js Array.filter not filtering out collection with matching id
I am working on a side project, trying to up my knowledge of React.js and Node.js and I have the following code in my Node server:

```<code>export const deleteConnection = async (req, res) => {
  try {
    let deletedConnection = await Connection.findByIdAndDelete(
      req.params.connectionId
    ).exec();
    let user = await User.findById(req.params.userId).exec();
    console.log(user);
    const remainingConnections = user.connections.filter(
      (c) => c.connection !== req.params.connectionId
    );
    console.log(remainingConnections);
    res.status(200).json(deletedConnection);
  } catch (err) {
    console.log(err);
    res.status(400).send("Unable to delete connection", err);
  }
};
</code>```

In the code, I have a collection called Connection and another one called User. I delete the Connection collection, and then I'm trying to filter out the Connection that matches the connectionId. However, it isn't working, and I don't know why. There are no errors in the code, and I leave screenshots below of what the server prints out. The Connection collection is deleted, but the filter is not filtering out the Connection that matches the connectionId, so I have no way of updating the User collection. I don't know if I'm missing something about Node.js that prevents it from working, but in React.js something like this would definitely work.

For reference, the userId is the string ending with bb8bd83 and the connectionId is ending with bb8bd8f. The top object in the second screenshot is the Connection that matches the connectionId (which shouldn't appear), and everything is accessed correctly (e.g. nothing prints out undefined or anything like that). Below is what the user console.log prints out:

And here is what the remainingConnections console.log prints out:

Body:
I am working on a side project, trying to up my knowledge of React.js and Node.js and I have the following code in my Node server:

export const deleteConnection = async (req, res) => {
  try {
    let deletedConnection = await Connection.findByIdAndDelete(
      req.params.connectionId
    ).exec();
    let user = await User.findById(req.params.userId).exec();
    console.log(user);
    const remainingConnections = user.connections.filter(
      (c) => c.connection !== req.params.connectionId
    );
    console.log(remainingConnections);
    res.status(200).json(deletedConnection);
  } catch (err) {
    console.log(err);
    res.status(400).send("Unable to delete connection", err);
  }
};

In the code, I have a collection called Connection and another one called User. I delete the Connection collection, and then I'm trying to filter out the Connection that matches the connectionId. However, it isn't working, and I don't know why. There are no errors in the code, and I leave screenshots below of what the server prints out. The Connection collection is deleted, but the filter is not filtering out the Connection that matches the connectionId, so I have no way of updating the User collection. I don't know if I'm missing something about Node.js that prevents it from working, but in React.js something like this would definitely work.

For reference, the userId is the string ending with bb8bd83 and the connectionId is ending with bb8bd8f. The top object in the second screenshot is the Connection that matches the connectionId (which shouldn't appear), and everything is accessed correctly (e.g. nothing prints out undefined or anything like that). Below is what the user console.log prints out:

And here is what the remainingConnections console.log prints out:


问:
Performance of logging to a file vs logging to the console
Is logging to file(s) generally known to be more performant than logging directly to the console? I read an article recently where somebody said you should log to files in production, but I can't find any evidence to back this up.</p>


问:
How to split a div width on Primeng resizable table columns so table fit all space
I have a Primeng table where I managed to add/remove columns by a primeng pickList
The columns are more than 100 , and the user can reset his selection to use default ones which are 9 columns
When user wanna to use default columns I wish i can make them fill container div widh
so no white space at the right

I want the table to fit all space if there is only the default columns

I tried to destroy the table from DOM then change the values in LocalStorage then render the table again

```<code>try{
            const payload: any = {};
            let array = this.selectedColumns.map(y => y.resizedByUser || widthToUse)
            payload.columnWidths = '173,';
            payload.columnWidths += array.join(',');
            payload.columnWidths += ',183';
            payload.filters = {};
            payload.first = 0;
            payload.rows = 20;
            payload.selection = [];
            payload.tableWidth = array.reduce((a, b) => a + b, 0);
            //this.dt.restoreColumnWidths();
            localStorage.setItem(this.resizeLocal, JSON.stringify(payload));
        }catch (err){

        }
</code>```
```<code>  let tableWidth = document.getElementById("my-table-clone").offsetWidth;
            let totalColsWidth = 173+183;
            this.selectedColumns.forEach((r)=>{
                totalColsWidth+=1
            })

            let widthToUse = 45
            if(tableWidth>=totalColsWidth){
                let difference = tableWidth - totalColsWidth
                let addition = difference / (this.selectedColumns.length || 1)
                widthToUse = addition + 45
            }

            this.initialConfig(widthToUse);
</code>```

When I choose different value than 1 - 45 it does not work , it is likely the values at columnWidths not using px , or use some Math calculation

Body:
I have a Primeng table where I managed to add/remove columns by a primeng pickList
The columns are more than 100 , and the user can reset his selection to use default ones which are 9 columns
When user wanna to use default columns I wish i can make them fill container div widh
so no white space at the right

I want the table to fit all space if there is only the default columns

I tried to destroy the table from DOM then change the values in LocalStorage then render the table again

try{
            const payload: any = {};
            let array = this.selectedColumns.map(y => y.resizedByUser || widthToUse)
            payload.columnWidths = '173,';
            payload.columnWidths += array.join(',');
            payload.columnWidths += ',183';
            payload.filters = {};
            payload.first = 0;
            payload.rows = 20;
            payload.selection = [];
            payload.tableWidth = array.reduce((a, b) => a + b, 0);
            //this.dt.restoreColumnWidths();
            localStorage.setItem(this.resizeLocal, JSON.stringify(payload));
        }catch (err){

        }

  let tableWidth = document.getElementById("my-table-clone").offsetWidth;
            let totalColsWidth = 173+183;
            this.selectedColumns.forEach((r)=>{
                totalColsWidth+=1
            })

            let widthToUse = 45
            if(tableWidth>=totalColsWidth){
                let difference = tableWidth - totalColsWidth
                let addition = difference / (this.selectedColumns.length || 1)
                widthToUse = addition + 45
            }

            this.initialConfig(widthToUse);

When I choose different value than 1 - 45 it does not work , it is likely the values at columnWidths not using px , or use some Math calculation


问:
Refresh SVG animation in vuejs
So I have an SVG animation that looks like this: https://youtu.be/sU76rUbhkqw.

I did the animation inside the SVG code like that:

```

and to make it the background of my landing page I simply use the background: url(); on my section.

So the animation is perfect when the window is loaded for the first time, but when I refresh with F5 it doesn't restart the animation. I have to refresh the cache too with Ctrl+Maj+R.

I'd really like the animation to refresh when refreshing the page with F5 but I don't know how to do it.

Thanks for your help :)

Title: Refresh SVG animation in vuejs

Body:
So I have an SVG animation that looks like this: https://youtu.be/sU76rUbhkqw.

I did the animation inside the SVG code like that:

and to make it the background of my landing page I simply use the background: url(); on my section.

So the animation is perfect when the window is loaded for the first time, but when I refresh with F5 it doesn't restart the animation. I have to refresh the cache too with Ctrl+Maj+R.

I'd really like the animation to refresh when refreshing the page with F5 but I don't know how to do it.

Thanks for your help :)


问:
How do I use trigger to destroy blocks on quest 2 unity?
I am making a game in Unity that is a combination of gorilla tag and minecraft and I am having trouble with using the RawAxsis1D.RIndexTrigger (top right quest 2 controller trigger) to destroy objects. (Some of my objects I'm trying to destroy have children.) I am also using raycasing so that it will make it so it will destroy the object the player is looking at, so far everything I have tried has failed.

Can anyone help me out? I am happy to provide any further info.

Main problem: when I add my script to my player, it did not do anything when the trigger was hit.


问:
Pandas/Seaborn KeyError: "['D06'] not in index" for large PairGrid as well as size and output issues
I am trying to copy this example from the Seaborn website: https://seaborn.pydata.org/examples/pairgrid_dotplot.html

Edit: Please note that some of the comments in the code are just from me trying to understand what the original seaborn code meant.

```<code>    Dist_codes = [ 'D06', 'D02', 'D01', 'D03', 'D09', 'D10', 'D08', 'D12', 'D97', 'D11', 'D98', 'D13',
              'D14', 'D16', 'D07', 'D15', 'D18', 'D17', 'D04', 'D20', 'D19', 'D21', 'D93', 'D22', 'D29', 'D30',
              'D23', 'D26', 'D24', 'D25', 'D27', 'D28', 'D31', 'D32', 'D33', 'D34', 'D95', 'D35', 'D38', 'D37',
              'D36', 'D39', 'D40', 'D41', 'D44', 'D45', 'D42', 'D43', 'D46', 'D56', 'D57', 'D58', 'D59', 'D47',
              'D49', 'D50', 'D51', 'D48', 'D53', 'D52', 'D54', 'D55', 'D60', 'D61', 'D63', 'D62', 'D64', 'D65',
              'D66', 'D67', 'D68', 'D69', 'D70', 'D71', 'D73', 'D74', 'D75', 'D76', 'D78', 'D77', 'D79', 'D80',
              'D81', 'D83', 'D84', 'D94', 'D82', 'D85', 'D86', 'D89', 'D90', 'D87', 'D88', 'D91'
]

test_data = pd.DataFrame(data=np.random.randint(1,150,size=(94,8)),columns=np.arange(2016,2024,1), index=Dist_codes)

# Make the PairGrid
g = sns.PairGrid(test_data, #sorts values so that largets crash appears first
                 x_vars=test_data.columns, y_vars=Dist_codes, #x is a list of the columns for crash type, y is the sates abrevated
                 height=2, aspect=.25) #Height (in inches) of each facet., Aspect * height gives the width (in inches) of each facet.

# Draw a dot plot using the stripplot function
g.map(sns.stripplot, size=10, orient="h", jitter=False, #categorical scatterplot using jitter to reduce overplotting
      palette="flare_r", linewidth=1, edgecolor="w")

# Use the same x axis limits on all columns and add better labels
g.set(xlim=(0, 150), xlabel="Total Active Cases", ylabel="")

# Use semantically meaningful titles for the columns
titles = test_data.columns

for ax, title in zip(g.axes.flat, titles):

    # Set a different title for each axes
    ax.set(title=title)

    # Make the grid horizontal instead of vertical
    ax.xaxis.grid(False)
    ax.yaxis.grid(True)

sns.despine(left=True, bottom=True) #remove spines from plots

</code>```

So far all I get as an ouput is

```<code>
KeyError: "['D06'] not in index"
</code>```

and a blank chart. Please advise on where I am going wrong

Body:
I am trying to copy this example from the Seaborn website: https://seaborn.pydata.org/examples/pairgrid_dotplot.html

Edit: Please note that some of the comments in the code are just from me trying to understand what the original seaborn code meant.

    Dist_codes = [ 'D06', 'D02', 'D01', 'D03', 'D09', 'D10', 'D08', 'D12', 'D97', 'D11', 'D98', 'D13',
              'D14', 'D16', 'D07', 'D15', 'D18', 'D17', 'D04', 'D20', 'D19', 'D21', 'D93', 'D22', 'D29', 'D30',
              'D23', 'D26', 'D24', 'D25', 'D27', 'D28', 'D31', 'D32', 'D33', 'D34', 'D95', 'D35', 'D38', 'D37',
              'D36', 'D39', 'D40', 'D41', 'D44', 'D45', 'D42', 'D43', 'D46', 'D56', 'D57', 'D58', 'D59', 'D47',
              'D49', 'D50', 'D51', 'D48', 'D53', 'D52', 'D54', 'D55', 'D60', 'D61', 'D63', 'D62', 'D64', 'D65',
              'D66', 'D67', 'D68', 'D69', 'D70', 'D71', 'D73', 'D74', 'D75', 'D76', 'D78', 'D77', 'D79', 'D80',
              'D81', 'D83', 'D84', 'D94', 'D82', 'D85', 'D86', 'D89', 'D90', 'D87', 'D88', 'D91'
]

test_data = pd.DataFrame(data=np.random.randint(1,150,size=(94,8)),columns=np.arange(2016,2024,1), index=Dist_codes)

# Make the PairGrid
g = sns.PairGrid(test_data, #sorts values so that largets crash appears first
                 x_vars=test_data.columns, y_vars=Dist_codes, #x is a list of the columns for crash type, y is the sates abrevated
                 height=2, aspect=.25) #Height (in inches) of each facet., Aspect * height gives the width (in inches) of each facet.

# Draw a dot plot using the stripplot function
g.map(sns.stripplot, size=10, orient="h", jitter=False, #categorical scatterplot using jitter to reduce overplotting
      palette="flare_r", linewidth=1, edgecolor="w")

# Use the same x axis limits on all columns and add better labels
g.set(xlim=(0, 150), xlabel="Total Active Cases", ylabel="")

# Use semantically meaningful titles for the columns
titles = test_data.columns

for ax, title in zip(g.axes.flat, titles):

    # Set a different title for each axes
    ax.set(title=title)

    # Make the grid horizontal instead of vertical
    ax.xaxis.grid(False)
    ax.yaxis.grid(True)

sns.despine(left=True, bottom=True) #remove spines from plots

So far all I get as an ouput is

KeyError: "['D06'] not in index"

and a blank chart. Please advise on where I am going wrong


问:
Zipline - Working with hourly timeseries data for backtesting
My machine learning model made training- and test set for around 100 stocks to make the predictions on an hourly basis. The data comes from a csv-file and is used by pandas in a multi-dataframe. Now, I want to backtest these predictions on my own csv-datafiles with Zipline. Zipline has several updated versions, communities which discuss issues, or other solved requests, but none of them do explain how to ingest hourly data or work with hourly data, instead of minute or daily data.

So my question is:
How can I backtest based on hourly data with zipline? Since zipline officially works only on a minute or daily timeframe.

My preference working with Zipline is the multi-timeframe function and the multitimeseries backtesting results, which are very detailed. The part from 'Tear Sheets' in the following link is what I want https://github.com/PacktPublishing/Machine-Learning-for-Algorithmic-Trading-Second-Edition/blob/master/11_decision_trees_random_forests/07_backtesting_with_zipline.ipynb

Or, maybe there are other backtesters which can do the same with machine learning predictions, but I haven't found them.


问:
ForEach Table, Union X,Y,Z
I have a SQL DB with tables that are created and updated programmatically.

What is the best approach to creating a new table from all the tables in my DB?  The tables will be dynamic and are all the same columns.

I'm assuming Union with a Foreach, but want to make there isn't a better way.

I have only created the powershell to import the CSVs to my DB so far.

Title: ForEach Table, Union X,Y,Z


问:
How can I convert disyunctive normal form to conjunctive normal form using equivalence rules?
For example, I have this (P^¬Q)v(Q^¬P)v(¬RvS) and I need to transform it into cnf with equivalence rules. More or less I can try to apply some things or others and make it.

More or less I can try to apply some things or others and make it. But maybe any of you can show me some kind of method to do or some steps to follow which are effective in every expression of boolean algebra to reach the cnf and pass with a 10 my exams.


问:
How to select and save foreign key from templates in Django views?
I am new to Django and I was trying to select a foreign key from my html template and save it in my database. It worked fine in admin panel but when I created a template myself I could display all the keys but I got error while posting the form.

Here is the model, views and html code.

```<code># urls.py

from django.contrib import admin
from django.urls import path
from Home import views

urlpatterns = [
    path('', views.home, name="Home"),
    path('postBlog', views.postBlog, name="Post-Blog"),
]

</code>```
```<code># views.py

from django.shortcuts import render
from django.http import HttpResponse
from Home.models import Blog, User
# from Home.forms import BlogForm

# Create your views here.
def home(request):
    return render(request, 'Home/HomePage.html')

def postBlog(request):

    if request.method == 'POST':

        title = request.POST.get('title')
        author = request.POST.get('author')
        blog = request.POST.get('blog')
        date = request.POST.get('date')
        time = request.POST.get('time')

        form = Blog(title=title, author=author, body=blog, date=date, time=time)

        form.save()
        return render(request, 'Home/HomePage.html', {'dic': form})

    else:

        users = User.objects.all()
        dic = {'users': users}

        return render(request, 'Forms/Post-Blogs.html', dic)
</code>```
```<code># models.py

from django.db import models
from django.contrib.auth.models import User
from django.forms import forms
from django.forms import Form

# Create your models here.
class Blog(models.Model):
    title = models.CharField(max_length=255)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField()
    date = models.DateField(default='2022-12-31')
    time = models.TimeField(default='06:00:00')

    def __str__(self):
        return self.title
</code>```
```<code># html

<form action="/postBlog" method="post">

                {% csrf_token %}

                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" id="floatingInput" placeholder="Enter title" name="title">
                        <label for="floatingInput">Title</label>
                    </div>

                    <div class="mb-3">

                        <select class="form-select" aria-label="Default select example" name="author">
                            <!-- <option selected>Gender</option> -->

                            {% for authors in users %}

                            <option value= {{authors.pk}}> {{authors}} </option>

                            {% endfor %}

                        </select>

                    </div>

                    <div class="form-floating mb-3">
                        <textarea class="form-control" placeholder="Enter blog" id="floatingTextarea2" style="height: 150px" name="blog"></textarea>
                        <label for="floatingTextarea2">Blog</label>
                    </div>

                    <div class="form-floating mb-3">
                        <input type="date" class="form-control" id="floatingdate" placeholder="Enter date" name="date">
                        <label for="floatingdate">Date</label>
                    </div>

                    <div class="form-floating mb-3">
                        <input type="time" class="form-control" id="floatingtime" placeholder="Enter time" name="time">
                        <label for="floatingtime">Time</label>
                    </div>

                    <button type="submit" class="btn btn-primary">Submit</button>

            </form>
</code>```

I got this error: Cannot assign "'2'": "Blog.author" must be a "User" instance.

Body:
I am new to Django and I was trying to select a foreign key from my html template and save it in my database. It worked fine in admin panel but when I created a template myself I could display all the keys but I got error while posting the form.

Here is the model, views and html code.

# urls.py

from django.contrib import admin
from django.urls import path
from Home import views

urlpatterns = [
    path('', views.home, name="Home"),
    path('postBlog', views.postBlog, name="Post-Blog"),
]

# views.py

from django.shortcuts import render
from django.http import HttpResponse
from Home.models import Blog, User
# from Home.forms import BlogForm

# Create your views here.
def home(request):
    return render(request, 'Home/HomePage.html')

def postBlog(request):

    if request.method == 'POST':

        title = request.POST.get('title')
        author = request.POST.get('author')
        blog = request.POST.get('blog')
        date = request.POST.get('date')
        time = request.POST.get('time')

        form = Blog(title=title, author=author, body=blog, date=date, time=time)

        form.save()
        return render(request, 'Home/HomePage.html', {'dic': form})

    else:

        users = User.objects.all()
        dic = {'users': users}

        return render(request, 'Forms/Post-Blogs.html', dic)

# models.py

from django.db import models
from django.contrib.auth.models import User
from django.forms import forms
from django.forms import Form

# Create your models here.
class Blog(models.Model):
    title = models.CharField(max_length=255)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField()
    date = models.DateField(default='2022-12-31')
    time = models.TimeField(default='06:00:00')

    def __str__(self):
        return self.title

# html

<form action="/postBlog" method="post">

                {% csrf_token %}

                        <input type="text" class="form-control" id="floatingInput" placeholder="Enter title" name="title">
                        Title

                        <select class="form-select" aria-label="Default select example" name="author">

                            {% for authors in users %}

                            <option value= {{authors.pk}}> {{authors}} </option>

                            {% endfor %}

                        </select>

                        <textarea class="form-control" placeholder="Enter blog" id="floatingTextarea2" style="height: 150px" name="blog"></textarea>
                        Blog

                        <input type="date" class="form-control" id="floatingdate" placeholder="Enter date" name="date">
                        Date

                        <input type="time" class="form-control" id="floatingtime" placeholder="Enter time" name="time">
                        Time

                    <button type="submit" class="btn btn-primary">Submit</button>

            </form>

I got this error: Cannot assign "'2'": "Blog.author" must be a "User" instance.


问:
boost log working in exe but crashing in dll

I have developed an application (application1) that uses boost::log with
severity_channel_logger_mt and two sinks (syslog_backend &
text_file_backend).

When I run the application as an .exe, the sinks work fine and I am able to see log text files generate from messages being passed across a network, but when
I link application1 as a .dll inside of another application (mainapp), I get
the following errors after about 20 seconds:

```<code>Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: boost::wrapexcept<boost::system::system_error> at memory location 0x000000F9BD9FF220.
Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: boost::wrapexcept<boost::system::system_error> at memory location 0x000000F9BD9FF220.
Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: boost::wrapexcept<boost::system::system_error> at memory location 0x000000F9BD9FF220.
Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: boost::wrapexcept<boost::system::system_error> at memory location 0x000000F9BD9FF220.
</code>```

After debugging, the exception happens in basic_sink_frontend.hpp and  core.hpp between these two calls:

basic_sink_frontend.hpp

```<code>backend.consume(rec, context->m_FormattedRecord);
</code>```

core.hpp

```<code>BOOST_FORCEINLINE void push_record(BOOST_RV_REF(record) rec)
{
    push_record_move(static_cast< record& >(rec));
}
</code>```

I have verified that the "rec" variable is not NULL.
The application1 DLL loads wihout error and I am able to run application1 functions from mainapp.
I still see message being passed across network from syslog sink, however text_file sink logs are not generated...
I built boost as a shared library and have the following libs in boost_1_80_0/stage/lib:
boost_log_setup-vc142-mt-x64-1_80
boost_log-vc142-mt-gd-x64-1_80
boost_log-vc142-mt-x64-1_80

Snippets from my code on how I use the loggers and sinks are below. Application1 uses boost::log and MainApp loads Application1 as DLL:

Application1:

#define DEFAULT_PORT 13000
#define DEFAULT_PORT_STRING "13000"
#define DEFAULT_IP "127.0.0.1"

enum class severity_levels
{
    info,
    warning,
    error
};

void Application1::init_builtin_syslog()
{

    // Create a syslog sink
    boost::shared_ptr< sinks::synchronous_sink< sinks::syslog_backend > > sys_sink(
        new sinks::synchronous_sink< sinks::syslog_backend >());

    sys_sink->set_formatter
    (
        expr::stream << "Application 1 Log - ID: " << expr::attr< unsigned int >("RecordID")
            << "| " << expr::attr< severity_levels >("Severity") << ": " << expr::smessage
    );

    // We'll have to map our custom levels to the syslog levels
    sinks::syslog::custom_severity_mapping< severity_levels > mapping("Severity");
    mapping[severity_levels::info] = sinks::syslog::info;
    mapping[severity_levels::warning] = sinks::syslog::warning;
    mapping[severity_levels::error] = sinks::syslog::critical;

    sys_sink->locked_backend()->set_severity_mapper(mapping);

    #if !defined(BOOST_LOG_NO_ASIO)
        // Set the remote address to send syslog messages to
        sys_sink->locked_backend()->set_target_address(DEFAULT_IP, DEFAULT_PORT);
    #endif

    //Create a text file sink
    boost::shared_ptr< sinks::synchronous_sink< sinks::text_file_backend > > file_sink(
        new sinks::synchronous_sink< sinks::text_file_backend >(
            keywords::file_name = "application1.log",  // file name pattern
            keywords::target_file_name = "application1_%Y%m%d_%H%M%S_%2N.log",
            keywords::rotation_size = 16384
            ));
    // Set up where the rotated files will be stored
    file_sink->locked_backend()->set_file_collector(sinks::file::make_collector(
        keywords::target = "logs",
        keywords::max_size = 64 * 1024 * 1024,
        keywords::min_free_space = 100 * 1024 * 1024,
        keywords::max_files = 512
        ));

    // Upon restart, scan the target directory for files matching the file_name pattern
    file_sink->locked_backend()->scan_for_files();

    file_sink->set_formatter
    (
        expr::format("%1% Application 1 Log - ID: %2% | %3% : \"%4%\"")
        % expr::attr< boost::posix_time::ptime >("TimeStamp")
        % expr::attr< unsigned int >("RecordID")
        % expr::attr< severity_levels >("Severity")
        % expr::smessage
    );

    // Add the sinks to the core
    logging::core::get()->add_sink(sys_sink);
    logging::core::get()->add_sink(file_sink);

    // Add logging attributes
    logging::core::get()->add_global_attribute("RecordID", attrs::counter< unsigned int >());
    logging::core::get()->add_global_attribute("TimeStamp", attrs::utc_clock());

}

int start()
{
   init_builtin_syslog();
   src::severity_channel_logger_mt\< severity_levels \> lg(keywords::severity = severity_levels::info, keywords::channel = "Application 1");

   for (int i = 0; i \< 10000; ++i)
   {
      BOOST_LOG_SEV(lg, severity_levels::info) \<\< infoLog;
      if(runexe) std::cout \<\< "App1 sent: " \<\< infoLog \<\< std::endl;
      boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));
   }
return 0;
}
```
<p>MainApp:</p>
```bool loadedApp1 = false;
std::atomic<bool> startApp1 = true;
std::atomic<char*> app1Err((char*)"");

HINSTANCE app1dll;
void printError( const TCHAR* msg );

typedef void (*MYPROC2)(std::atomic<bool>&, std::atomic<char*>&);
MYPROC2 app1start;

int main()
{

std::cout << "Starting application 1... " << std::endl;
        try
        {
            app1dll = LoadLibrary(TEXT("application1.dll"));
            if(app1dll == NULL)
            {
                std::cerr << "Application 1 DLL load library failure." << GetLastError() << '\n';
                loadedApp1 = false;
            }
            else
            {
                loadedApp1 = true;
                 app1start = (MYPROC2) GetProcAddress(app1dll, MAKEINTRESOURCEA(1));
                if (NULL != app1start)
                {
                    std::thread t1(app1start, std::ref(startApp1), std::ref(app1Err));
                    t1.detach();
                    std::this_thread::sleep_for(std::chrono::milliseconds(4000));
                }
                if(startApp1.load() == false)
                {
                    std::cout << "Error starting Application 1: " << app1Err.load() << std::endl;
                }
            }
}
 catch(const std::exception& e)
{
    std::cerr << e.what() << '\n';
    return 1;
}
return 0;
}
```

Body:
I have developed an application (application1) that uses boost::log with
severity_channel_logger_mt and two sinks (syslog_backend &
text_file_backend).

When I run the application as an .exe, the sinks work fine and I am able to see log text files generate from messages being passed across a network, but when
I link application1 as a .dll inside of another application (mainapp), I get
the following errors after about 20 seconds:

Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: boost::wrapexcept<boost::system::system_error> at memory location 0x000000F9BD9FF220.
Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: boost::wrapexcept<boost::system::system_error> at memory location 0x000000F9BD9FF220.
Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: boost::wrapexcept<boost::system::system_error> at memory location 0x000000F9BD9FF220.
Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: boost::wrapexcept<boost::system::system_error> at memory location 0x000000F9BD9FF220.

After debugging, the exception happens in basic_sink_frontend.hpp and  core.hpp between these two calls:

basic_sink_frontend.hpp

backend.consume(rec, context->m_FormattedRecord);

core.hpp

BOOST_FORCEINLINE void push_record(BOOST_RV_REF(record) rec)
{
    push_record_move(static_cast< record& >(rec));
}

I have verified that the "rec" variable is not NULL.
The application1 DLL loads wihout error and I am able to run application1 functions from mainapp.
I still see message being passed across network from syslog sink, however text_file sink logs are not generated...
I built boost as a shared library and have the following libs in boost_1_80_0/stage/lib:
boost_log_setup-vc142-mt-x64-1_80
boost_log-vc142-mt-gd-x64-1_80
boost_log-vc142-mt-x64-1_80

Snippets from my code on how I use the loggers and sinks are below. Application1 uses boost::log and MainApp loads Application1 as DLL:

Application1:

#define DEFAULT_PORT 13000
#define DEFAULT_PORT_STRING "13000"
#define DEFAULT_IP "127.0.0.1"

enum class severity_levels
{
    info,
    warning,
    error
};

void Application1::init_builtin_syslog()
{

    // Create a syslog sink
    boost::shared_ptr< sinks::synchronous_sink< sinks::syslog_backend > > sys_sink(
        new sinks::synchronous_sink< sinks::syslog_backend >());

    sys_sink->set_formatter
    (
        expr::stream << "Application 1 Log - ID: " << expr::attr< unsigned int >("RecordID")
            << "| " << expr::attr< severity_levels >("Severity") << ": " << expr::smessage
    );

    // We'll have to map our custom levels to the syslog levels
    sinks::syslog::custom_severity_mapping< severity_levels > mapping("Severity");
    mapping[severity_levels::info] = sinks::syslog::info;
    mapping[severity_levels::warning] = sinks::syslog::warning;
    mapping[severity_levels::error] = sinks::syslog::critical;

    sys_sink->locked_backend()->set_severity_mapper(mapping);

    #if !defined(BOOST_LOG_NO_ASIO)
        // Set the remote address to send syslog messages to
        sys_sink->locked_backend()->set_target_address(DEFAULT_IP, DEFAULT_PORT);
    #endif

    //Create a text file sink
    boost::shared_ptr< sinks::synchronous_sink< sinks::text_file_backend > > file_sink(
        new sinks::synchronous_sink< sinks::text_file_backend >(
            keywords::file_name = "application1.log",  // file name pattern
            keywords::target_file_name = "application1_%Y%m%d_%H%M%S_%2N.log",
            keywords::rotation_size = 16384
            ));
    // Set up where the rotated files will be stored
    file_sink->locked_backend()->set_file_collector(sinks::file::make_collector(
        keywords::target = "logs",
        keywords::max_size = 64 * 1024 * 1024,
        keywords::min_free_space = 100 * 1024 * 1024,
        keywords::max_files = 512
        ));

    // Upon restart, scan the target directory for files matching the file_name pattern
    file_sink->locked_backend()->scan_for_files();

    file_sink->set_formatter
    (
        expr::format("%1% Application 1 Log - ID: %2% | %3% : \"%4%\"")
        % expr::attr< boost::posix_time::ptime >("TimeStamp")
        % expr::attr< unsigned int >("RecordID")
        % expr::attr< severity_levels >("Severity")
        % expr::smessage
    );

    // Add the sinks to the core
    logging::core::get()->add_sink(sys_sink);
    logging::core::get()->add_sink(file_sink);

    // Add logging attributes
    logging::core::get()->add_global_attribute("RecordID", attrs::counter< unsigned int >());
    logging::core::get()->add_global_attribute("TimeStamp", attrs::utc_clock());

}

int start()
{
   init_builtin_syslog();
   src::severity_channel_logger_mt\< severity_levels \> lg(keywords::severity = severity_levels::info, keywords::channel = "Application 1");

   for (int i = 0; i \< 10000; ++i)
   {
      BOOST_LOG_SEV(lg, severity_levels::info) \<\< infoLog;
      if(runexe) std::cout \<\< "App1 sent: " \<\< infoLog \<\< std::endl;
      boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));
   }
return 0;
}

MainApp:

bool loadedApp1 = false;
std::atomic<bool> startApp1 = true;
std::atomic<char*> app1Err((char*)"");

HINSTANCE app1dll;
void printError( const TCHAR* msg );

typedef void (*MYPROC2)(std::atomic<bool>&, std::atomic<char*>&);
MYPROC2 app1start;

int main()
{

std::cout << "Starting application 1... " << std::endl;
        try
        {
            app1dll = LoadLibrary(TEXT("application1.dll"));
            if(app1dll == NULL)
            {
                std::cerr << "Application 1 DLL load library failure." << GetLastError() << '\n';
                loadedApp1 = false;
            }
            else
            {
                loadedApp1 = true;
                 app1start = (MYPROC2) GetProcAddress(app1dll, MAKEINTRESOURCEA(1));
                if (NULL != app1start)
                {
                    std::thread t1(app1start, std::ref(startApp1), std::ref(app1Err));
                    t1.detach();
                    std::this_thread::sleep_for(std::chrono::milliseconds(4000));
                }
                if(startApp1.load() == false)
                {
                    std::cout << "Error starting Application 1: " << app1Err.load() << std::endl;
                }
            }
}
 catch(const std::exception& e)
{
    std::cerr << e.what() << '\n';
    return 1;
}
return 0;
}


问:
Flutter - A TextEditingController was used after being disposed - Provider
I have a List of custom widgets that contain a TextFormField and use a TextEditingController which I initialize in the initState() function of the custom widget. I have wrapped the custom Widget in a Dismissible Widget to remove them from a list using the onDismissed function. This all looks like this:

```<code>@override
  void initState() {
    super.initState();
    widget.nameController = TextEditingController(text: widget.initialName);
    widget.amountController = TextEditingController(text: widget.initialAmount);
  }

  @override
  void dispose() {
    widget.nameController.dispose();
    widget.amountController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    CreateOrEditRecipe createOrEditRecipe =
        Provider.of<CreateOrEditRecipe>(context);

    return Dismissible(
      key: Key(widget.id),
      background: buildSwipeActionRight(),
      direction: DismissDirection.endToStart,
      onDismissed: (direction) {
        createOrEditRecipe.removeIngredientCard(widget.id);
      },
      child: Container(
        child: Row(
          children: <Widget>[
            SizedBox(
              width: SizeConfig.blockSizeHorizontal * 60,
              child: TextFormField(
                controller: widget.nameController,
                decoration: const InputDecoration(
                  labelText: "Foo",
                  labelStyle: TextStyle(fontSize: 12),
                ),
              ),
            ),
          ],
        ),
      ),
    );
</code>```
```<code>removeIngredientCard(String toRemove) {
    _ingredientCards.removeWhere((element) => element.id == toRemove);

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

After removing the UI is updated using notifyListeners().

This removes the custom Widget from the list correctly and the UI updates correctly aswell, but if I now select the TextFormField of the last of the remaining widgets in the list, I get an error.

This error does not appear when I remove the last widget of the list and then try to select the TextFormField of the last widget of the remaining ones.

Any ideas where the problem might be?

Body:
I have a List of custom widgets that contain a TextFormField and use a TextEditingController which I initialize in the initState() function of the custom widget. I have wrapped the custom Widget in a Dismissible Widget to remove them from a list using the onDismissed function. This all looks like this:

@override
  void initState() {
    super.initState();
    widget.nameController = TextEditingController(text: widget.initialName);
    widget.amountController = TextEditingController(text: widget.initialAmount);
  }

  @override
  void dispose() {
    widget.nameController.dispose();
    widget.amountController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    CreateOrEditRecipe createOrEditRecipe =
        Provider.of<CreateOrEditRecipe>(context);

    return Dismissible(
      key: Key(widget.id),
      background: buildSwipeActionRight(),
      direction: DismissDirection.endToStart,
      onDismissed: (direction) {
        createOrEditRecipe.removeIngredientCard(widget.id);
      },
      child: Container(
        child: Row(
          children: <Widget>[
            SizedBox(
              width: SizeConfig.blockSizeHorizontal * 60,
              child: TextFormField(
                controller: widget.nameController,
                decoration: const InputDecoration(
                  labelText: "Foo",
                  labelStyle: TextStyle(fontSize: 12),
                ),
              ),
            ),
          ],
        ),
      ),
    );

removeIngredientCard(String toRemove) {
    _ingredientCards.removeWhere((element) => element.id == toRemove);

    notifyListeners();
}

After removing the UI is updated using notifyListeners().

This removes the custom Widget from the list correctly and the UI updates correctly aswell, but if I now select the TextFormField of the last of the remaining widgets in the list, I get an error.

This error does not appear when I remove the last widget of the list and then try to select the TextFormField of the last widget of the remaining ones.

Any ideas where the problem might be?