问:
How to use Laravel AssertJson for testing a structured response
I have a signup API that returns a JSON response in this kind of format

```<code>{
    "meta": {
        //response metadata
    },
    "data": {
        //user object
    }
}
</code>```

I want to test this response with AssertableJson but I'm only concerned about the user object.

How do I use AssertableJson only for the data property of the response?

I've tried something like this with no success

```<code>$response->data->assertJson(
            function(AssertableJson $json){
                $json->whereType('id', 'string')
                     ->where('email', 'email@gmail.com')
                     ->etc();
            }
        );
</code>```

Body:
I have a signup API that returns a JSON response in this kind of format

{
    "meta": {
        //response metadata
    },
    "data": {
        //user object
    }
}

I want to test this response with AssertableJson but I'm only concerned about the user object.

How do I use AssertableJson only for the data property of the response?

I've tried something like this with no success

$response->data->assertJson(
            function(AssertableJson $json){
                $json->whereType('id', 'string')
                     ->where('email', 'email@gmail.com')
                     ->etc();
            }
        );


来源: stackexchange

问:
Pycharm typehint warning for AsyncContextManager
Is this a Pycharm typehinting bug because surely that return type should be implicitly hinted as bool | None, I'm guessing that's why the error is there?

Typehint warning: Type of '__aexit__' is incompatible with 'AsyncContextManager'

from contextlib import AbstractAsyncContextManager

class Test(AbstractAsyncContextManager):
    def __init__(self):
        ...

    async def __aenter__(self):
        ...
        return self

    async def __aexit__(self, exc_type, exc_value, traceback):
        ...
        return None
```

ContentLicense: CC BY-SA 4.0


问:
im trying to run apollo client in my react app , but iim getting this error Uncaught Invariant Violation: Invariant Violation: 9
I read all apollo documentation and followed them and this is what I tried but still can figure it out [![enter image description here][1]][1]</p>


问:
How to avoid NaN value for prometheus query if no http requests made in last 5 mins?
I have implemented one sli for error rate(success rate) for that I have written one prometheus query. It is giving result on the basis of http requests made based on 2xx & 5xx responses. But I want, what if no http request made in last 5 mins, what will be the result of that query ?

This is my working query which calculates error rate for last 5 mins.

sum by(instance) (rate(http_server_requests_seconds_count{status=~"2.."}[5m])) / ignoring(uri) sum by(instance) (rate(http_server_requests_seconds_count{status=~"5.."}[5m]))

With this query if no http request made in last 5 mins it is giving result as NaN, I want to set some default value instead of that.

Please help to solve this issue if no request made in last 5 mins, what should be default value and how to set it in above mentioned prometheus query.
Thanks In advance.


问:
Massive performance downgrade in Spring Batch application after update the Spring Boot Dependencies version from 2.4.2 to 2.7.6
We have upgraded a Spring Batch application in which the Spring Boot Dependencies is upgrade from version 2.4.2 to 2.7.6. Unfortunately we noticed a performance downgrade in processing the same file and eventually sending to Kafka using KafkaItemWriter.

We tried to do a few baby steps from version 2.4.2 to 2.4.4 and found that the version 2.4.2 uses the Spring Batch version 4.3.1 while the version 2.4.4 uses the Spring Batch version 4.3.2. To my point of view, it seems sending the data to Kafka asynchronously in the Spring Batch version 4.3.1 and sending the data to Kafka synchronously from the Spring Batch version 2.4.4 according to this release note where a change is made to wait for the result from KafkaItemWriter.

We tried to wrote our own implementation of KafkaItemWriter which reverted the changed made in the PR of the new version (https://github.com/spring-projects/spring-batch/pull/3827/commits/3acbaaa73dbaed3ea5e5e92c53b75780c50c86b6) and it could give us the good result but not sure if it is required to do a flush explicitly which could cause us any issues of losing data to Kafka broker down the line.

public class NoWaitKafkaItemWriter<K, T> extends KafkaItemWriter<K, T> {
    private static final Logger LOGGER = LogManager.getLogger(NoWaitKafkaItemWriter.class);

    @Override
    protected void writeKeyValue(K key, T value) {
        LOGGER.info("About to write key {} value {}", key, value);

        if (this.delete) {
            this.kafkaTemplate.sendDefault(key, null);
        } else {
            this.kafkaTemplate.sendDefault(key, value);
        }
    }

    @Override
    protected void flush() {
        // do nothing
        LOGGER.info("Do nothing in flush");
    }
}
```
<pre class="lang-java prettyprint-override"><code>@Bean
public KafkaItemWriter<String, MyKafkaObject> getKafkaItemWriter(
            KafkaTemplate<String, MyKafkaObject> kafkaProducerTemplate) {

    LOGGER.info("Creating KafkaItemWriter that doesn't wait");

    KafkaItemWriter writer = new NoWaitKafkaItemWriter();
    writer.setKafkaTemplate(kafkaProducerTemplate);
    writer.setItemKeyMapper(this.kafkaItemKeyMapper);

    return writer;
}
</code>```

We also tried with the timeout in 0 millisecond but it wouldn't help much since it is still waiting for the flush completion.

@Bean
public KafkaItemWriter<String, MyKafkaObject> getKafkaItemWriter(
        KafkaTemplate<String, MyKafkaObject> kafkaProducerTemplate) {

    LOGGER.info("Creating KafkaItemWriter");

    return new KafkaItemWriterBuilder<String, MyKafkaObject>()
            .kafkaTemplate(kafkaProducerTemplate)
            .itemKeyMapper(this.kafkaItemKeyMapper)
            .timeout(0)
            .build();
}
```

We are wondering if there is any options that we could make the application running asynchronously as it was before that change?

Any guidance would be much appreciated.

Body:
We have upgraded a Spring Batch application in which the Spring Boot Dependencies is upgrade from version 2.4.2 to 2.7.6. Unfortunately we noticed a performance downgrade in processing the same file and eventually sending to Kafka using KafkaItemWriter.

We tried to do a few baby steps from version 2.4.2 to 2.4.4 and found that the version 2.4.2 uses the Spring Batch version 4.3.1 while the version 2.4.4 uses the Spring Batch version 4.3.2. To my point of view, it seems sending the data to Kafka asynchronously in the Spring Batch version 4.3.1 and sending the data to Kafka synchronously from the Spring Batch version 2.4.4 according to this release note where a change is made to wait for the result from KafkaItemWriter.

We tried to wrote our own implementation of KafkaItemWriter which reverted the changed made in the PR of the new version (https://github.com/spring-projects/spring-batch/pull/3827/commits/3acbaaa73dbaed3ea5e5e92c53b75780c50c86b6) and it could give us the good result but not sure if it is required to do a flush explicitly which could cause us any issues of losing data to Kafka broker down the line.

public class NoWaitKafkaItemWriter<K, T> extends KafkaItemWriter<K, T> {
    private static final Logger LOGGER = LogManager.getLogger(NoWaitKafkaItemWriter.class);

    @Override
    protected void writeKeyValue(K key, T value) {
        LOGGER.info("About to write key {} value {}", key, value);

        if (this.delete) {
            this.kafkaTemplate.sendDefault(key, null);
        } else {
            this.kafkaTemplate.sendDefault(key, value);
        }
    }

    @Override
    protected void flush() {
        // do nothing
        LOGGER.info("Do nothing in flush");
    }
}

@Bean
public KafkaItemWriter<String, MyKafkaObject> getKafkaItemWriter(
            KafkaTemplate<String, MyKafkaObject> kafkaProducerTemplate) {

    LOGGER.info("Creating KafkaItemWriter that doesn't wait");

    KafkaItemWriter writer = new NoWaitKafkaItemWriter();
    writer.setKafkaTemplate(kafkaProducerTemplate);
    writer.setItemKeyMapper(this.kafkaItemKeyMapper);

    return writer;
}

We also tried with the timeout in 0 millisecond but it wouldn't help much since it is still waiting for the flush completion.

@Bean
public KafkaItemWriter<String, MyKafkaObject> getKafkaItemWriter(
        KafkaTemplate<String, MyKafkaObject> kafkaProducerTemplate) {

    LOGGER.info("Creating KafkaItemWriter");

    return new KafkaItemWriterBuilder<String, MyKafkaObject>()
            .kafkaTemplate(kafkaProducerTemplate)
            .itemKeyMapper(this.kafkaItemKeyMapper)
            .timeout(0)
            .build();
}

We are wondering if there is any options that we could make the application running asynchronously as it was before that change?

Any guidance would be much appreciated.


问:
How to resolve Importing a file from blender in its exact apperance to unity?
I am wanting to create cards for unity, I'm using Blender to achieve this (this is what it looks like: (https://i.stack.imgur.com/s9ypU.png)). when I import through to unity, I get this: (https://i.stack.imgur.com/fNUPz.png)

now I am aware that I have hidden a cube, though that cube was used as a boolean for one of the other shapes.

I find that even if I move the cube object in unity that there are different results (https://i.stack.imgur.com/TCm8W.png). Is there a way to have the import be the exact same from blender with having the selected object hidden?


问:
Workflow variable is being ignored
I have a project that I would like to deploy to my server by first uploading it to the home directory, extracting and then copying it to the /srv. I wanted the following structure in /home:

```<code>site/
    /releases
    /artifacts
admin/
    /releases
    /artifacts
</code>```

And this structure in /srv:

```<code>databases/
site/
admin/
</code>```

I made this workflow file  which sets a workflow variable (APP) - for which I intend to toggle to site or admin, with the following contents:

```<code>
on:
  push:
    branches:
      - main

env:
  APP: admin

jobs:
  create-deployment-artifacts:
    name: Create Deployment Artifacts
    runs-on: ubuntu-latest

    outputs:
      deployment-matrix: ${{ steps.export-deployment-matrix.outputs.deployment-matrix }}

    steps:
      - uses: actions/checkout@v2

      - name: Compile CSS and Javascript
        run:
          npm install
          npm run prod

      - name: Configure PHP 8.1
        uses: shivammathur/setup-php@master
        with:
          php-version: 8.1
          extensions: mbstring, ctype, fileinfo, openssl, json, tokenizer, xml

      - name: Install Composer Dependencies
        run: composer install --no-dev --no-interaction --prefer-dist

      - name: Create Deployment Artifacts
        env:
          GITHUB_SHA: ${{ github.sha }}
        run: tar -czf "${GITHUB_SHA}".tar.gz --exclude=*.git --exclude=node_modules *

      - name: Store Artifact for Distribution
        uses: actions/upload-artifact@v2
        with:
          name: app-build
          path: ${{ github.sha }}.tar.gz

      - name: Export Deployment Matrix
        id: export-deployment-matrix
        run: |
          JSON="$(cat ./deployment-matrix.json)"
          JSON="${JSON//'%'/'%25'}"
          JSON="${JSON//$'\n'/'%0A'}"
          JSON="${JSON//$'\r'/'%0D'}"
          echo "::set-output name=deployment-matrix::$JSON"

  prepare-release-on-servers:
    name: "${{ matrix.server.name }}: Prepare Release"
    runs-on: ubuntu-latest
    needs: create-deployment-artifacts
    strategy:
      matrix:
        server: ${{ fromJson(needs.create-deployment-artifacts.outputs.deployment-matrix) }}

    steps:
      - uses: actions/download-artifact@v2
        with:
          name: app-build

      - name: Upload
        uses: appleboy/scp-action@master
        with:
          host: ${{ matrix.server.ip }}
          username: ${{ matrix.server.username }}
          key: ${{ secrets.SSH_KEY }}
          port: ${{ matrix.server.port }}
          source: ${{ github.sha }}.tar.gz
          target: "$HOME/$APP/artifacts"

      - name: Extract Archive and Create Directories
        uses: appleboy/ssh-action@master
        env:
          GITHUB_SHA: ${{ github.sha }}
        with:
          host: ${{ matrix.server.ip }}
          username: ${{ matrix.server.username }}
          key: ${{ secrets.SSH_KEY }}
          port: ${{ matrix.server.port }}
          envs: GITHUB_SHA
          script: |
            echo $APP
            mkdir -p "$HOME/$APP/releases/${GITHUB_SHA}"
            tar xzf "$HOME/$APP/artifacts/${GITHUB_SHA}.tar.gz" -C "$HOME/$APP/releases/${GITHUB_SHA}"
            chmod -R 0777 $HOME/$APP/releases/${GITHUB_SHA}/storage
            sudo rm -rf /srv/$APP/*
            sudo cp -a $HOME/$APP/releases/${GITHUB_SHA}/. /srv/$APP/

  activate-release:
    name: "${{ matrix.server.name }}: Activate release"
    runs-on: ubuntu-latest
    needs: [ create-deployment-artifacts, prepare-release-on-servers]
    strategy:
      matrix:
        server: ${{ fromJson(needs.create-deployment-artifacts.outputs.deployment-matrix) }}
    steps:
      - name: Activate release
        uses: appleboy/ssh-action@master
        env:
          APP: /srv/$APP
          LARAVEL_ENV: ${{ secrets.LARAVEL_ENV }}
        with:
          host: ${{ matrix.server.ip }}
          username: ${{ matrix.server.username }}
          key: ${{ secrets.SSH_KEY }}
          port: ${{ matrix.server.port }}
          envs: APP,LARAVEL_ENV
          script: |
            printf "%s" "$LARAVEL_ENV" > "${APP}/.env"
            sudo chown -R www-data ${APP}/storage
            sudo chown -R www-data ${APP}/public
            sudo chmod -R 777 ${APP}/storage
            sudo chmod -R 775 ${APP}/public
            sudo service php8.1-fpm reload
</code>```

I already tried everything to interpolate the content of the said variable in my scripts blocks (using $APP or ${APP}), but I don't know why it's being ignored. And so I get all the contents of the projects being dumped directly in /srv/ and not inside the directory site or admin. The same is true for releases and artifacts directories.

I read here the one should add _PATH to the end of a variable that refers to the filesystem, but changing it yields the same results. What am I doing wrong?

Title: Workflow variable is being ignored

Body:
I have a project that I would like to deploy to my server by first uploading it to the home directory, extracting and then copying it to the /srv. I wanted the following structure in /home:

site/
    /releases
    /artifacts
admin/
    /releases
    /artifacts

And this structure in /srv:

databases/
site/
admin/

I made this workflow file  which sets a workflow variable (APP) - for which I intend to toggle to site or admin, with the following contents:

on:
  push:
    branches:
      - main

env:
  APP: admin

jobs:
  create-deployment-artifacts:
    name: Create Deployment Artifacts
    runs-on: ubuntu-latest

    outputs:
      deployment-matrix: ${{ steps.export-deployment-matrix.outputs.deployment-matrix }}

    steps:
      - uses: actions/checkout@v2

      - name: Compile CSS and Javascript
        run:
          npm install
          npm run prod

      - name: Configure PHP 8.1
        uses: shivammathur/setup-php@master
        with:
          php-version: 8.1
          extensions: mbstring, ctype, fileinfo, openssl, json, tokenizer, xml

      - name: Install Composer Dependencies
        run: composer install --no-dev --no-interaction --prefer-dist

      - name: Create Deployment Artifacts
        env:
          GITHUB_SHA: ${{ github.sha }}
        run: tar -czf "${GITHUB_SHA}".tar.gz --exclude=*.git --exclude=node_modules *

      - name: Store Artifact for Distribution
        uses: actions/upload-artifact@v2
        with:
          name: app-build
          path: ${{ github.sha }}.tar.gz

      - name: Export Deployment Matrix
        id: export-deployment-matrix
        run: |
          JSON="$(cat ./deployment-matrix.json)"
          JSON="${JSON//'%'/'%25'}"
          JSON="${JSON//$'\n'/'%0A'}"
          JSON="${JSON//$'\r'/'%0D'}"
          echo "::set-output name=deployment-matrix::$JSON"

  prepare-release-on-servers:
    name: "${{ matrix.server.name }}: Prepare Release"
    runs-on: ubuntu-latest
    needs: create-deployment-artifacts
    strategy:
      matrix:
        server: ${{ fromJson(needs.create-deployment-artifacts.outputs.deployment-matrix) }}

    steps:
      - uses: actions/download-artifact@v2
        with:
          name: app-build

      - name: Upload
        uses: appleboy/scp-action@master
        with:
          host: ${{ matrix.server.ip }}
          username: ${{ matrix.server.username }}
          key: ${{ secrets.SSH_KEY }}
          port: ${{ matrix.server.port }}
          source: ${{ github.sha }}.tar.gz
          target: "$HOME/$APP/artifacts"

      - name: Extract Archive and Create Directories
        uses: appleboy/ssh-action@master
        env:
          GITHUB_SHA: ${{ github.sha }}
        with:
          host: ${{ matrix.server.ip }}
          username: ${{ matrix.server.username }}
          key: ${{ secrets.SSH_KEY }}
          port: ${{ matrix.server.port }}
          envs: GITHUB_SHA
          script: |
            echo $APP
            mkdir -p "$HOME/$APP/releases/${GITHUB_SHA}"
            tar xzf "$HOME/$APP/artifacts/${GITHUB_SHA}.tar.gz" -C "$HOME/$APP/releases/${GITHUB_SHA}"
            chmod -R 0777 $HOME/$APP/releases/${GITHUB_SHA}/storage
            sudo rm -rf /srv/$APP/*
            sudo cp -a $HOME/$APP/releases/${GITHUB_SHA}/. /srv/$APP/

  activate-release:
    name: "${{ matrix.server.name }}: Activate release"
    runs-on: ubuntu-latest
    needs: [ create-deployment-artifacts, prepare-release-on-servers]
    strategy:
      matrix:
        server: ${{ fromJson(needs.create-deployment-artifacts.outputs.deployment-matrix) }}
    steps:
      - name: Activate release
        uses: appleboy/ssh-action@master
        env:
          APP: /srv/$APP
          LARAVEL_ENV: ${{ secrets.LARAVEL_ENV }}
        with:
          host: ${{ matrix.server.ip }}
          username: ${{ matrix.server.username }}
          key: ${{ secrets.SSH_KEY }}
          port: ${{ matrix.server.port }}
          envs: APP,LARAVEL_ENV
          script: |
            printf "%s" "$LARAVEL_ENV" > "${APP}/.env"
            sudo chown -R www-data ${APP}/storage
            sudo chown -R www-data ${APP}/public
            sudo chmod -R 777 ${APP}/storage
            sudo chmod -R 775 ${APP}/public
            sudo service php8.1-fpm reload

I already tried everything to interpolate the content of the said variable in my scripts blocks (using $APP or ${APP}), but I don't know why it's being ignored. And so I get all the contents of the projects being dumped directly in /srv/ and not inside the directory site or admin. The same is true for releases and artifacts directories.

I read here the one should add _PATH to the end of a variable that refers to the filesystem, but changing it yields the same results. What am I doing wrong?


问:
ERROR Cannot read properties of undefined (reading 'hook') VueJS, Nuxt, Npx
I have downloaded and setup the an existing old code on my laptop and did npm install to install the necessary packages and did npm audit fix --force to solve the vulnerabilities. When i do npm run start it gives error

```<code>Error: Cannot find module 'C:\Work\Xampp\htdocs\folder-name\node_modules\nuxt\bin\nuxt.js'
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:956:15)
    at Function.Module._load (node:internal/modules/cjs/loader:804:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}
</code>```

when i run npm run dev it tells to run npx nuxi dev or other commands using npx nuxi ---

now when i run npx nuxi dev it gives the below error

```<code>ERROR  Cannot start nuxt:  Cannot read properties of undefined (reading 'hook')                                                                           18:25:30

  at nuxtBootstrapVue (node_modules\bootstrap-vue\nuxt\index.js:34:13)
  at installModule (/C:/Work/Xampp/htdocs/folder-name/node_modules/@nuxt/kit/dist/index.mjs:416:9)
  at async initNuxt (/C:/Work/Xampp/htdocs/folder-name/node_modules/nuxt/dist/index.mjs:1825:7)
  at async load (/C:/Work/Xampp/htdocs/folder-name/node_modules/nuxi/dist/chunks/dev.mjs:6779:9)
  at async Object.invoke (/C:/Work/Xampp/htdocs/folder-name/node_modules/nuxi/dist/chunks/dev.mjs:6840:5)
  at async _main (/C:/Work/Xampp/htdocs/folder-name/node_modules/nuxi/dist/cli.mjs:50:20)
</code>```

facing ERROR  Cannot start nuxt:  Cannot read properties of undefined (reading 'hook') when trying to run command npx nuxi dev, i have tried to delete and reinstall node modules as well

Body:
I have downloaded and setup the an existing old code on my laptop and did npm install to install the necessary packages and did npm audit fix --force to solve the vulnerabilities. When i do npm run start it gives error

Error: Cannot find module 'C:\Work\Xampp\htdocs\folder-name\node_modules\nuxt\bin\nuxt.js'
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:956:15)
    at Function.Module._load (node:internal/modules/cjs/loader:804:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}

when i run npm run dev it tells to run npx nuxi dev or other commands using npx nuxi ---

now when i run npx nuxi dev it gives the below error

ERROR  Cannot start nuxt:  Cannot read properties of undefined (reading 'hook')                                                                           18:25:30

  at nuxtBootstrapVue (node_modules\bootstrap-vue\nuxt\index.js:34:13)
  at installModule (/C:/Work/Xampp/htdocs/folder-name/node_modules/@nuxt/kit/dist/index.mjs:416:9)
  at async initNuxt (/C:/Work/Xampp/htdocs/folder-name/node_modules/nuxt/dist/index.mjs:1825:7)
  at async load (/C:/Work/Xampp/htdocs/folder-name/node_modules/nuxi/dist/chunks/dev.mjs:6779:9)
  at async Object.invoke (/C:/Work/Xampp/htdocs/folder-name/node_modules/nuxi/dist/chunks/dev.mjs:6840:5)
  at async _main (/C:/Work/Xampp/htdocs/folder-name/node_modules/nuxi/dist/cli.mjs:50:20)

facing ERROR  Cannot start nuxt:  Cannot read properties of undefined (reading 'hook') when trying to run command npx nuxi dev, i have tried to delete and reinstall node modules as well


问:
Change parameter of one object in array based on user's choice in React
I'm trying to write a simple app that will simulate a hand in blackjack (previous question here that will let the user decide if they want to get 1 or 11 points if they get an ace.
Now, because I have an array of cards where I set the values of the cards (for example:

```<code>export const deckArray = [
    {
      suits: "Heart",
      card: "A",
      color: "red",
      index: "1",
      unicode: "",
      value: 0
    },
    {
      suits: "Heart",
      card: "2",
      color: "red",
      index: "2",
      unicode: "",
      value: 2
    },
    {
      suits: "Heart",
      card: "3",
      color: "red",
      index: "3",
      unicode: "",
      value: 3
    }]
</code>```

and so on, I need to change the value of the ace that is being received by the user.

I used the code from the previous answer like so:

```<code>import {useState, useEffect, Fragment} from 'react'
import Card from '../components/Card';
import Total from '../components/Total';
import Popup from '../components/Popup'
import AceSetterModal from '../components/AceSetterModal';
import {shuffle} from '../hooks/shuffleCards'
import {deckArray} from '../utils/data'

export default function Home(){
    const startHandSize = 2
    const lowAce = 1
    const highAce = 11
    const goal = 21

    const [starterDeck, setStarterDeck] = useState(shuffle(deckArray))
    const [howManyDealt, setHowManyDealt] = useState(startHandSize)
    const [triggerPopup, setButtonPopup] = useState(false)

    const [checker,setChecker] = useState(startHandSize);
    const [isStarted, setIsStarted] = useState(false)
    const [aceToSet, setAceToSet] = useState(null)

    const deal = () => {
        setHowManyDealt(startHandSize)
        setStarterDeck(shuffle(deckArray))
        setChecker(0)
        //setTotal(0)
    }

    if(isStarted){
        deal()
    }

    const hit = () => !bust && setHowManyDealt(prev => prev + 1)

    const usersCards = starterDeck.slice(-howManyDealt)

    var total = usersCards.reduce((a, e) => a + e.value, 0);

    const bust = total > 21;

    const handleAceSet = value => {
        console.log("handleAceSet called")
        total += value
        setStarterDeck(starterDeck => {
            const i = starterDeck.findIndex(e => e.card === aceToSet.card)
            return [
                ...starterDeck.slice(0, i),
                {...aceToSet, value},
                ...starterDeck.slice(i + 1)
            ]
        })
        console.log(starterDeck)
        setAceToSet(null)
    }

    return(
        <div>
        {aceToSet ?
          <AceSetterModal
          handleSetLow={() => handleAceSet(lowAce)}
          handleSetHigh={() => handleAceSet(highAce)}/> :
          <Fragment>
          <button onClick={deal}>DEAL</button>
            <button disabled={bust} onClick={hit}>HIT</button>
            <button disabled={bust}>STAND</button>
            <Total total={total} usersCards={usersCards}/>

        {usersCards.map(card => (
            <Card key={card.index}
                handleAceSet={() => setAceToSet(card)}
                card={card}
            />
        ))}
          </Fragment>}
        </div>
    )
}
</code>```

With the code below, I can get the index of the ace, but it is still not updating the ace, and, more importantly, the total. I also tried just adding the chosen value to the total, but it is not updating on the screen.

Body:
I'm trying to write a simple app that will simulate a hand in blackjack (previous question here that will let the user decide if they want to get 1 or 11 points if they get an ace.
Now, because I have an array of cards where I set the values of the cards (for example:

export const deckArray = [
    {
      suits: "Heart",
      card: "A",
      color: "red",
      index: "1",
      unicode: "",
      value: 0
    },
    {
      suits: "Heart",
      card: "2",
      color: "red",
      index: "2",
      unicode: "",
      value: 2
    },
    {
      suits: "Heart",
      card: "3",
      color: "red",
      index: "3",
      unicode: "",
      value: 3
    }]

and so on, I need to change the value of the ace that is being received by the user.

I used the code from the previous answer like so:

import {useState, useEffect, Fragment} from 'react'
import Card from '../components/Card';
import Total from '../components/Total';
import Popup from '../components/Popup'
import AceSetterModal from '../components/AceSetterModal';
import {shuffle} from '../hooks/shuffleCards'
import {deckArray} from '../utils/data'

export default function Home(){
    const startHandSize = 2
    const lowAce = 1
    const highAce = 11
    const goal = 21

    const [starterDeck, setStarterDeck] = useState(shuffle(deckArray))
    const [howManyDealt, setHowManyDealt] = useState(startHandSize)
    const [triggerPopup, setButtonPopup] = useState(false)

    const [checker,setChecker] = useState(startHandSize);
    const [isStarted, setIsStarted] = useState(false)
    const [aceToSet, setAceToSet] = useState(null)

    const deal = () => {
        setHowManyDealt(startHandSize)
        setStarterDeck(shuffle(deckArray))
        setChecker(0)
        //setTotal(0)
    }

    if(isStarted){
        deal()
    }

    const hit = () => !bust && setHowManyDealt(prev => prev + 1)

    const usersCards = starterDeck.slice(-howManyDealt)

    var total = usersCards.reduce((a, e) => a + e.value, 0);

    const bust = total > 21;

    const handleAceSet = value => {
        console.log("handleAceSet called")
        total += value
        setStarterDeck(starterDeck => {
            const i = starterDeck.findIndex(e => e.card === aceToSet.card)
            return [
                ...starterDeck.slice(0, i),
                {...aceToSet, value},
                ...starterDeck.slice(i + 1)
            ]
        })
        console.log(starterDeck)
        setAceToSet(null)
    }

    return(

        {aceToSet ?
          <AceSetterModal
          handleSetLow={() => handleAceSet(lowAce)}
          handleSetHigh={() => handleAceSet(highAce)}/> :
          <Fragment>
          <button onClick={deal}>DEAL</button>
            <button disabled={bust} onClick={hit}>HIT</button>
            <button disabled={bust}>STAND</button>
            <Total total={total} usersCards={usersCards}/>

        {usersCards.map(card => (
            <Card key={card.index}
                handleAceSet={() => setAceToSet(card)}
                card={card}
            />
        ))}
          </Fragment>}

    )
}

With the code below, I can get the index of the ace, but it is still not updating the ace, and, more importantly, the total. I also tried just adding the chosen value to the total, but it is not updating on the screen.


问:
test with jset fails if the component includes react-quill in nextjs app
I'm trying to test my next app with jest and react-testing-library, the test works fine until i add react-quill it give me those errers:
" Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.
Check the render method of ForwardRef(LoadableComponent)."
"Error: Uncaught [Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object."

I'm importing react-quill with dynamic import and use it inside form uses react-form-hook like this:

import FormItemInner from "../../ui/reusable/customForm/FormItemInner"
import React, { FC, useState, useEffect } from 'react';
import dynamic from 'next/dynamic';
import { Controller } from "react-hook-form";
import { Form } from "react-bootstrap";
import ReportAttachment from "./ReportAttachment";
import { ValidationMessage } from "../../ui/reusable/Reusable";

const QuillNoSSRWrapper: any = dynamic(import('react-quill'), {
    ssr: false,
    loading: () =>
Loading ...
,
})

const ProofOfConcept: FC<{ getFiles: any, register: any, errors: any, control: any, translate: any, authTranslate: any }> = ({ getFiles, register, errors, control, translate, authTranslate }) => {
    const [loaded, setLoaded] = useState(false);

    useEffect(() => {
        setLoaded(true)
    }, [])
    return (

            <FormItemInner title={translate("impactTitle")} required description={translate('reportImpactDescription')}>
                <Form.Control
                    className="mb-4 gray_input"
                    id="inputReportImpact"
                    data-testid="inputReportImpact"
                    type="name"
                    {...register("impact", {
                        required: true,
                    })}
                />
                {errors?.impact?.type === "required" && (
                    <ValidationMessage
                        message={authTranslate("RequiredField")}
                    />

                )}
            </FormItemInner>
            <FormItemInner title={translate("summaryTitle")} required description={translate('reportSummaryDescription')}>
                <Controller
                    name="summary"
                    control={control}
                    render={({ field: { onChange, value }, }) => (
                        <QuillNoSSRWrapper className="wrapperClassName mb-4" theme="snow" value={value} onChange={onChange} />
                    )}
                />
            </FormItemInner>
            <FormItemInner title={translate("recommendationTitle")} required description={translate('reportRecommendationDescription')}>
                <Controller
                    name="recommendation"
                    control={control}
                    render={({ field: { onChange, value } }) => (
                        <QuillNoSSRWrapper className="wrapperClassName mb-4" theme="snow" value={value} onChange={onChange} />

                    )}
                />
            </FormItemInner>

            <FormItemInner title={translate("attachmentTitle")} description={translate('reportAttachmentDescription')}>
                <ReportAttachment getFiles={getFiles} translate={translate} />
            </FormItemInner>

    )

}

export default ProofOfConcept```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```


问:
Spring cloud API gateway unexpectedly finishes TCP connections for WebSocket clients after 30 seconds
I have developed a Spring cloud API gateway and a WebSocket-based notification project which runs behind the API-Gateway. Here are the Yaml configurations of the API-Gateway:

spring:
  main:
    allow-bean-definition-overriding: true
    web-application-type: reactive
  security:
    oauth2:
      client:
        registration:
          login-client:
            provider: uaa
            client-id: ${CLIENT_ID}
            client-secret: "*******"
            authorization-grant-type: authorization_code
            redirect-uri: "${BACKEND_ROOT_ADDRESS}/login/oauth2/code/{registrationId}"
        provider:
          uaa:
            authorization-uri: ${AUTH_SERVER_DOMAIN}/cas/oauth2.0/authorize
            token-uri: ${AUTH_SERVICE_INTERNAL_ADDRESS}/cas/oauth2.0/accessToken
            user-info-uri: ${AUTH_SERVICE_INTERNAL_ADDRESS}/cas/oauth2.0/profile
            user-name-attribute: id
            user-info-authentication-method: form
  cloud:
    gateway:
      globalcors:
        add-to-simple-url-handler-mapping: true
      default-filters:
        - TokenRelay=
        - RequestHashing=SHA-256
      routes:
        - id: notification
          uri: lb://NOTIFICATION
          predicates:
            - Path=/notification/**
          filters:
            - RewritePath=/notification(?<segment>/?.*), $\{segment}
          metadata:
            - response-timeout: 300000000
            - connect-timeout: 300000000
eureka:
  client:
    serviceUrl:
      defaultZone: http://discovery-service/eureka
```
<p>When I connect to the notification service directly, without using API-Gateway, the connection remains active. Here is a sample URL I use for connecting to my service:</p>
```ws://my-company/notification/openConnection?the_client_id=42
```
<p>However, when I use API-Gateway, it closes the connection after 30 seconds. Here is the log of my notification service that confirms the WebSocket connection is closed by receiving the TCP finish packet.</p>
```[p-nio-80-exec-2] o.a.t.websocket.server.WsFrameServer     : wsFrameServer.onDataAvailable
[p-nio-80-exec-2] o.a.tomcat.util.net.SocketWrapperBase    : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@67f46c3f:org.apache.tomcat.util.net.NioChannel@2a4e5a44:java.nio.channels.SocketChannel[connected local=/172.28.0.11:80 remote=/172.28.0.12:56006]], Read from buffer: [0]
[p-nio-80-exec-2] org.apache.tomcat.util.net.NioEndpoint   : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@67f46c3f:org.apache.tomcat.util.net.NioChannel@2a4e5a44:java.nio.channels.SocketChannel[connected local=/172.28.0.11:80 remote=/172.28.0.12:56006]], Read direct from socket: [6]
[p-nio-80-exec-2] o.a.t.websocket.server.WsFrameServer     : Read [6] bytes into input buffer ready for processing
[p-nio-80-exec-2] o.a.t.websocket.server.WsFrameServer     : WebSocket frame received. fin [true], rsv [0], OpCode [8], payload length [0]
[p-nio-80-exec-2] s.w.s.h.LoggingWebSocketHandlerDecorator : StandardWebSocketSession[id=0df41ae3-ffc2-4d90-723c-88dacbfe11a3, uri=ws://da3a67eb76df/openConnection?party=42] closed with CloseStatus[code=1000, reason=null]
after close: 0df41ae3-ffc2-4d90-723c-88dacbfe11a3
[p-nio-80-exec-2] o.apache.tomcat.util.threads.LimitLatch  : Counting down[http-nio-80-exec-2] latch=1
[p-nio-80-exec-2] org.apache.tomcat.util.net.NioEndpoint   : Calling [org.apache.tomcat.util.net.NioEndpoint@11fe2371].closeSocket([org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@67f46c3f:org.apache.tomcat.util.net.NioChannel@2a4e5a44:java.nio.channels.SocketChannel[connected local=/172.28.0.11:80 remote=/172.28.0.12:56006]])
```
<p>And here is the log of API-Gateway at the moment it closes the websocket:</p>
```
[or-http-epoll-7] r.n.http.client.HttpClientOperations     : [c66f9ad0-1, L:/172.28.0.12:58846 - R:1bc0b9f7e00d/172.28.0.11:80] Cancelling Websocket inbound. Closing Websocket
[or-http-epoll-7] r.n.resources.PooledConnectionProvider   : [c66f9ad0-1, L:/172.28.0.12:58846 ! R:1bc0b9f7e00d/172.28.0.11:80] Channel closed, now: 0 active connections, 0 inactive connections and 0 pending acquire requests.
[or-http-epoll-7] reactor.netty.ReactorNetty               : [c66f9ad0-1, L:/172.28.0.12:58846 ! R:1bc0b9f7e00d/172.28.0.11:80] Non Removed handler: reactor.left.httpAggregator, context: null, pipeline: DefaultChannelPipeline{(ws-decoder = io.netty.handler.codec.http.websocketx.WebSocket13FrameDecoder), (ws-encoder = io.netty.handler.codec.http.websocketx.WebSocket13FrameEncoder), (reactor.left.wsFrameAggregator = io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator), (reactor.right.reactiveBridge = reactor.netty.channel.ChannelOperationsHandler)}
[or-http-epoll-7] r.n.http.server.HttpServerOperations     : [b51c2362-1, L:/172.28.0.12:80 ! R:/172.28.0.1:33582] Cancelling Websocket inbound. Closing Websocket
[or-http-epoll-7] r.n.r.DefaultPooledConnectionProvider    : [c66f9ad0, L:/172.28.0.12:58846 ! R:1bc0b9f7e00d/172.28.0.11:80] onStateChange(ws{uri=/openConnection?party=42, connection=PooledConnection{channel=[id: 0xc66f9ad0, L:/172.28.0.12:58846 ! R:1bc0b9f7e00d/172.28.0.11:80]}}, [response_completed])
[or-http-epoll-7] r.n.r.DefaultPooledConnectionProvider    : [c66f9ad0, L:/172.28.0.12:58846 ! R:1bc0b9f7e00d/172.28.0.11:80] onStateChange(ws{uri=/openConnection?party=42, connection=PooledConnection{channel=[id: 0xc66f9ad0, L:/172.28.0.12:58846 ! R:1bc0b9f7e00d/172.28.0.11:80]}}, [disconnecting])

```

Body:
I have developed a Spring cloud API gateway and a WebSocket-based notification project which runs behind the API-Gateway. Here are the Yaml configurations of the API-Gateway:

spring:
  main:
    allow-bean-definition-overriding: true
    web-application-type: reactive
  security:
    oauth2:
      client:
        registration:
          login-client:
            provider: uaa
            client-id: ${CLIENT_ID}
            client-secret: "*******"
            authorization-grant-type: authorization_code
            redirect-uri: "${BACKEND_ROOT_ADDRESS}/login/oauth2/code/{registrationId}"
        provider:
          uaa:
            authorization-uri: ${AUTH_SERVER_DOMAIN}/cas/oauth2.0/authorize
            token-uri: ${AUTH_SERVICE_INTERNAL_ADDRESS}/cas/oauth2.0/accessToken
            user-info-uri: ${AUTH_SERVICE_INTERNAL_ADDRESS}/cas/oauth2.0/profile
            user-name-attribute: id
            user-info-authentication-method: form
  cloud:
    gateway:
      globalcors:
        add-to-simple-url-handler-mapping: true
      default-filters:
        - TokenRelay=
        - RequestHashing=SHA-256
      routes:
        - id: notification
          uri: lb://NOTIFICATION
          predicates:
            - Path=/notification/**
          filters:
            - RewritePath=/notification(?<segment>/?.*), $\{segment}
          metadata:
            - response-timeout: 300000000
            - connect-timeout: 300000000
eureka:
  client:
    serviceUrl:
      defaultZone: http://discovery-service/eureka

When I connect to the notification service directly, without using API-Gateway, the connection remains active. Here is a sample URL I use for connecting to my service:

ws://my-company/notification/openConnection?the_client_id=42

However, when I use API-Gateway, it closes the connection after 30 seconds. Here is the log of my notification service that confirms the WebSocket connection is closed by receiving the TCP finish packet.

[p-nio-80-exec-2] o.a.t.websocket.server.WsFrameServer     : wsFrameServer.onDataAvailable
[p-nio-80-exec-2] o.a.tomcat.util.net.SocketWrapperBase    : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@67f46c3f:org.apache.tomcat.util.net.NioChannel@2a4e5a44:java.nio.channels.SocketChannel[connected local=/172.28.0.11:80 remote=/172.28.0.12:56006]], Read from buffer: [0]
[p-nio-80-exec-2] org.apache.tomcat.util.net.NioEndpoint   : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@67f46c3f:org.apache.tomcat.util.net.NioChannel@2a4e5a44:java.nio.channels.SocketChannel[connected local=/172.28.0.11:80 remote=/172.28.0.12:56006]], Read direct from socket: [6]
[p-nio-80-exec-2] o.a.t.websocket.server.WsFrameServer     : Read [6] bytes into input buffer ready for processing
[p-nio-80-exec-2] o.a.t.websocket.server.WsFrameServer     : WebSocket frame received. fin [true], rsv [0], OpCode [8], payload length [0]
[p-nio-80-exec-2] s.w.s.h.LoggingWebSocketHandlerDecorator : StandardWebSocketSession[id=0df41ae3-ffc2-4d90-723c-88dacbfe11a3, uri=ws://da3a67eb76df/openConnection?party=42] closed with CloseStatus[code=1000, reason=null]
after close: 0df41ae3-ffc2-4d90-723c-88dacbfe11a3
[p-nio-80-exec-2] o.apache.tomcat.util.threads.LimitLatch  : Counting down[http-nio-80-exec-2] latch=1
[p-nio-80-exec-2] org.apache.tomcat.util.net.NioEndpoint   : Calling [org.apache.tomcat.util.net.NioEndpoint@11fe2371].closeSocket([org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@67f46c3f:org.apache.tomcat.util.net.NioChannel@2a4e5a44:java.nio.channels.SocketChannel[connected local=/172.28.0.11:80 remote=/172.28.0.12:56006]])

And here is the log of API-Gateway at the moment it closes the websocket:

[or-http-epoll-7] r.n.http.client.HttpClientOperations     : [c66f9ad0-1, L:/172.28.0.12:58846 - R:1bc0b9f7e00d/172.28.0.11:80] Cancelling Websocket inbound. Closing Websocket
[or-http-epoll-7] r.n.resources.PooledConnectionProvider   : [c66f9ad0-1, L:/172.28.0.12:58846 ! R:1bc0b9f7e00d/172.28.0.11:80] Channel closed, now: 0 active connections, 0 inactive connections and 0 pending acquire requests.
[or-http-epoll-7] reactor.netty.ReactorNetty               : [c66f9ad0-1, L:/172.28.0.12:58846 ! R:1bc0b9f7e00d/172.28.0.11:80] Non Removed handler: reactor.left.httpAggregator, context: null, pipeline: DefaultChannelPipeline{(ws-decoder = io.netty.handler.codec.http.websocketx.WebSocket13FrameDecoder), (ws-encoder = io.netty.handler.codec.http.websocketx.WebSocket13FrameEncoder), (reactor.left.wsFrameAggregator = io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator), (reactor.right.reactiveBridge = reactor.netty.channel.ChannelOperationsHandler)}
[or-http-epoll-7] r.n.http.server.HttpServerOperations     : [b51c2362-1, L:/172.28.0.12:80 ! R:/172.28.0.1:33582] Cancelling Websocket inbound. Closing Websocket
[or-http-epoll-7] r.n.r.DefaultPooledConnectionProvider    : [c66f9ad0, L:/172.28.0.12:58846 ! R:1bc0b9f7e00d/172.28.0.11:80] onStateChange(ws{uri=/openConnection?party=42, connection=PooledConnection{channel=[id: 0xc66f9ad0, L:/172.28.0.12:58846 ! R:1bc0b9f7e00d/172.28.0.11:80]}}, [response_completed])
[or-http-epoll-7] r.n.r.DefaultPooledConnectionProvider    : [c66f9ad0, L:/172.28.0.12:58846 ! R:1bc0b9f7e00d/172.28.0.11:80] onStateChange(ws{uri=/openConnection?party=42, connection=PooledConnection{channel=[id: 0xc66f9ad0, L:/172.28.0.12:58846 ! R:1bc0b9f7e00d/172.28.0.11:80]}}, [disconnecting])


问:
Termux. How to fix: Unable to locate package airmon-ng
After full update/upgrade, tried to change repo... I saw different guide but still nothing...

THIS'S WHAT I DO

~ $ pkg install airmon-ng

Checking availability of current mirror:

[*] https://termux.librehat.com/apt/termux-main: ok

Reading package lists... Done

Building dependency tree... Done

Reading state information... Done

E: Unable to locate package airmon-ng


Title: [lua]how can i decode a message using lua

Body:
local Letter = ':X/6E}1v@4j1T/9d{5K-7F?9L/2M*6U-8Y-7S?7x{4e/3p/7l#7j{2T@8Y#2f-0a@6E{3w!5x*0O!1M@3O$8R*8E!1S{2f!0M8:t*3c!0l}3A-1m*9F7P*1s#7M#7b@0s!2P{2U#3m@7E*4W*2R#1n3P@4R#7D$7r}5H{9w$9 *6D*3D-4L!5n6Q!9s$7k-5w#5Y5a1:u$6u#9M6z}9 *8s#5v?8g-4V/5Y?1B/3S*5O$4a8d/1n#4C@1P/8w{9I@3c$9C?6d/5 1Z*1q1j}6e?4Q{2n-1 {8w*6:k}9J$4v6F{4F#4H$1L}7E{7e*3Y$8Z{5z#3O{3 ?7D5 $8h?6A*2F!3N!2g$5O!6q1I#0P9Q5D?0J$0R#6H$3E}4r$4z#5G1F-9J?1D?5d@2K@4e*6D}3f-2Z{6L#7l8b#1:f#9R{5Z{1X2q}1w-6c*8O/0M$0w?3t/7x-7b@2t@9r?0F}4w@4G{7E*6Y$8o?1J$6T*5t-4W!7u@2W@0G!7m$8T/5d/8e$1p!0e!7p?2H#5G8x/7H$9z}5Q{8F/5D5T{3n!5c#1y/7X-7W-6C$7E?3k/7O6:U#6U/1s@1Q#3d$6X/9r}7E-9H3d-3G*2m{0z4f$5K5f-7c@7O*2e#8R@8v$2x/0o*5D@0x}9 }8a!7U*8q0X8R}3w*0M?9P!6B!4l{3B}0y*4r?7Y{4:R@0c}6w5B$9a?8J-9J{6I@9R$1m#6Y?1c/5q?2f}2J*9O$8w#0M!1l-6v*4 #1Z}3y!6 {2m$3w$1A/1P}7N!8i4g-0D#8w$2i8P?8:I!0l*5C#8A/6 ?5v?1a/7m/5y#1m-7s!5z?2q$3M*7I/6I#7m!9A-7J@9v#9R$1K5T?8v?5e/4i{1Q-4w?8N?4Y{8 !0T!8w/7M!7f@8Q}8j#9r#6b-7i#7i!5I!8l@5R/1j@6q*6:s?5t}9U!7W/9j*0u-7a-3n{1p{0c-5 {9Y!3Z@6d}8u!8o}2p0Z#2B!5X?3v!8q{9w{7k#0q@0K/1L!7m?3x*7h{2M#9p/1a$2C}4g!2a/1O$5w*9a!3z?4l/8F{2B?4y$1:C*2S$1i/5Y4o$1M3 }7m!2d@8g#5i$5s2I#1i-5s}6L-2g5 2h?4V{7P@8N#2l0V-1j/7W$5T@8M$9 @0f{4Q$6n!0I/9r-3w*5e8Q6H0B{8o!9S$6'

local Symbols = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz $!#@{}-/*? '

its a message from a challenge and I would like to know what is written, bare in mind I don't know how to code

would be much appreciated if explained too!


问:
Sick LIDAR TIM561 : Python test API won't load sick_scan_shared_lib.dll
I'm trying to use a TIM561 Sick lidar with the Python test API :
https://github.com/SICKAG/sick_scan_xd/blob/master/doc/sick_scan_api/sick_scan_api.md#complete-usage-example-in-python

I'm having trouble loading the sick_scan_shared_lib.dll library. When I try to import it, I get the following error message:

# Load sick_scan_library
if os.name == 'nt': # Load windows dll
        sick_scan_library = SickScanApiLoadLibrary(["build/Debug/", "build_win64/Debug/", "src/build/Debug/", "src/build_win64/Debug/", "src/sick_scan_xd/build/Debug/", "src/sick_scan_xd/build_win64/Debug/", "./", "../"], "sick_scan_shared_lib.dll")

api_handle = SickScanApiCreate(sick_scan_library)
```
```Could not find module 'sick_scan_shared_lib.dll' (or one of its dependencies). Try using the full path with constructor syntax.
```

I've checked that the library is located in a directory that is in my system's PATH environment variable, and I've also tried specifying the full path to the library when importing it. However, I'm still getting the same error message.

What could be causing this issue, and how can I fix it?
Thank you in advance for your answers.

Body:
I'm trying to use a TIM561 Sick lidar with the Python test API :
https://github.com/SICKAG/sick_scan_xd/blob/master/doc/sick_scan_api/sick_scan_api.md#complete-usage-example-in-python

I'm having trouble loading the sick_scan_shared_lib.dll library. When I try to import it, I get the following error message:

# Load sick_scan_library
if os.name == 'nt': # Load windows dll
        sick_scan_library = SickScanApiLoadLibrary(["build/Debug/", "build_win64/Debug/", "src/build/Debug/", "src/build_win64/Debug/", "src/sick_scan_xd/build/Debug/", "src/sick_scan_xd/build_win64/Debug/", "./", "../"], "sick_scan_shared_lib.dll")

api_handle = SickScanApiCreate(sick_scan_library)

Could not find module 'sick_scan_shared_lib.dll' (or one of its dependencies). Try using the full path with constructor syntax.

I've checked that the library is located in a directory that is in my system's PATH environment variable, and I've also tried specifying the full path to the library when importing it. However, I'm still getting the same error message.

What could be causing this issue, and how can I fix it?
Thank you in advance for your answers.


问:
How to compare data values in AWS Quicksight
I have a requirement to build a visual which shows the changes in the data between 2 dates (compare data within a same table). For example, consider the below data :

Execution Date
Server Name
Metallic Rating
Deployment Status

31 Dec 2022
Server1
Gold
Deployed

31 Dec 2022
Server2
Silver
Not Deployed

03 Jan 2023
Server1
Platinum
Deployed

03 Jan 2023
Server3
Gold
Deployed

if you notice, between two dates, following has changed:

Metallic rating of Server 1 changed from Gold to Platinum

for the execution date of 03 Jan 2023, server2 record has been removed and a new record for server3 has been added

Using quicksight, I want to build a visual which shows, between two execution dates, the metallic rating for server1 changed

I tried this using different visuals but not able to find out how to do it


问:
Verify if yup field has a value that exists in a predefined array of values
I am using Yup for form data validation along with Formik.

This is a yup schema for one of my react forms.

```<code>const values=['All','Subscribers']

export const newsLetterSchema = yup.object().shape({
  audience: yup.string(),
  subject: yup.string().min(1).required("Required"),
  body: yup.string().min(1).max(1000).required("Required"),
});
</code>```

By this schema i want the "audience" field to have a value which is already pre-defined in the array of values by me and any other value should throw me an error.

The audience field should be either audience='All' or audience ='Subscribers' and if audience='any other value' then it should give me error.
I tried to find a solution but could not find any. Thank you in advance.

Body:
I am using Yup for form data validation along with Formik.

This is a yup schema for one of my react forms.

const values=['All','Subscribers']

export const newsLetterSchema = yup.object().shape({
  audience: yup.string(),
  subject: yup.string().min(1).required("Required"),
  body: yup.string().min(1).max(1000).required("Required"),
});

By this schema i want the "audience" field to have a value which is already pre-defined in the array of values by me and any other value should throw me an error.

The audience field should be either audience='All' or audience ='Subscribers' and if audience='any other value' then it should give me error.
I tried to find a solution but could not find any. Thank you in advance.


问:
How to call a reusable function that uses yewdux store within use_effect hook?
I want to make a reusable function that uses yewdux store, and call it in use_effect of another component. As per hook rule, hooks can only be used in top level of a function / hook

```<code>use crate::components::accounts::account_store::PhraseStore;
use yew::prelude::*;
use yewdux::prelude::*;

#[derive(Clone)]
pub struct SignTx {
    pub sign_tx: (),
}

#[hook]
pub fn use_sign_tx<T>(tx: T) -> SignTx
{
    let (store, _) = use_store::<PhraseStore>();

    let sign_tx = {
        wasm_bindgen_futures::spawn_local(async move {
            // code logic using store
            // api calls
        });
    };
    SignTx { sign_tx }
}
</code>```

Now I want to call sign_tx function in another component?

```<code>#[function_component(TransactionFromHooks)]
pub fn transaction() -> Html {
    let first_load = use_state(|| true);
    use_effect(move || {
        if *first_load {
            wasm_bindgen_futures::spawn_local(async move {

               // Call the sign_tx function here
               // let sign = use_sign_tx(tx);

            });
            first_load.set(false);
        }
        || {}
    });

    html! {
        <h1>{"Transaction"}</h1>
    }
}
</code>```

How to do it?

Body:
I want to make a reusable function that uses yewdux store, and call it in use_effect of another component. As per hook rule, hooks can only be used in top level of a function / hook

use crate::components::accounts::account_store::PhraseStore;
use yew::prelude::*;
use yewdux::prelude::*;

#[derive(Clone)]
pub struct SignTx {
    pub sign_tx: (),
}

#[hook]
pub fn use_sign_tx<T>(tx: T) -> SignTx
{
    let (store, _) = use_store::<PhraseStore>();

    let sign_tx = {
        wasm_bindgen_futures::spawn_local(async move {
            // code logic using store
            // api calls
        });
    };
    SignTx { sign_tx }
}

Now I want to call sign_tx function in another component?

#[function_component(TransactionFromHooks)]
pub fn transaction() -> Html {
    let first_load = use_state(|| true);
    use_effect(move || {
        if *first_load {
            wasm_bindgen_futures::spawn_local(async move {

               // Call the sign_tx function here
               // let sign = use_sign_tx(tx);

            });
            first_load.set(false);
        }
        || {}
    });

    html! {

{"Transaction"}

    }
}

How to do it?


问:
how this useTransition hook works in reactjs?
I'm just playing around with the reactjs useTransition hook and trying to understand how to use it. I've gone through almost everything on the doc. The example given there is working as expected.

I'm trying to use this hook in a different context, but this time it doesn't seem to be working. Here's my code below:

import { useState, useTransition } from "react";

function Component() {
  const [slow, setSlow] = useState(0);
  const [fast, setFast] = useState(0);

  const [isPending, startTransition] = useTransition();

  const handleSlowClick = () => {
    startTransition(() => {
      let starting = performance.now();
      while (performance.now() - starting < 5000) {
        // do nothing for 5sec
      }
      setSlow((prev) => prev + 1);
    });
  };

  const handleFastClick = () => {
    setFast((prev) => prev + 1);
  };

  return (
    <>
      <button onClick={handleSlowClick}>slow - {slow}</button>
      <button onClick={handleFastClick}>fast - {fast}</button>
    </>
  );
}

export default Component;```

react is supposed to give everything inside the startTransition function less priority when updating states. But this isn't the case in the browser. When I click the slow button, it makes the whole web page unresponsive for 5 sec

I wonder what's happening under the hood?

[NOTE: I'm trying it inside my current NextJS project, in case it matters]

Body:
I'm just playing around with the reactjs useTransition hook and trying to understand how to use it. I've gone through almost everything on the doc. The example given there is working as expected.

I'm trying to use this hook in a different context, but this time it doesn't seem to be working. Here's my code below:

import { useState, useTransition } from "react";

function Component() {
  const [slow, setSlow] = useState(0);
  const [fast, setFast] = useState(0);

  const [isPending, startTransition] = useTransition();

  const handleSlowClick = () => {
    startTransition(() => {
      let starting = performance.now();
      while (performance.now() - starting < 5000) {
        // do nothing for 5sec
      }
      setSlow((prev) => prev + 1);
    });
  };

  const handleFastClick = () => {
    setFast((prev) => prev + 1);
  };

  return (
    <>
      <button onClick={handleSlowClick}>slow - {slow}</button>
      <button onClick={handleFastClick}>fast - {fast}</button>
    </>
  );
}

export default Component;

react is supposed to give everything inside the startTransition function less priority when updating states. But this isn't the case in the browser. When I click the slow button, it makes the whole web page unresponsive for 5 sec

I wonder what's happening under the hood?

[NOTE: I'm trying it inside my current NextJS project, in case it matters]


问:
Attribute Error: type object 'TFLiteConverter' has no attribute 'from keras model'
I am  working with tensorflow and android.

I am trying to run the following lines of code:

```<code>`tflite_model =tf.keras.models.load_model('ECEO_model.h5')
converter = tf.lite.TFLiteConverter.from_keras_model(tflite_model)
tflite_save = converter.convert()
open("ECEO_model.tflite", "wb").write(tflite_save)`
</code>```

and getting this error:

```<code>`WARNING:tensorflow:From C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\ops\init_ops.py:97: calling GlorotUniform.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
WARNING:tensorflow:From C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\ops\init_ops.py:97: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)
<ipython-input-17-9ec4d030e614> in <module>
      1 tflite_model =tf.keras.models.load_model('ECEO_model.h5')
      2 #tf.keras.models.save_model(model,keras_file)
----> 3 converter = tf.lite.TFLiteConverter.from_keras_model(tflite_model)
      4 tflite_save = converter.convert()
      5 open("ECEO_model.tflite", "wb").write(tflite_save)

AttributeError: type object 'TFLiteConverter' has no attribute 'from_keras_model'`

</code>```

I tried with many possibilities as found from google search, but not able to debug it. Can anyone please help me debug this as I am new to tensorflow and android?
I would be very thankful to you for this.

Body:
I am  working with tensorflow and android.

I am trying to run the following lines of code:

`tflite_model =tf.keras.models.load_model('ECEO_model.h5')
converter = tf.lite.TFLiteConverter.from_keras_model(tflite_model)
tflite_save = converter.convert()
open("ECEO_model.tflite", "wb").write(tflite_save)`

and getting this error:

`WARNING:tensorflow:From C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\ops\init_ops.py:97: calling GlorotUniform.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
WARNING:tensorflow:From C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\ops\init_ops.py:97: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)
<ipython-input-17-9ec4d030e614> in <module>
      1 tflite_model =tf.keras.models.load_model('ECEO_model.h5')
      2 #tf.keras.models.save_model(model,keras_file)
----> 3 converter = tf.lite.TFLiteConverter.from_keras_model(tflite_model)
      4 tflite_save = converter.convert()
      5 open("ECEO_model.tflite", "wb").write(tflite_save)

AttributeError: type object 'TFLiteConverter' has no attribute 'from_keras_model'`

I tried with many possibilities as found from google search, but not able to debug it. Can anyone please help me debug this as I am new to tensorflow and android?
I would be very thankful to you for this.


问:
Pipelines with tag in DataOps/GitLab
I have a few jobs:
job_1,
job_2,
job_3,
job_5.

Job_1,job_2 and job_3 is triggered every hour. Which means that I have everyday 24 logs in DataOps per one job. I saw that in Dataops there is a search toolbar where can I search for "Tag name". Here is a question, Can I somehow add a tag to specific job for example job_1 will have tag JOB1 etc.?

Thanks for the help

Title: Pipelines with tag in DataOps/GitLab


问:
Why does the section slips under the other? CSS
the section #portfolio slips under the section #team-container when resizing the page to a smaller width

the website should show up like this:  https://content.codecademy.com/PRO/independent-practice-projects/flexbox-business-site/example-site/index.html#team

Despite that what would you do to make the code better?

HTML:

```<code><html><head>
    <title>VC Enterprise Portfolio</title>
    <link rel="stylesheet" href="stylesheet.css" type="text/css">
    <link rel="shortcut icon" href="/tiefes-lernen.png" type="image/x-icon">
    <link href="https://fonts.googleapis.com/css?family=Lexend+Mega" rel="stylesheet" type="text/css">
  </head>

  <body>
    <div class="header">
      <h1>The VC Experience</h1>
      <div class="navbar">
        <p><a href="#mission">Mission Statement</a></p>
        <p><a href="#portfolio">Portfolio</a></p>
        <p><a href="#team">Investment Team</a></p>
      </div>
    </div>

    <div class="main">

      <div class="mission">
        <div class="content">
          <h2>The VC Experience</h2>
          <h4>Our fund is committed to the furthering entrepreneurs in the mobility sector.</h4>
        </div>
      </div>

      <div id="portfolio">
        <div class="content">
          <h2>Our Mobility Portfolio</h2>
          <h4>Impacting diverse sectors of mobility to better the human experience and the world we inhabit</h4>
          <div class="companies">
            <div class="company">
              <img src="img URL">
              <span>AeroArgonauts</span>
            </div>
            <div class="company">
              <img src="img URL">
              <span>AutoBueno</span>
            </div>
            <div class="company">
              <img src="img URL">
              <span>LaneChatter</span>
            </div>
            <div class="company">
              <img src="img URL">
              <span>TigerTreads</span>
            </div>
            <div class="company">
              <img src="img URL">
              <span>ValetToday</span>
            </div>
          </div>
        </div>
      </div>

      <div id="team-container">
        <h2>Our Team</h2>
        <div class="team">
          <div class="teammate">
            <img src="img URL">
            <h3>Lisa Fischer</h3>
            <p>C.E.O. - Founder and Principal Investor</p>
          </div>
          <div class="teammate">
            <img src="img URL">
            <h3>Alex Lasker</h3>
            <p>Partner - Research & Development</p>
          </div>
          <div class="teammate">
            <img src="img URL">
            <h3>Omar Carlsen</h3>
            <p>Partner - Partnerships & Marketing</p>
          </div>
        </div>
      </div>

        <div class="contact">
          <h2>The VC Experience</h2>
          <h5>introduction@vcexperience.investors</h5>
          <h5>555-867-5309</h5>
        </div>

        <div class="copyright">
          <h5>copyright VC Enterprises 2020</h5>
        </div>

      </div>

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

CSS:

```<code>/*https://content.codecademy.com/PRO/independent-practice-projects/flexbox-business-site/img/skyscrapers.jpg*/
html {
    display: block;
}

body {
    font-family: "Lexend Mega", sans-serif;
}

h1 {
    display: block;
    margin-top: .75em;
    font-size: 2.75rem;
}

.navbar {
    display: flex;
    justify-content: space-around;
    font-size: 1.375rem;
    margin: 0 10%;
}

.navbar p{
    padding: 0 15px 10px 30px;
    display: inline-block;
}

a {
    color: black;
}

header {
    display: flex;
    flex-direction: column;
    align-items: center;
}

body {
    text-align: center;
}

.navbar {
    justify-content: space-around;
    margin: 0 10px;
    display: flex;
}

.mission {
    display: flex;
    background-image: img URL;
    width: auto;
    padding-top: 10px;
}

.content {
    display: block;
    width: 100%;
    height: 300px;
    position: relative;
    top: 80px;
    margin-bottom: 0;
}

h2, h4 {
    background-color: white;
    position: relative;
    font-size: 33px;
    margin: 0;
    padding: 10px;
}

h4 {
    font-size: 22px;
}

#portfolio {
    min-height: 500px;
    margin: auto;
    padding-top: 35px;
}

.company {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.company img {
    width: 200px;
    height: auto;
    padding: 10px;
    margin-left: auto;
    margin-right: auto;
}

span {
    min-width: 240px;
    padding: 5px;
    text-align: center;
    font-size: 22px;
    font-weight: bold;
}

.companies {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    align-items: center;
}

#team-container {
    position: relative;
    display: block;
}

#team-container h2 {
    margin: 0;
    padding: 5px;
    display: block;
}

.team {
    padding-top: 75px;
    justify-content: center;
    display: flex;
    flex-wrap: wrap;
    background-image: img URL;
}

.team img {
    padding: 10px;
    height : 300px;
    width: 200px;
}

.teammate {
    padding: 5px;
    color: white;
    flex-basis: 280px;
}
</code>```

Tried to make some paddings to top or bottom but it looks whacky. I also tried to inspect the original site but can't find the reason why.

Body:
the section #portfolio slips under the section #team-container when resizing the page to a smaller width

the website should show up like this:  https://content.codecademy.com/PRO/independent-practice-projects/flexbox-business-site/example-site/index.html#team

Despite that what would you do to make the code better?

HTML:

    <title>VC Enterprise Portfolio</title>
    <link rel="stylesheet" href="stylesheet.css" type="text/css">
    <link rel="shortcut icon" href="/tiefes-lernen.png" type="image/x-icon">
    <link href="https://fonts.googleapis.com/css?family=Lexend+Mega" rel="stylesheet" type="text/css">

The VC Experience

Mission Statement

Portfolio

Investment Team

The VC Experience

Our fund is committed to the furthering entrepreneurs in the mobility sector.

Our Mobility Portfolio

Impacting diverse sectors of mobility to better the human experience and the world we inhabit

              AeroArgonauts

              AutoBueno

              LaneChatter

              TigerTreads

              ValetToday

Our Team

Lisa Fischer

C.E.O. - Founder and Principal Investor

Alex Lasker

Partner - Research & Development

Omar Carlsen

Partner - Partnerships & Marketing

The VC Experience

introduction@vcexperience.investors

555-867-5309

copyright VC Enterprises 2020

CSS:

/*https://content.codecademy.com/PRO/independent-practice-projects/flexbox-business-site/img/skyscrapers.jpg*/
html {
    display: block;
}

body {
    font-family: "Lexend Mega", sans-serif;
}

h1 {
    display: block;
    margin-top: .75em;
    font-size: 2.75rem;
}

.navbar {
    display: flex;
    justify-content: space-around;
    font-size: 1.375rem;
    margin: 0 10%;
}

.navbar p{
    padding: 0 15px 10px 30px;
    display: inline-block;
}

a {
    color: black;
}

header {
    display: flex;
    flex-direction: column;
    align-items: center;
}

body {
    text-align: center;
}

.navbar {
    justify-content: space-around;
    margin: 0 10px;
    display: flex;
}

.mission {
    display: flex;
    background-image: img URL;
    width: auto;
    padding-top: 10px;
}

.content {
    display: block;
    width: 100%;
    height: 300px;
    position: relative;
    top: 80px;
    margin-bottom: 0;
}

h2, h4 {
    background-color: white;
    position: relative;
    font-size: 33px;
    margin: 0;
    padding: 10px;
}

h4 {
    font-size: 22px;
}

#portfolio {
    min-height: 500px;
    margin: auto;
    padding-top: 35px;
}

.company {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.company img {
    width: 200px;
    height: auto;
    padding: 10px;
    margin-left: auto;
    margin-right: auto;
}

span {
    min-width: 240px;
    padding: 5px;
    text-align: center;
    font-size: 22px;
    font-weight: bold;
}

.companies {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    align-items: center;
}

#team-container {
    position: relative;
    display: block;
}

#team-container h2 {
    margin: 0;
    padding: 5px;
    display: block;
}

.team {
    padding-top: 75px;
    justify-content: center;
    display: flex;
    flex-wrap: wrap;
    background-image: img URL;
}

.team img {
    padding: 10px;
    height : 300px;
    width: 200px;
}

.teammate {
    padding: 5px;
    color: white;
    flex-basis: 280px;
}

Tried to make some paddings to top or bottom but it looks whacky. I also tried to inspect the original site but can't find the reason why.


问:
how to trigger shell script after pulling docker image successfully
I want to run shell script(bash) when my ec2 pull docker image successfully.

Is there any way I can try?

I just found "docker events" command, but I don't know how to trigger script with this.


问:
Why Do I Get a Stack Overflow When Base Case Compares an Empty Array
I am working on understanding recursion. I wrote a function that returns the sum of an array.

If the if statement for the base case looks like this if (arr.length === 0), the function works. If it looks like this if (arr === []), I get a stack overflow. Why is that? Here is the full program.

```<code>
const getSum = function (arr){

    //the if statement in question
    if (arr.length === 0){
        return 0;
    }
    else{
        console.log(arr)
        return arr[0] + getSum(arr.slice(1));
    };

};
</code>```

Body:
I am working on understanding recursion. I wrote a function that returns the sum of an array.

If the if statement for the base case looks like this if (arr.length === 0), the function works. If it looks like this if (arr === []), I get a stack overflow. Why is that? Here is the full program.

const getSum = function (arr){

    //the if statement in question
    if (arr.length === 0){
        return 0;
    }
    else{
        console.log(arr)
        return arr[0] + getSum(arr.slice(1));
    };

};


问:
How to display a message even when the intercom messenger is closed?
Can someone please tell me how to activate or display this layer on the intercom messenger widget? I couldn't find anything from the messenger settings to do this.


问:
AWS MSK with confluent schema registry
Is it possible to use AWS MSK with confluent schema registry with docker instance? I dont need any Kafka connector or sink connector. Before publish want to use AVRO with confluent schema registry and deserialize the same during consumption. What are all the properties i need to set on confluent schema-registry docker? When i try to run i get this error java.lang.RuntimeException: No endpoints found for security protocol [PLAINTEXT]. Endpoints found in ZK. Any pointers are greatly appreciated.</p>

Title: AWS MSK with confluent schema registry


问:
Could not load file or assembly Blazored.LocalStorage on Kestrel server on Linux
Very strange problem.  Of course, I have been dealing with this error for decades and typically it means the DLL is missing or the wrong version.  However, I am stymied in this case, hopefully someone can help?

I have a Blazor web server, and built a Linux-target deployment.  It runs fine on the Windows development environment.
It has been running for about 9 months through several updates, no problem on the Linux deployed environment.  The latest update today, I built and deployed updated code to Linux, which involved zipping the published folder, sftp to the target machine, unzip, chmod +x to the executable, and attempting to start the service entry.  The DLL is definitely there in the deployment package, and is there when I unzip (running on Ubuntu 20.04 LTS), but when I start it up, I get the error:

```<code>Unhandled exception. System.IO.FileNotFoundException: Could not load file or assembly 'Blazored.LocalStorage, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3c577f5cf869402a'. The system cannot find the file specified.

File name: 'Blazored.LocalStorage, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3c577f5cf869402a'
Aborted (core dumped)
</code>```

If I do a strings Blazored.LocalStorage.dll | egrep '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' I do get 1.0.0.0, so I can't figure out why it is dumping.  Since it is complaining about that file, it is definitely in the assembly manifest.

All the files are there with same owner, same group, same permissions, this is the only DLL I am having a problem with.

The web server has been working for months, and only stopped working when I stopped it and tried to restart it.  The things I tried after getting the error are:

Reverting code back to previous version and start.

Running apt-get update / apt-get upgrade, and rebooting.

Exporting shell variables for .NET and Kestrel startup parameters, and starting in a shell (same error)

Installing on a different Linux box - this worked.  I added .NET environment variables, Kestrel config variables, unzipped the Linux publication, and voila, it worked fine.

What's the difference between the one box it has worked on for months, and the other one?  Nothing I can tell, just one - Ubuntu 20.04 (first box) and 22.04 (second box).  Same firewall config, etc.

Body:
Very strange problem.  Of course, I have been dealing with this error for decades and typically it means the DLL is missing or the wrong version.  However, I am stymied in this case, hopefully someone can help?

I have a Blazor web server, and built a Linux-target deployment.  It runs fine on the Windows development environment.
It has been running for about 9 months through several updates, no problem on the Linux deployed environment.  The latest update today, I built and deployed updated code to Linux, which involved zipping the published folder, sftp to the target machine, unzip, chmod +x to the executable, and attempting to start the service entry.  The DLL is definitely there in the deployment package, and is there when I unzip (running on Ubuntu 20.04 LTS), but when I start it up, I get the error:

Unhandled exception. System.IO.FileNotFoundException: Could not load file or assembly 'Blazored.LocalStorage, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3c577f5cf869402a'. The system cannot find the file specified.

File name: 'Blazored.LocalStorage, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3c577f5cf869402a'
Aborted (core dumped)

If I do a strings Blazored.LocalStorage.dll | egrep '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' I do get 1.0.0.0, so I can't figure out why it is dumping.  Since it is complaining about that file, it is definitely in the assembly manifest.

All the files are there with same owner, same group, same permissions, this is the only DLL I am having a problem with.

The web server has been working for months, and only stopped working when I stopped it and tried to restart it.  The things I tried after getting the error are:

Reverting code back to previous version and start.

Running apt-get update / apt-get upgrade, and rebooting.

Exporting shell variables for .NET and Kestrel startup parameters, and starting in a shell (same error)

Installing on a different Linux box - this worked.  I added .NET environment variables, Kestrel config variables, unzipped the Linux publication, and voila, it worked fine.

What's the difference between the one box it has worked on for months, and the other one?  Nothing I can tell, just one - Ubuntu 20.04 (first box) and 22.04 (second box).  Same firewall config, etc.


问:
PHPUnit feature tests pass locally but not in Github Actions
I have a set of tests that pass locally, but once I push to Github, the tests fail. The Github Action seems like a black box to me, and I'm unsure of even how to troubleshoot this. I'm using in-memory sqlite both locally and in my github action workflow.

I'm inserting some data for my tests, and at the beginning of these seeder classes, I'm temporarily disabling foreign keys to allow me to truncate the tables:

```<code>Schema::disableForeignKeyConstraints();
QuickbooksTransaction::truncate();
Schema::enableForeignKeyConstraints();
</code>```

Here's the start of my test class that's producing the errors:

```<code>class FindMatchesTest extends TestCase
{
    use RefreshDatabase, WithFaker;

    protected $user;
    protected $client;
    protected $location;
    protected $statement;

    public function setup(): void
    {
        parent::setUp();
        $this->setupFaker();
        $this->seed();
        $this->user = User::factory()->create();
        $this->client = Client::factory()->create();
        $this->location = Location::factory()->create();
        $this->statement = Statement::factory()->create();
        $this->seed(StatementTransactionSeeder::class); //truncates and populates a table
        $this->seed(TransactionSeeder::class); //truncates and populates a table

        $action = new FindMatches($this->statement, true);
        $action->handle();
    }
</code>```

this is the first of 3 tests that are failing. It doesn't matter which assertion I put first, they all fail:

```<code>  public function test_right_matching_invoice_nbr_produces_match()
    {
        $row = StatementTransaction::where('invoice_nbr', '999999654321')->first();
        $qbRow = Transaction::where('invoice_nbr', '888888654321')->first();

        $this->assertNotEmpty($row->transaction_id);
        $this->assertEquals(1, $row->has_partial_match);
        $this->assertEquals(0, $row->has_match);
        $this->assertEquals(0, $row->has_identified_match);
        $this->assertEquals($row->transaction_id, $qbRow->id);
        $this->assertGreaterThanOrEqual(Config::get('match_threshold'), $row->invoice_nbr_match_confidence);
    }
</code>```

If I leave the order that's above, I get Failed asserting that 7 matches expected 8.

If I switch the order up and put the next row first, I get Failed asserting that 1 matches expected 0.

It's almost like it's seeeing different data than what I'm seeing locally, but that doesn't seem possible if it's running it the same way as it is locally.

Could there be a difference in how PHPUnit would run locally and how it would run in Github actions? Is there a way to see the data it's seeing when it runs so I can begin to troubleshoot this?

Here is my Github Action config file:

```<code>name: LaravelTest

on:
  push:
    branches: [ test ]

jobs:
  laravel_tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@main
      - name: Copy .env
        run: php -r "file_exists('.env') || copy('.env.example', '.env');"
      - name: Install Dependencies
        run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress
      - name: Generate key
        run: php artisan key:generate
      - name: Directory Permissions
        run: chmod -R 777 storage bootstrap/cache
      - name: Create Database
        run: |
          mkdir -p database
          touch database/database.sqlite
      - name: Compile assets
        run: |
          npm install
          npm run production
      - name: Execute tests (Unit and Feature tests) via PHPUnit
        env:
          DB_CONNECTION: sqlite
          DB_DATABASE: database/database.sqlite
          CACHE_DRIVER: array
          SESSION_DRIVER: array
          QUEUE_DRIVER: sync
        run: vendor/bin/phpunit
  forge_deploy:
    runs-on: ubuntu-latest
    needs: laravel_tests
    steps:
      - name: Make Get Request
        uses: satak/webrequest-action@master
        with:
          url: ${{ secrets.TEST_DEPLOY_URL }}
          method: GET
</code>```

EDIT: adding the seeder classes. Both classes are close to identical, with just a bunch of insert statements to create the dummy records for testing.

```<code>class TransactionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Schema::disableForeignKeyConstraints();
        Transaction::truncate();
        Schema::enableForeignKeyConstraints();

       $id = Statement::first()->id;
       $inv = Helper::cleanInvoiceNumber('888888654321');
       $date = Carbon::now()->startOfMonth()->format('Y-m-d');

        DB::table('transactions')->insert([
            'statement_id' => $id,
            'transaction_type_id' => 1,
            'transaction_date' => $date,
            'invoice_nbr' => '888888654321',
            'invoice_nbr_clean' => $inv,
            'original_amount' => '16100',
            'balance' => '16100',
            'row_hash' =>  Helper::makeHash([
                $id,
                1,
                $inv,
                $date,
                '16100'
            ])
        ]);

//...more inserts like above...
}

</code>```
```<code>class StatementTransactionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Schema::disableForeignKeyConstraints();
        StatementTransaction::truncate();
        Schema::enableForeignKeyConstraints();

        $id = Statement::first()->id;
        $inv = Helper::cleanInvoiceNumber('999999654321');
        $date = Carbon::now()->startOfMonth()->format('Y-m-d');

        DB::table('statement_transactions')->insert([
            'statement_id' => $id,
            'transaction_type_id' => 1,
            'transaction_date' => $date,
            'invoice_nbr' => '999999654321',
            'invoice_nbr_clean' => $inv,
            'po_nbr' => 'Right 6 match',
            'original_amount' => '16100',
            'balance' => '16100',
            'row_hash' =>  Helper::makeHash([
                $id,
                1,
                $inv,
                $date,
                '16100'
            ])
        ]);

//...more inserts like above...
}

</code>```

Clarification requested in comment:

When I say switch the order, I just mean that the first assertion always fails in this test, regardless of the order of the assert statements. So this:

```<code> $this->assertNotEmpty($row->transaction_id);
 $this->assertEquals(1, $row->has_partial_match);
</code>```

or this:

```<code> $this->assertEquals(1, $row->has_partial_match);
 $this->assertNotEmpty($row->transaction_id);
</code>```

will both fail on the first assert statement it hits. This, combined with the error message it spits out, leads me to believe that the data isn't the same on the server as it is locally for some reason.

UPDATE

Based on feedback in the comments, I updated the line to get the statement with this: $id = Statement::orderBy('id', 'desc')->first()->id;

Now all the tests in this class are failing with the message:  You requested 1 items, but there are only 0 items available..

I have no idea what this means. Currently wading through google results.

UPDATE 2

Ok that was wrong. I think I incorrectly removed a line of code for a factory that wasn't needed in the test, but was a dependency for another factory.

I'm back at square one.

UPDATE 3

In an effort to not spend my entire life on this, I'm going back to the drawing board and eliminating the seeder classes and just inserting the records I need for the specific test inside the test itself. Hoping this resolves the issue so I don't have to jump off a cliff in despair.

Body:
I have a set of tests that pass locally, but once I push to Github, the tests fail. The Github Action seems like a black box to me, and I'm unsure of even how to troubleshoot this. I'm using in-memory sqlite both locally and in my github action workflow.

I'm inserting some data for my tests, and at the beginning of these seeder classes, I'm temporarily disabling foreign keys to allow me to truncate the tables:

Schema::disableForeignKeyConstraints();
QuickbooksTransaction::truncate();
Schema::enableForeignKeyConstraints();

Here's the start of my test class that's producing the errors:

class FindMatchesTest extends TestCase
{
    use RefreshDatabase, WithFaker;

    protected $user;
    protected $client;
    protected $location;
    protected $statement;

    public function setup(): void
    {
        parent::setUp();
        $this->setupFaker();
        $this->seed();
        $this->user = User::factory()->create();
        $this->client = Client::factory()->create();
        $this->location = Location::factory()->create();
        $this->statement = Statement::factory()->create();
        $this->seed(StatementTransactionSeeder::class); //truncates and populates a table
        $this->seed(TransactionSeeder::class); //truncates and populates a table

        $action = new FindMatches($this->statement, true);
        $action->handle();
    }

this is the first of 3 tests that are failing. It doesn't matter which assertion I put first, they all fail:

  public function test_right_matching_invoice_nbr_produces_match()
    {
        $row = StatementTransaction::where('invoice_nbr', '999999654321')->first();
        $qbRow = Transaction::where('invoice_nbr', '888888654321')->first();

        $this->assertNotEmpty($row->transaction_id);
        $this->assertEquals(1, $row->has_partial_match);
        $this->assertEquals(0, $row->has_match);
        $this->assertEquals(0, $row->has_identified_match);
        $this->assertEquals($row->transaction_id, $qbRow->id);
        $this->assertGreaterThanOrEqual(Config::get('match_threshold'), $row->invoice_nbr_match_confidence);
    }

If I leave the order that's above, I get Failed asserting that 7 matches expected 8.

If I switch the order up and put the next row first, I get Failed asserting that 1 matches expected 0.

It's almost like it's seeeing different data than what I'm seeing locally, but that doesn't seem possible if it's running it the same way as it is locally.

Could there be a difference in how PHPUnit would run locally and how it would run in Github actions? Is there a way to see the data it's seeing when it runs so I can begin to troubleshoot this?

Here is my Github Action config file:

name: LaravelTest

on:
  push:
    branches: [ test ]

jobs:
  laravel_tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@main
      - name: Copy .env
        run: php -r "file_exists('.env') || copy('.env.example', '.env');"
      - name: Install Dependencies
        run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress
      - name: Generate key
        run: php artisan key:generate
      - name: Directory Permissions
        run: chmod -R 777 storage bootstrap/cache
      - name: Create Database
        run: |
          mkdir -p database
          touch database/database.sqlite
      - name: Compile assets
        run: |
          npm install
          npm run production
      - name: Execute tests (Unit and Feature tests) via PHPUnit
        env:
          DB_CONNECTION: sqlite
          DB_DATABASE: database/database.sqlite
          CACHE_DRIVER: array
          SESSION_DRIVER: array
          QUEUE_DRIVER: sync
        run: vendor/bin/phpunit
  forge_deploy:
    runs-on: ubuntu-latest
    needs: laravel_tests
    steps:
      - name: Make Get Request
        uses: satak/webrequest-action@master
        with:
          url: ${{ secrets.TEST_DEPLOY_URL }}
          method: GET

EDIT: adding the seeder classes. Both classes are close to identical, with just a bunch of insert statements to create the dummy records for testing.

class TransactionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Schema::disableForeignKeyConstraints();
        Transaction::truncate();
        Schema::enableForeignKeyConstraints();

       $id = Statement::first()->id;
       $inv = Helper::cleanInvoiceNumber('888888654321');
       $date = Carbon::now()->startOfMonth()->format('Y-m-d');

        DB::table('transactions')->insert([
            'statement_id' => $id,
            'transaction_type_id' => 1,
            'transaction_date' => $date,
            'invoice_nbr' => '888888654321',
            'invoice_nbr_clean' => $inv,
            'original_amount' => '16100',
            'balance' => '16100',
            'row_hash' =>  Helper::makeHash([
                $id,
                1,
                $inv,
                $date,
                '16100'
            ])
        ]);

//...more inserts like above...
}

class StatementTransactionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Schema::disableForeignKeyConstraints();
        StatementTransaction::truncate();
        Schema::enableForeignKeyConstraints();

        $id = Statement::first()->id;
        $inv = Helper::cleanInvoiceNumber('999999654321');
        $date = Carbon::now()->startOfMonth()->format('Y-m-d');

        DB::table('statement_transactions')->insert([
            'statement_id' => $id,
            'transaction_type_id' => 1,
            'transaction_date' => $date,
            'invoice_nbr' => '999999654321',
            'invoice_nbr_clean' => $inv,
            'po_nbr' => 'Right 6 match',
            'original_amount' => '16100',
            'balance' => '16100',
            'row_hash' =>  Helper::makeHash([
                $id,
                1,
                $inv,
                $date,
                '16100'
            ])
        ]);

//...more inserts like above...
}

Clarification requested in comment:

When I say switch the order, I just mean that the first assertion always fails in this test, regardless of the order of the assert statements. So this:

 $this->assertNotEmpty($row->transaction_id);
 $this->assertEquals(1, $row->has_partial_match);

or this:

 $this->assertEquals(1, $row->has_partial_match);
 $this->assertNotEmpty($row->transaction_id);

will both fail on the first assert statement it hits. This, combined with the error message it spits out, leads me to believe that the data isn't the same on the server as it is locally for some reason.

UPDATE

Based on feedback in the comments, I updated the line to get the statement with this: $id = Statement::orderBy('id', 'desc')->first()->id;

Now all the tests in this class are failing with the message:  You requested 1 items, but there are only 0 items available..

I have no idea what this means. Currently wading through google results.

UPDATE 2

Ok that was wrong. I think I incorrectly removed a line of code for a factory that wasn't needed in the test, but was a dependency for another factory.

I'm back at square one.

UPDATE 3

In an effort to not spend my entire life on this, I'm going back to the drawing board and eliminating the seeder classes and just inserting the records I need for the specific test inside the test itself. Hoping this resolves the issue so I don't have to jump off a cliff in despair.


问:
Why FFmpeg is consuming more and more bandwith when restreaming a YouTube HLS stream?
I've been creating a bot in Python which allows to copy one YouTube livestream and stream it to another channel using the HLS protocol.

This is the command I'm using in Python to start the FFmpeg process:

```<code>m3u8_url = streamlink.streams(stream_url)['1080p'].url
ffmpeg_process = Popen(
    ["ffmpeg", "-i", m3u8_url, "-c", "copy","-ignore_io_errors", "1", "-f", "hls", "-http_persistent", "1", '-attempt_recovery', '1',
    '-method', 'POST', '-hls_time', '1', '-hls_playlist_type', 'event', '-g', '5', '-reconnect_at_eof', '1',
    'https://a.upload.youtube.com/http_upload_hls?cid=' + stream_key + '&copy=0&file=stream.m3u8'])
</code>```

I'm using streamlink to extract the 1080p m3u8 playlist of a given livestream and then using "-c", "copy"I'm just passing the raw HLS stream back to YouTube servers.

The problem is that at first FFmpeg is using around 1.5 Mbps for both upload and download, but as the stream progresses the used bandwidth per second grows substantially. After 5 hours FFmpeg uses 5 Mbps of upload and about half of that  in download, but it just keeps on growing. It's gotten to a point where my VPS was blocked as after a few days it was using > 1500 Mbps of bandwidth (with 10 active streams).

The only thing that comes to my mind is that for some reason with every .ts segment, FFmpeg is trying to send all the previous ones as well. It might be worth mentioning that YouTube Studio is complaining that the incoming stream bandwith is too low and it should be 4.5 Mbps.

I've tried changing the "-method" from PUT to POST, which helped reducing the download bandwidth, but didn't change anything in regards to upload.

Body:
I've been creating a bot in Python which allows to copy one YouTube livestream and stream it to another channel using the HLS protocol.

This is the command I'm using in Python to start the FFmpeg process:

m3u8_url = streamlink.streams(stream_url)['1080p'].url
ffmpeg_process = Popen(
    ["ffmpeg", "-i", m3u8_url, "-c", "copy","-ignore_io_errors", "1", "-f", "hls", "-http_persistent", "1", '-attempt_recovery', '1',
    '-method', 'POST', '-hls_time', '1', '-hls_playlist_type', 'event', '-g', '5', '-reconnect_at_eof', '1',
    'https://a.upload.youtube.com/http_upload_hls?cid=' + stream_key + '&copy=0&file=stream.m3u8'])

I'm using streamlink to extract the 1080p m3u8 playlist of a given livestream and then using "-c", "copy"I'm just passing the raw HLS stream back to YouTube servers.

The problem is that at first FFmpeg is using around 1.5 Mbps for both upload and download, but as the stream progresses the used bandwidth per second grows substantially. After 5 hours FFmpeg uses 5 Mbps of upload and about half of that  in download, but it just keeps on growing. It's gotten to a point where my VPS was blocked as after a few days it was using > 1500 Mbps of bandwidth (with 10 active streams).

The only thing that comes to my mind is that for some reason with every .ts segment, FFmpeg is trying to send all the previous ones as well. It might be worth mentioning that YouTube Studio is complaining that the incoming stream bandwith is too low and it should be 4.5 Mbps.

I've tried changing the "-method" from PUT to POST, which helped reducing the download bandwidth, but didn't change anything in regards to upload.


问:
ERROR [TypeError: Network request failed] Expo App
I would like to test my expo app on my iphone. Already is running but after few seconds on my app, I got this error  ERROR  [TypeError: Network request failed]

I can't see my server information and I don't understand why.
My front and my back are connected because I can see this res.json in my terminal :

```<code>app.get("/", (req, res) => {
  console.log("Welcome");
  res.json({message: "Bienvenue sur mon serveur !"});
});
</code>```

But when I'm using the /firstPage (example) routes, I don't received any informations of this routes in by front.
My server and my device are running with the same wifi.
My app and my server on the port 3000.

So if someone could explain me how can I received the informations from my server ( for example the data from some sql requests )
Thanks you in advance !

Body:
I would like to test my expo app on my iphone. Already is running but after few seconds on my app, I got this error  ERROR  [TypeError: Network request failed]

I can't see my server information and I don't understand why.
My front and my back are connected because I can see this res.json in my terminal :

app.get("/", (req, res) => {
  console.log("Welcome");
  res.json({message: "Bienvenue sur mon serveur !"});
});

But when I'm using the /firstPage (example) routes, I don't received any informations of this routes in by front.
My server and my device are running with the same wifi.
My app and my server on the port 3000.

So if someone could explain me how can I received the informations from my server ( for example the data from some sql requests )
Thanks you in advance !


问:
how to do docx to pdf conversion using python library without subprocess in linux?
I tried this docx2pdf library in windows.but in linux I'm facing the error as

```<code>NotImplementedError: docx2pdf is not implemented for linux as it requires Microsoft Word to be installed
</code>```

any alternative library to convert docx to pdf using python without using subprocess(terminal)

and also I have tried this code (.doc to pdf using python)  not worked for me
I got this error on linux (ImportError: cannot import name COMError in python)

I tried

```<code>from docx2pdf import convert

convert("myDoc.docx")
</code>```

I got

```<code>File /opt/conda/lib/python3.10/site-packages/docx2pdf/__init__.py:108, in convert(input_path, output_path, keep_active)
    106     return windows(paths, keep_active)
    107 else:
--> 108     raise NotImplementedError(
    109         "docx2pdf is not implemented for linux as it requires Microsoft Word to be installed"
    110     )

NotImplementedError: docx2pdf is not implemented for linux as it requires Microsoft Word to be installed
</code>```

Body:
I tried this docx2pdf library in windows.but in linux I'm facing the error as

NotImplementedError: docx2pdf is not implemented for linux as it requires Microsoft Word to be installed

any alternative library to convert docx to pdf using python without using subprocess(terminal)

and also I have tried this code (.doc to pdf using python)  not worked for me
I got this error on linux (ImportError: cannot import name COMError in python)

I tried

from docx2pdf import convert

convert("myDoc.docx")

I got

File /opt/conda/lib/python3.10/site-packages/docx2pdf/__init__.py:108, in convert(input_path, output_path, keep_active)
    106     return windows(paths, keep_active)
    107 else:
--> 108     raise NotImplementedError(
    109         "docx2pdf is not implemented for linux as it requires Microsoft Word to be installed"
    110     )

NotImplementedError: docx2pdf is not implemented for linux as it requires Microsoft Word to be installed