问:
How to select single cell when there are multiple editable cells on Ant Design Vue 3?
Right now I need some way to make all cells on my table editable. I know I'm able to do it like in this example. But it's just one cell per row, I'm wondering how I can achieve this for all cells on in a single row with its own v-model. I've been searching for examples but couldn't find any. Does anyone know how can I do it?

I'm able to edit all of them but when I click it, it opens the edition mode for all cells when in fact I want to open just the one I clicked.

This is how my code looks like now:

```<code><template>
     <a-table bordered :data-source="dataSource" :columns="columns" :pagination="false">
        <template #title>
            <div class="formLayoutCrud">
                <p>{{this.title}}</p>
                <input-multiple-button :name="'buttonOptions'" :value="'percentage'" :options="this.buttonOptions"> </input-multiple-button>
            </div>
        </template>
        <template v-for="col in this.editableCells" #[col]="{ text, record }" :key="col">
            <div class="editable-cell">
                <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
                    <a-input v-model:value="editableData[record.key][col]" @pressEnter="save(record.key)" />
                    <check-outlined class="editable-cell-icon-check" @click="save(record.key)" />
                </div>
                <div v-else class="editable-cell-text-wrapper">
                    {{ text || ' ' }}
                    <edit-outlined class="editable-cell-icon" @click="edit(record.key, col)" />
                </div>
            </div>
        </template>
    </a-table>
</template>
<script>
import { reactive, ref } from 'vue';
import { CheckOutlined, EditOutlined } from '@ant-design/icons-vue';

import InputMultipleButton from '@/components/crudForm/InputMultipleButton.vue';

export default {
    name: 'TableEditable',
    props: {
        title: String,
        buttonOptions: Array,
        editableCells: Array,
        dataSrc: Array
    },
    components: {
        CheckOutlined,
        EditOutlined,
        InputMultipleButton
    },
    setup() {
        const columns = [
            {
                title: 'Mon',
                dataIndex: 'monday',
                slots: {
                    customRender: 'monday',
                },
            },
            {
                title: 'Tue',
                dataIndex: 'tuesday',
                slots: {
                    customRender: 'tuesday',
                },
            },
            {
                title: 'Wed',
                dataIndex: 'wednesday',
                slots: {
                    customRender: 'wednesday',
                },
            },
            {
                title: 'Thr',
                dataIndex: 'thursday',
                slots: {
                    customRender: 'thursday',
                },
            },
            {
                title: 'Fri',
                dataIndex: 'friday',
                slots: {
                    customRender: 'friday',
                },
            },
            {
                title: 'Sat',
                dataIndex: 'saturday',
                slots: {
                    customRender: 'saturday',
                },
            },
            {
                title: 'Sun',
                dataIndex: 'sunday',
                slots: {
                    customRender: 'sunday',
                },
            },
        ];
        const dataSource = ref([
            {
                key: '0',
                monday: '0',
                tuesday: '0',
                wednesday: '0',
                thursday: '0',
                friday: '0',
                saturday: '0',
                sunday: '0'

            }
            ]);
        const editableData = reactive({});

        const edit = (key, teste) => {
            console.log(teste)
            editableData[key] = JSON.parse(JSON.stringify(dataSource.value.filter(item => key === item.key)[0]));
        };

        const save = key => {
            console.log(key)
            Object.assign(dataSource.value.filter(item => key === item.key)[0], editableData[key]);
            delete editableData[key];
        };
        return {
            columns,
            dataSource,
            editableData,
            edit,
            save
        };
  },
}
</script>
</code>```

Thanks in advance!

答:
TL;DR:

use composite key, like editableData[row + '|' + column] to target row and column for editing.

The example (that I assume you intended to link) has a couple shortcomings.

If you'll pardon the "pedantics", I'll explain what the example does first. I've kept the important bits here:

// in template:  @click="edit(record.key)"

// in setup:
const editableData = reactive({});

function edit(key){
  editableData[key] = JSON.parse(
    JSON.stringify(dataSource.value.filter((item) => key === item.key)[0])
  );
}
```
<p><code>editableData</code> is a reactive object that will store two parameters the key and the copy of the entire object. for example assigning <code>editableData[2] = {...}</code> will allow the <code>save</code> method to replace the 3rd item (key) to the altered copy. One issue with that is that all the fields in the same row are tied together. So if you edit two, but only save one, they will both be updated. The second issue is that there is no way to target which specific value in the object you are making editable. Additionally, relying on the copy of an entire object, could cause some issues if the underlying data is mutable through some other path.</p>
<p>There are couple different ways to solve for this issue, but I'll just share, what I believe to be, the simplest, which is to use a composite key.</p>
<p>instead of <code>editableData[key] = {a copy of row object}</code> you can use <code>editableData[rowKey + "|"+ colKey] = 12</code> (12 being example of the value when user hits edit)</p>
<p>it would look something like this:</p>
<p>template:</p>
<pre class="lang-html prettyprint-override"><code><template
  v-for="col in editableCells"
  #[col]="{ column, text, record }"
  :key="col"
>
  <div class="editable-cell">
    <div
      v-if="editableData[record.key + '|' + column.key]"
      class="editable-cell-input-wrapper"
    >
      <a-input
        v-model:value="editableData[record.key + '|' + column.key]"
        @pressEnter="save(record.key, column.key)"
      />
      <check-outlined
        class="editable-cell-icon-check"
        @click="save(record.key, column.key)"
      />
    </div>
    <div v-else class="editable-cell-text-wrapper">
      {{ text || ' ' }}
      <edit-outlined
        class="editable-cell-icon"
        @click="edit(record.key, column.key)"
      />
    </div>
  </div>
</template>
</code>```

script:

const edit = (row, column) => {
  editableData[row + '|' + column] = dataSource.value.filter(
    (item) => row === item.key
  )[0][column];
};

const save = (row, column) => {
  dataSource.value[row][column] = editableData[row + '|' + column];
  delete editableData[row + '|' + column];
};
```

I'm using the pipe character as a separation character to concatenate the two strings, you can omit that and just use row + column which should resolve to a string and not cause any issues. This can be handy though if you have a potential for conflicting keys (such as both being indexes)

Body:
Right now I need some way to make all cells on my table editable. I know I'm able to do it like in this example. But it's just one cell per row, I'm wondering how I can achieve this for all cells on in a single row with its own v-model. I've been searching for examples but couldn't find any. Does anyone know how can I do it?

I'm able to edit all of them but when I click it, it opens the edition mode for all cells when in fact I want to open just the one I clicked.

This is how my code looks like now:

<template>

        <template #title>

{{this.title}}

                <input-multiple-button :name="'buttonOptions'" :value="'percentage'" :options="this.buttonOptions"> </input-multiple-button>

        </template>
        <template v-for="col in this.editableCells" #[col]="{ text, record }" :key="col">

                    <check-outlined class="editable-cell-icon-check" @click="save(record.key)" />

                    {{ text || ' ' }}
                    <edit-outlined class="editable-cell-icon" @click="edit(record.key, col)" />

        </template>

</template>

Thanks in advance!

Body:
TL;DR:

use composite key, like editableData[row + '|' + column] to target row and column for editing.

The example (that I assume you intended to link) has a couple shortcomings.

If you'll pardon the "pedantics", I'll explain what the example does first. I've kept the important bits here:

// in template:  @click="edit(record.key)"

// in setup:
const editableData = reactive({});

function edit(key){
  editableData[key] = JSON.parse(
    JSON.stringify(dataSource.value.filter((item) => key === item.key)[0])
  );
}

editableData is a reactive object that will store two parameters the key and the copy of the entire object. for example assigning editableData[2] = {...} will allow the save method to replace the 3rd item (key) to the altered copy. One issue with that is that all the fields in the same row are tied together. So if you edit two, but only save one, they will both be updated. The second issue is that there is no way to target which specific value in the object you are making editable. Additionally, relying on the copy of an entire object, could cause some issues if the underlying data is mutable through some other path.

There are couple different ways to solve for this issue, but I'll just share, what I believe to be, the simplest, which is to use a composite key.

instead of editableData[key] = {a copy of row object} you can use editableData[rowKey + "|"+ colKey] = 12 (12 being example of the value when user hits edit)

it would look something like this:

template:

<template
  v-for="col in editableCells"
  #[col]="{ column, text, record }"
  :key="col"
>
  <div class="editable-cell">
    <div
      v-if="editableData[record.key + '|' + column.key]"
      class="editable-cell-input-wrapper"
    >
      <a-input
        v-model:value="editableData[record.key + '|' + column.key]"
        @pressEnter="save(record.key, column.key)"
      />
      <check-outlined
        class="editable-cell-icon-check"
        @click="save(record.key, column.key)"
      />
    </div>
    <div v-else class="editable-cell-text-wrapper">
      {{ text || ' ' }}
      <edit-outlined
        class="editable-cell-icon"
        @click="edit(record.key, column.key)"
      />
    </div>
  </div>
</template>

script:

const edit = (row, column) => {
  editableData[row + '|' + column] = dataSource.value.filter(
    (item) => row === item.key
  )[0][column];
};

const save = (row, column) => {
  dataSource.value[row][column] = editableData[row + '|' + column];
  delete editableData[row + '|' + column];
};

I'm using the pipe character as a separation character to concatenate the two strings, you can omit that and just use row + column which should resolve to a string and not cause any issues. This can be handy though if you have a potential for conflicting keys (such as both being indexes)


来源: stackexchange

问:
Converting matrix data frame to a list but I can't the same entry data to iNEXT
I am trying to convert a matrix data frame like this (lowland):

```<code>     species DT1 DT3 DT6 DT7 DT12 DT13 DT14 DT15 DT28 DT29
1  M_vaccinifolia   0   0   0   0    0    0    1    0    0    1
2  M_vaccinifolia   0   0   0   0    0    0    0    0    0    1
3  M_vaccinifolia   0   0   0   0    0    0    0    0    0    1
4  M_vaccinifolia   0   0   0   0    0    0    0    0    0    1
5  M_vaccinifolia   0   0   0   0    0    0    0    0    0    1
6  M_vaccinifolia   0   0   0   0    0    0    0    0    0    1
7  M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
8  M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
9  M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
10 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
11 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
12 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
13 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
14 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
15 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
16 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
17 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
18 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
19 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
20 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
21 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
22 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
23 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
24 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
</code>```

And I want to transform to a list that I can enter the data as the iNEXT data "ciliates" list is used to perform the examples in the rarefaction curves (example in the section "RAW INCIDENCE DATA FUNCTION: incidence_raw" in this link: https://cran.r-project.org/web/packages/iNEXT/vignettes/Introduction.html. Below is how the list is interpreted:

```<code> command
str(ciliates$EtoshaPan)

int [1:365, 1:19] 0 0 0 0 0 0 0 0 0 0 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:365] "Acaryophrya.collaris" "Actinobolina.multinucleata.n..sp." "Afroamphisiella.multinucleata.n..sp." "Afrothrix.multinucleata.n..sp." ...
  ..$ : chr [1:19] "x53" "x54" "x55" "x56" ...
</code>```

When I convert my data lowland, I just can reach this kind of list

```<code>     lowland_list <- list(lowland)
    str(lowland_list)

    List of 1
 $ :'data.frame':   24 obs. of  11 variables:
  ..$ species: chr [1:24] "M_vaccinifolia" "M_vaccinifolia" "M_vaccinifolia" "M_vaccinifolia" ...
  ..$ DT1    : int [1:24] 0 0 0 0 0 0 0 0 0 0 ...
  ..$ DT3    : int [1:24] 0 0 0 0 0 0 0 0 0 0 ...
  ..$ DT6    : int [1:24] 0 0 0 0 0 0 0 0 0 0 ...
  ..$ DT7    : int [1:24] 0 0 0 0 0 0 0 0 0 0 ...
  ..$ DT12   : int [1:24] 0 0 0 0 0 0 0 0 0 0 ...
  ..$ DT13   : int [1:24] 0 0 0 0 0 0 0 0 0 0 ...
  ..$ DT14   : int [1:24] 1 0 0 0 0 0 0 0 0 0 ...
  ..$ DT15   : int [1:24] 0 0 0 0 0 0 0 0 0 0 ...
  ..$ DT28   : int [1:24] 0 0 0 0 0 0 0 0 0 0 ...
  ..$ DT29   : int [1:24] 1 1 1 1 1 1 0 0 0 0 ...
</code>```

What is not a proper entry data format to iNEXT read as the example.
I spent many hours trying to make a list to enter this data but I couldn't figure it out. How can I do this?

答:
Not sure if this helps, but I have 2 data.frames that are in species columns and sites rows (datA and datB).
Here's some example code.

make an empty list:

datlist <- list()
datlist$A <- data.frame(t(datA))
datlist$B <- data.frame(t(datB))
```
<p>then run iNEXT</p>
<pre class="lang-r prettyprint-override"><code>iNEXT(datlist
      , q = c(0, 1, 2)
      , "incidence_raw"
      , conf = 0.95
      , se = TRUE
      , knots = 200
      , nboot = 200
      )
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to convert a matrix data frame like this (lowland):

     species DT1 DT3 DT6 DT7 DT12 DT13 DT14 DT15 DT28 DT29
1  M_vaccinifolia   0   0   0   0    0    0    1    0    0    1
2  M_vaccinifolia   0   0   0   0    0    0    0    0    0    1
3  M_vaccinifolia   0   0   0   0    0    0    0    0    0    1
4  M_vaccinifolia   0   0   0   0    0    0    0    0    0    1
5  M_vaccinifolia   0   0   0   0    0    0    0    0    0    1
6  M_vaccinifolia   0   0   0   0    0    0    0    0    0    1
7  M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
8  M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
9  M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
10 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
11 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
12 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
13 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
14 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
15 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
16 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
17 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
18 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
19 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
20 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
21 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
22 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
23 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0
24 M_vaccinifolia   0   0   0   0    0    0    0    0    0    0

And I want to transform to a list that I can enter the data as the iNEXT data "ciliates" list is used to perform the examples in the rarefaction curves (example in the section "RAW INCIDENCE DATA FUNCTION: incidence_raw" in this link: https://cran.r-project.org/web/packages/iNEXT/vignettes/Introduction.html. Below is how the list is interpreted:

 command
str(ciliates$EtoshaPan)

int [1:365, 1:19] 0 0 0 0 0 0 0 0 0 0 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:365] "Acaryophrya.collaris" "Actinobolina.multinucleata.n..sp." "Afroamphisiella.multinucleata.n..sp." "Afrothrix.multinucleata.n..sp." ...
  ..$ : chr [1:19] "x53" "x54" "x55" "x56" ...

When I convert my data lowland, I just can reach this kind of list

     lowland_list <- list(lowland)
    str(lowland_list)

    List of 1
 $ :'data.frame':   24 obs. of  11 variables:
  ..$ species: chr [1:24] "M_vaccinifolia" "M_vaccinifolia" "M_vaccinifolia" "M_vaccinifolia" ...
  ..$ DT1    : int [1:24] 0 0 0 0 0 0 0 0 0 0 ...
  ..$ DT3    : int [1:24] 0 0 0 0 0 0 0 0 0 0 ...
  ..$ DT6    : int [1:24] 0 0 0 0 0 0 0 0 0 0 ...
  ..$ DT7    : int [1:24] 0 0 0 0 0 0 0 0 0 0 ...
  ..$ DT12   : int [1:24] 0 0 0 0 0 0 0 0 0 0 ...
  ..$ DT13   : int [1:24] 0 0 0 0 0 0 0 0 0 0 ...
  ..$ DT14   : int [1:24] 1 0 0 0 0 0 0 0 0 0 ...
  ..$ DT15   : int [1:24] 0 0 0 0 0 0 0 0 0 0 ...
  ..$ DT28   : int [1:24] 0 0 0 0 0 0 0 0 0 0 ...
  ..$ DT29   : int [1:24] 1 1 1 1 1 1 0 0 0 0 ...

What is not a proper entry data format to iNEXT read as the example.
I spent many hours trying to make a list to enter this data but I couldn't figure it out. How can I do this?

Body:
Not sure if this helps, but I have 2 data.frames that are in species columns and sites rows (datA and datB).
Here's some example code.

make an empty list:

datlist <- list()
datlist$A <- data.frame(t(datA))
datlist$B <- data.frame(t(datB))

then run iNEXT

iNEXT(datlist
      , q = c(0, 1, 2)
      , "incidence_raw"
      , conf = 0.95
      , se = TRUE
      , knots = 200
      , nboot = 200
      )


问:
could not install sass-loader using npm
when I using this command to install sass-loader in my project:

```<code>npm install sass-loader@12.4.0
</code>```

show error like this:

```<code>➜  crx-selection-translate git:(6.x-master) ✗ npm install sass-loader@12.4.0
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: undefined@undefined
npm ERR! Found: webpack@1.15.0
npm ERR! node_modules/webpack
npm ERR!   dev webpack@"^1.13.1" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer webpack@"^5.0.0" from sass-loader@12.4.0
npm ERR! node_modules/sass-loader
npm ERR!   sass-loader@"12.4.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /Users/xiaoqiangjiang/.npm/eresolve-report.txt for a full report.
</code>```

why did this happen? what should I do to fix this problem? is it possible to auto resolve and fix the dependencies? I really did not know which version should I use, and I still did not know the dependencies matrix, is it possible to let the npm to find the most suitable dependencies and auto install and fix?

答:
I found a solution on dev.to

This worked for me

```<code>npm install -D sass-loader@^10 sass
</code>```

Title: could not install sass-loader using npm

Body:
when I using this command to install sass-loader in my project:

npm install sass-loader@12.4.0

show error like this:

➜  crx-selection-translate git:(6.x-master) ✗ npm install sass-loader@12.4.0
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: undefined@undefined
npm ERR! Found: webpack@1.15.0
npm ERR! node_modules/webpack
npm ERR!   dev webpack@"^1.13.1" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer webpack@"^5.0.0" from sass-loader@12.4.0
npm ERR! node_modules/sass-loader
npm ERR!   sass-loader@"12.4.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /Users/xiaoqiangjiang/.npm/eresolve-report.txt for a full report.

why did this happen? what should I do to fix this problem? is it possible to auto resolve and fix the dependencies? I really did not know which version should I use, and I still did not know the dependencies matrix, is it possible to let the npm to find the most suitable dependencies and auto install and fix?

Body:
I found a solution on dev.to

This worked for me

npm install -D sass-loader@^10 sass


问:
Typescript Inferring parameter types from function records
I have a object fn with name:function pairs that can take arbitrary parameters. I want to be able to map these functions in order to wrap them with another default function to handle errors in a single location. I have the following code which doesn't even compile giving A spread argument must either have a tuple type or be passed to a rest parameter. on fn[f](...args)

```<code>const fn = {
    ...userActions,
    ...companyActions,
    ...dataActions
};

type A<T extends Array<any>, U> = Record<keyof typeof fn, (...args: T) => Promise<U>>;

function map<T extends Array<any>, U>(f: keyof A<T, U>, ...args: T) {
    fn[f](...args);
}
</code>```

I can wrap functions using the code below but it requires importing the relevant function into the caller file and passing it into fn parameter

```<code>async function run<T extends Array<any>, U>(fn: (...args: T) => Promise<U>, ...temp: Parameters<typeof fn>) {
    await fn(...temp); // works but needs to pass the function itself.
}
</code>```

Is there a way to get around the issue on first piece of code? Basically I want to infer the parameter type by using just the key from a record.

答:
The problem here is that, in your map function, Typescript does not infer that keyof typeof fn is one particular key of fn, but rather that it is the union of all possible keys of fn.  It won't resolve the particular key until you actually pass it a concrete type when you call map.  This in turn means that args is being resolve as the intersection of all possible args of all functions in fn--not a spread of one particular args.

This is a typescript limitation as TS won't resolve the generic inside a function until it is actually passed a concrete type.

So, unfortunately, I do think some assertion is necessary inside the map function, but that doesn't prevent you from having good type safety on the inputs and outputs of your map function.

That said, I wasn't 100% clear on how you were hoping to use your map function, but hopefully this helps understand a way to type this kind of problem:

const userActions = {
  func1: (x:string)=>parseInt(x)
}
const companyActions = {
  func2: (x:number)=>x.toString()
}
const fn = {
    ...userActions,
    ...companyActions,
};

 function map<T extends keyof typeof fn>(f: T, ...args: Parameters<typeof fn[T]>):ReturnType<typeof fn[T]> {
    return (fn[f] as any)(args) as ReturnType<typeof fn[T]>;
}

map("func1", "foo")
map("func2", 3)

//these will error
map("func1", 3)
map("func2", "string")
```

With a playground.  This will ensure the inputs and output of map are typed based on fn.

I removed the Promise as I don't think that's fundamental to your question.  It's trivial to add that back in.  Please post more info if this isn't sufficient.

Body:
I have a object fn with name:function pairs that can take arbitrary parameters. I want to be able to map these functions in order to wrap them with another default function to handle errors in a single location. I have the following code which doesn't even compile giving A spread argument must either have a tuple type or be passed to a rest parameter. on fn[f](...args)

const fn = {
    ...userActions,
    ...companyActions,
    ...dataActions
};

type A<T extends Array<any>, U> = Record<keyof typeof fn, (...args: T) => Promise>;

function map<T extends Array<any>, U>(f: keyof A<T, U>, ...args: T) {
    fn[f](...args);
}

I can wrap functions using the code below but it requires importing the relevant function into the caller file and passing it into fn parameter

async function run<T extends Array<any>, U>(fn: (...args: T) => Promise, ...temp: Parameters<typeof fn>) {
    await fn(...temp); // works but needs to pass the function itself.
}

Is there a way to get around the issue on first piece of code? Basically I want to infer the parameter type by using just the key from a record.

Body:
The problem here is that, in your map function, Typescript does not infer that keyof typeof fn is one particular key of fn, but rather that it is the union of all possible keys of fn.  It won't resolve the particular key until you actually pass it a concrete type when you call map.  This in turn means that args is being resolve as the intersection of all possible args of all functions in fn--not a spread of one particular args.

This is a typescript limitation as TS won't resolve the generic inside a function until it is actually passed a concrete type.

So, unfortunately, I do think some assertion is necessary inside the map function, but that doesn't prevent you from having good type safety on the inputs and outputs of your map function.

That said, I wasn't 100% clear on how you were hoping to use your map function, but hopefully this helps understand a way to type this kind of problem:

const userActions = {
  func1: (x:string)=>parseInt(x)
}
const companyActions = {
  func2: (x:number)=>x.toString()
}
const fn = {
    ...userActions,
    ...companyActions,
};

 function map<T extends keyof typeof fn>(f: T, ...args: Parameters<typeof fn[T]>):ReturnType<typeof fn[T]> {
    return (fn[f] as any)(args) as ReturnType<typeof fn[T]>;
}

map("func1", "foo")
map("func2", 3)

//these will error
map("func1", 3)
map("func2", "string")

With a <a href="https://www.typescriptlang.org/play?#code/MYewdgzgLgBArhApgJwILCgS3BGBeGAbwCgYYAzOMYARgC4YAKADzumUzAHMBKPAPgAOAQ2RIAkmCgsexAL7FQkWKAC2IsAE90WHPiKkKVYACYGLOmDiqARij79mAOiggAylA7dGshUugUYPokZGRO4QgoOtiQADSGYeFqGtoYMRDxcgDcxKSU1LpBqsKCADwAKjCIzFCIYAAmuADWiJog5DBQmoKI7YH8jOQM5bEw4U6iXBAMAAqiwqqItWKlXT195GAA2uUAuvw8dABKS3DIYOXdiKtXG9t7-AahMMin50ybW%20S7MMK4wloeIxJhAeL9cCcoGcLlcbusOp8HjkFMRioJGAAifK0DGjLEgEAY2RozHYky4mAAZlkxAA9LSoAALRBIGAQRkgOAAG3qVWQyBAyFRJVJxhoFOpwvRWOM5Lx7E4XCJQA" rel="nofollow noreferrer">playground.  This will ensure the inputs and output of map are typed based on fn.

I removed the Promise as I don't think that's fundamental to your question.  It's trivial to add that back in.  Please post more info if this isn't sufficient.


问:
A more efficient way of updating object field values in Java
I have a golf application and I want to update an Scorecard which has score, nettScore, points each for 18 holes, so 54 in total

I have spent a few days getting to the point I am at now, All works fine, but I feel there must be a more efficient way of doing this. So far I have this, (ent refers to an Entrant and e refers to an event)

```<code>public void update(long eventId, long memberId, ScoreCard scorecard) {
    Event e = eventRepo.findEventById(eventId);
    Member m = memberRepo.findMemberById(memberId);
    double courseHandicapDouble = m.getHandicap()/113*e.getCourse().getSlopeRating();
    int courseHcp = (int) Math.round(courseHandicapDouble);
    int stableFordTotal = 0;
    int medalTotal = 0;
    int nettTotal = 0;
    List<Entrants> en = entrantsRepo.findAllByEvent(e);
    for(Entrants ent : en) {
        if (ent.getMember().equals(m)) {
            //Hole 1
            //Set the entrants score to the value of hole1 score on the scorecard
            ent.getScoreCard().setH1Score(scorecard.getH1Score());
            //If the players course handicap is more than or equal to the stroke index for the hole, set nett score to score -1
            if(courseHcp >= e.getCourse().getHoles().get(0).getStrokeIndex()) {
                ent.getScoreCard().setH1NettScore(scorecard.getH1Score() - 1);
                //Set points for the first hole as per the setPoints helper method.
                    ent.getScoreCard().setH1Points(setPointsPar(ent.getScoreCard().getH1NettScore(), e.getCourse().getHoles().get(0).getPar()));
            } else {
                ent.getScoreCard().setH1NettScore(scorecard.getH1Score());
                ent.getScoreCard().setH1Points(setPointsPar(ent.getScoreCard().getH1NettScore(), e.getCourse().getHoles().get(0).getPar()));
            }
            //Update running total scores
            medalTotal += ent.getScoreCard().getH1Score();
            stableFordTotal += ent.getScoreCard().getH1Points();
            nettTotal += ent.getScoreCard().getH1NettScore();
//repeated 18 times for holes 2-18
</code>```

The helper method to work out the points is a simple switch method that gives points depending on the score and the par of the hole.

```<code>public int setPointsPar(int score, int par){
        int points = 0;
        if(par == 3) {
            switch (score) {
                case 1:
                    points = 4;
                    break;
                case 2:
                    points = 3;
                    break;
                case 3:
                    points = 2;
                    break;
                case 4:
                    points = 1;
                    break;
            }
        }

        if(par == 4) {
            switch (score) {
                case 1:
                    points = 5;
                    break;
                case 2:
                    points = 4;
                    break;
                case 3:
                    points = 3;
                    break;
                case 4:
                    points = 2;
                    break;
                case 5:
                    points = 1;
                    break;
            }
        }
            if(par == 5) {
                switch (score) {
                    case 1:
                        points = 6;
                        break;
                    case 2:
                        points = 5;
                        break;
                    case 3:
                        points = 4;
                        break;
                    case 4:
                        points = 3;
                        break;
                    case 5:
                        points = 2;
                        break;
                    case 6:
                        points = 1;
                        break;
                }
        }
        return points;
    }
</code>```

This part of the code is almost duplicated 18 times, the only difference being that h1Score is change to h2Score and h1NettScore to h2NettScore etc

```<code>//Hole 1
                //Set the entrants score to the value of hole1 score on the scorecard
                ent.getScoreCard().setH1Score(scorecard.getH1Score());
                //If the players course handicap is more than or equal to the stroke index for the hole, set nett score to score -1
                if(courseHcp >= e.getCourse().getHoles().get(0).getStrokeIndex()) {
                    ent.getScoreCard().setH1NettScore(scorecard.getH1Score() - 1);
                    //Set points for the first hole as per the setPoints helper method.
                        ent.getScoreCard().setH1Points(setPointsPar(ent.getScoreCard().getH1NettScore(), e.getCourse().getHoles().get(0).getPar()));
                } else {
                    ent.getScoreCard().setH1NettScore(scorecard.getH1Score());
                    ent.getScoreCard().setH1Points(setPointsPar(ent.getScoreCard().getH1NettScore(), e.getCourse().getHoles().get(0).getPar()));
                }
                //Update running total scores
                medalTotal += ent.getScoreCard().getH1Score();
                stableFordTotal += ent.getScoreCard().getH1Points();
                nettTotal += ent.getScoreCard().getH1NettScore();
</code>```

I can't think of any possible way to loop through the above so that all the 1s are changed to 2s, then 3s etc.

As I say, what I have works fine. It is more of a learning point for me as I like to write as efficiently as possible.

答:
First you can calculate the score as simply par + 2 - score and get rid of the case statements.

Second, your ScoreCard class should have a number of Map<Integer,Integer>s which contain the score, points and nett score for each hole, so you can write:

void updateForHole(Event e, Entrants ent, int hole) {
//Set the entrants score to the value of hole1 score on the scorecard
                ent.getScoreCard().setScore(hole, scorecard.getScore(hole));
                //If the players course handicap is more than or equal to the stroke index for the hole, set nett score to score -1
                if(courseHcp >= e.getCourse().getHoles().get(hole).getStrokeIndex()) {
                    ent.getScoreCard().setNettScore(hole, scorecard.getScore(hole) - 1);
                    //Set points for the first hole as per the setPoints helper method.
                        ent.getScoreCard().setPoints(hole, setPointsPar(ent.getScoreCard().getNettScore(hole), e.getCourse().getHoles().get(hole).getPar()));
                } else {
                    ent.getScoreCard().setNettScore(hole, scorecard.getScore(hole));
                    ent.getScoreCard().setPoints(hole, setPointsPar(ent.getScoreCard().getNettScore(hole), e.getCourse().getHoles().get(0).getPar()));
                }
                //Update running total scores
                medalTotal += ent.getScoreCard().getScore(hole);
                stableFordTotal += ent.getScoreCard().getPoints(hole);
                nettTotal += ent.getScoreCard().getNettScore(hole);
}
```
<p>This is similar to the approach you already use for getting a particular hole from the course.</p>
<p>Then you call <code>updateForHole</code> in a loop: (I'm using zero for hole 1 to match what you've done with the <code>Course</code> already)</p>
```for (int hole = 0; hole < e.getCourse().getHoles().size(); hole++) {
  updateForHole(hole);
}
```
<p>The get and set functions could look like this:</p>
```class ScoreCard {
  private final Map<Integer,Integer> scores = new HashMap<>();
  ...
  public void setScore(int hole, int score) {
    scores.put(hole, score);
  }

  public int getScore(int hole) {
    return scores.get(hole);
  }
  ...
}
```

If you call getScore for a hole which you haven't set a score for yet, it will throw a NullPointerException, because the value in the Map for that hole will be null. That will tell you that you have a logic bug in your program, and you are trying to use a value before you've set it. Finding that out is usually a good thing.

Body:
I have a golf application and I want to update an Scorecard which has score, nettScore, points each for 18 holes, so 54 in total

I have spent a few days getting to the point I am at now, All works fine, but I feel there must be a more efficient way of doing this. So far I have this, (ent refers to an Entrant and e refers to an event)

public void update(long eventId, long memberId, ScoreCard scorecard) {
    Event e = eventRepo.findEventById(eventId);
    Member m = memberRepo.findMemberById(memberId);
    double courseHandicapDouble = m.getHandicap()/113*e.getCourse().getSlopeRating();
    int courseHcp = (int) Math.round(courseHandicapDouble);
    int stableFordTotal = 0;
    int medalTotal = 0;
    int nettTotal = 0;
    List<Entrants> en = entrantsRepo.findAllByEvent(e);
    for(Entrants ent : en) {
        if (ent.getMember().equals(m)) {
            //Hole 1
            //Set the entrants score to the value of hole1 score on the scorecard
            ent.getScoreCard().setH1Score(scorecard.getH1Score());
            //If the players course handicap is more than or equal to the stroke index for the hole, set nett score to score -1
            if(courseHcp >= e.getCourse().getHoles().get(0).getStrokeIndex()) {
                ent.getScoreCard().setH1NettScore(scorecard.getH1Score() - 1);
                //Set points for the first hole as per the setPoints helper method.
                    ent.getScoreCard().setH1Points(setPointsPar(ent.getScoreCard().getH1NettScore(), e.getCourse().getHoles().get(0).getPar()));
            } else {
                ent.getScoreCard().setH1NettScore(scorecard.getH1Score());
                ent.getScoreCard().setH1Points(setPointsPar(ent.getScoreCard().getH1NettScore(), e.getCourse().getHoles().get(0).getPar()));
            }
            //Update running total scores
            medalTotal += ent.getScoreCard().getH1Score();
            stableFordTotal += ent.getScoreCard().getH1Points();
            nettTotal += ent.getScoreCard().getH1NettScore();
//repeated 18 times for holes 2-18

The helper method to work out the points is a simple switch method that gives points depending on the score and the par of the hole.

public int setPointsPar(int score, int par){
        int points = 0;
        if(par == 3) {
            switch (score) {
                case 1:
                    points = 4;
                    break;
                case 2:
                    points = 3;
                    break;
                case 3:
                    points = 2;
                    break;
                case 4:
                    points = 1;
                    break;
            }
        }

        if(par == 4) {
            switch (score) {
                case 1:
                    points = 5;
                    break;
                case 2:
                    points = 4;
                    break;
                case 3:
                    points = 3;
                    break;
                case 4:
                    points = 2;
                    break;
                case 5:
                    points = 1;
                    break;
            }
        }
            if(par == 5) {
                switch (score) {
                    case 1:
                        points = 6;
                        break;
                    case 2:
                        points = 5;
                        break;
                    case 3:
                        points = 4;
                        break;
                    case 4:
                        points = 3;
                        break;
                    case 5:
                        points = 2;
                        break;
                    case 6:
                        points = 1;
                        break;
                }
        }
        return points;
    }

This part of the code is almost duplicated 18 times, the only difference being that h1Score is change to h2Score and h1NettScore to h2NettScore etc

//Hole 1
                //Set the entrants score to the value of hole1 score on the scorecard
                ent.getScoreCard().setH1Score(scorecard.getH1Score());
                //If the players course handicap is more than or equal to the stroke index for the hole, set nett score to score -1
                if(courseHcp >= e.getCourse().getHoles().get(0).getStrokeIndex()) {
                    ent.getScoreCard().setH1NettScore(scorecard.getH1Score() - 1);
                    //Set points for the first hole as per the setPoints helper method.
                        ent.getScoreCard().setH1Points(setPointsPar(ent.getScoreCard().getH1NettScore(), e.getCourse().getHoles().get(0).getPar()));
                } else {
                    ent.getScoreCard().setH1NettScore(scorecard.getH1Score());
                    ent.getScoreCard().setH1Points(setPointsPar(ent.getScoreCard().getH1NettScore(), e.getCourse().getHoles().get(0).getPar()));
                }
                //Update running total scores
                medalTotal += ent.getScoreCard().getH1Score();
                stableFordTotal += ent.getScoreCard().getH1Points();
                nettTotal += ent.getScoreCard().getH1NettScore();

I can't think of any possible way to loop through the above so that all the 1s are changed to 2s, then 3s etc.

As I say, what I have works fine. It is more of a learning point for me as I like to write as efficiently as possible.

Body:
First you can calculate the score as simply par + 2 - score and get rid of the case statements.

Second, your ScoreCard class should have a number of Map<Integer,Integer>s which contain the score, points and nett score for each hole, so you can write:

void updateForHole(Event e, Entrants ent, int hole) {
//Set the entrants score to the value of hole1 score on the scorecard
                ent.getScoreCard().setScore(hole, scorecard.getScore(hole));
                //If the players course handicap is more than or equal to the stroke index for the hole, set nett score to score -1
                if(courseHcp >= e.getCourse().getHoles().get(hole).getStrokeIndex()) {
                    ent.getScoreCard().setNettScore(hole, scorecard.getScore(hole) - 1);
                    //Set points for the first hole as per the setPoints helper method.
                        ent.getScoreCard().setPoints(hole, setPointsPar(ent.getScoreCard().getNettScore(hole), e.getCourse().getHoles().get(hole).getPar()));
                } else {
                    ent.getScoreCard().setNettScore(hole, scorecard.getScore(hole));
                    ent.getScoreCard().setPoints(hole, setPointsPar(ent.getScoreCard().getNettScore(hole), e.getCourse().getHoles().get(0).getPar()));
                }
                //Update running total scores
                medalTotal += ent.getScoreCard().getScore(hole);
                stableFordTotal += ent.getScoreCard().getPoints(hole);
                nettTotal += ent.getScoreCard().getNettScore(hole);
}

This is similar to the approach you already use for getting a particular hole from the course.

Then you call updateForHole in a loop: (I'm using zero for hole 1 to match what you've done with the Course already)

for (int hole = 0; hole < e.getCourse().getHoles().size(); hole++) {
  updateForHole(hole);
}

The get and set functions could look like this:

class ScoreCard {
  private final Map<Integer,Integer> scores = new HashMap<>();
  ...
  public void setScore(int hole, int score) {
    scores.put(hole, score);
  }

  public int getScore(int hole) {
    return scores.get(hole);
  }
  ...
}

If you call getScore for a hole which you haven't set a score for yet, it will throw a NullPointerException, because the value in the Map for that hole will be null. That will tell you that you have a logic bug in your program, and you are trying to use a value before you've set it. Finding that out is usually a good thing.


问:
Use of semicolons with if/else and try/finally blocks
I have found that this code compiles both with and without a semicolon at the places pointed out below.

What is the correct way to use semicolons here?

```<code>  try
    try
      if MyBoolean = True then
      begin
        DoSomething;
      end
      else
      begin
        DoSomethingElse;
      end <<<--- Semi colon here?
    except
      ;
    end <<<--- Semi colon here?
  finally
    ;
  end;
</code>```

答:
This is documented behavior:

Declarations and Statements (Delphi): Compound Statements

A compound statement is a sequence of other (simple or structured) statements to be executed in the order in which they are written. The compound statement is bracketed by the reserved words begin and end, and its constituent statements are separated by semicolons. For example:

```<code>begin
  Z := X;
  X := Y;
  X := Y;
end;
</code>```

The last semicolon before end is optional. So this could have been written as:

```<code>begin
  Z := X;
  X := Y;
  Y := Z
end;
</code>```

And also:

Delphi's Object Pascal Style Guide: Statements

Statements are one or more lines of code followed by a semicolon. Simple statements have one semicolon, while compound statements have more than one semicolon and therefore consist of multiple simple statements.

Here is a simple statement:

```<code>A := B;
</code>```

If you need to wrap the simple statement, indent the second line two spaces in from the previous line. Here is a compound, or structured, statement:

```<code>begin
  B := C;
  A := B;
end;
</code>```

Compound Statements always end with a semicolon, unless they immediately precede an end keyword, in which case the semicolon is optional but recommended by this style guide.

An "end keyword" in your example would include except and finally.

Body:
I have found that this code compiles both with and without a semicolon at the places pointed out below.

What is the correct way to use semicolons here?

  try
    try
      if MyBoolean = True then
      begin
        DoSomething;
      end
      else
      begin
        DoSomethingElse;
      end <<<--- Semi colon here?
    except
      ;
    end <<<--- Semi colon here?
  finally
    ;
  end;

Body:
This is documented behavior:

Declarations and Statements (Delphi): Compound Statements

A compound statement is a sequence of other (simple or structured) statements to be executed in the order in which they are written. The compound statement is bracketed by the reserved words begin and end, and its constituent statements are separated by semicolons. For example:

begin
  Z := X;
  X := Y;
  X := Y;
end;

The last semicolon before end is optional. So this could have been written as:

begin
  Z := X;
  X := Y;
  Y := Z
end;

And also:

Delphi's Object Pascal Style Guide: Statements

Statements are one or more lines of code followed by a semicolon. Simple statements have one semicolon, while compound statements have more than one semicolon and therefore consist of multiple simple statements.

Here is a simple statement:

A := B;

If you need to wrap the simple statement, indent the second line two spaces in from the previous line. Here is a compound, or structured, statement:

begin
  B := C;
  A := B;
end;

Compound Statements always end with a semicolon, unless they immediately precede an end keyword, in which case the semicolon is optional but recommended by this style guide.

An "end keyword" in your example would include except and finally.


问:
Unity trying to convert a variable defined as a float to a vetcor3?
Unity doesn't seem to like the way I'm declaring my variables, I was just trying to clean up my code and moved some of the variables and now it doesn't work.

The Error:

Assets\Movement.cs(33,22): error CS0029: Cannot implicitly convert type 'UnityEngine.Vector3' to 'float'

Assets\Movement.cs(39,29): error CS1503: Argument 1: cannot convert from 'float' to 'UnityEngine.Vector3'

Assets\Movement.cs(41,29): error CS1503: Argument 1: cannot convert from 'float' to 'UnityEngine.Vector3'

Assets\Movement.cs(43,29): error CS1503: Argument 1: cannot convert from 'float' to 'UnityEngine.Vector3'

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Movement : MonoBehaviour{
    public CharacterController controller;
    public Transform Player;
    public Transform groundCheck;
    public Text StaminaBar;
    public LayerMask groundMask;

    Vector3 move;
    Vector3 velocity;

    float WalkingSpeed = 12;
    float SprintingSpeed = 15;
    float CrouchingSpeed = 6;
    float gravity = 30;

    void Update(){
        Speed();
        Jump();
        Crouching();
        //Gravity
        controller.Move(velocity * Time.deltaTime);
    }
    void Speed(){
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");
        float CurrentX = Player.transform.position.x;
        float CurrentZ = Player.transform.position.z;
        float move = transform.right * x + transform.forward * z;
        bool isWalking = Input.GetKey(KeyCode.W);
        bool isCrouching = Input.GetKey(KeyCode.LeftShift);
        bool isSprinting = Input.GetKey(KeyCode.R);
        velocity.y += gravity * Time.deltaTime;
        if (isWalking){
            controller.Move(move * WalkingSpeed * Time.deltaTime);
        } else if (isCrouching){
            controller.Move(move * CrouchingSpeed * Time.deltaTime);
        }else if(isSprinting){
            controller.Move(move * SprintingSpeed * Time.deltaTime);
        }
    }
    void Jump(){
        bool isGrounded = Physics.CheckSphere(groundCheck.position, 0.1f, groundMask);

    }
    void Crouching(){
    }
    void Sliding(){
    }
    void Climbing(){
    }
    void WallRunning(){
    }
}```
```

答:
You are declaring your variable move multiple times.

float move = ... should be move = ...

Body:
Unity doesn't seem to like the way I'm declaring my variables, I was just trying to clean up my code and moved some of the variables and now it doesn't work.

The Error:

Assets\Movement.cs(33,22): error CS0029: Cannot implicitly convert type 'UnityEngine.Vector3' to 'float'

Assets\Movement.cs(39,29): error CS1503: Argument 1: cannot convert from 'float' to 'UnityEngine.Vector3'

Assets\Movement.cs(41,29): error CS1503: Argument 1: cannot convert from 'float' to 'UnityEngine.Vector3'

Assets\Movement.cs(43,29): error CS1503: Argument 1: cannot convert from 'float' to 'UnityEngine.Vector3'

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Movement : MonoBehaviour{
    public CharacterController controller;
    public Transform Player;
    public Transform groundCheck;
    public Text StaminaBar;
    public LayerMask groundMask;

    Vector3 move;
    Vector3 velocity;

    float WalkingSpeed = 12;
    float SprintingSpeed = 15;
    float CrouchingSpeed = 6;
    float gravity = 30;

    void Update(){
        Speed();
        Jump();
        Crouching();
        //Gravity
        controller.Move(velocity * Time.deltaTime);
    }
    void Speed(){
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");
        float CurrentX = Player.transform.position.x;
        float CurrentZ = Player.transform.position.z;
        float move = transform.right * x + transform.forward * z;
        bool isWalking = Input.GetKey(KeyCode.W);
        bool isCrouching = Input.GetKey(KeyCode.LeftShift);
        bool isSprinting = Input.GetKey(KeyCode.R);
        velocity.y += gravity * Time.deltaTime;
        if (isWalking){
            controller.Move(move * WalkingSpeed * Time.deltaTime);
        } else if (isCrouching){
            controller.Move(move * CrouchingSpeed * Time.deltaTime);
        }else if(isSprinting){
            controller.Move(move * SprintingSpeed * Time.deltaTime);
        }
    }
    void Jump(){
        bool isGrounded = Physics.CheckSphere(groundCheck.position, 0.1f, groundMask);

    }
    void Crouching(){
    }
    void Sliding(){
    }
    void Climbing(){
    }
    void WallRunning(){
    }
}```


问:
Pull ALL files from git LFS
Is it possible to locally cache ALL files in a git-LFS repo for offline use? That is, make the repo usable like a normal git repo, even without an internet connection to fetch git-LFS files?</p>

答:
Local git to retrieve the latest meta-data

```<code>git lfs fetch --all
</code>```

Brings (copy) the changes from the remote repository

```<code>git lfs pull
</code>```

Title: Pull ALL files from git LFS

Body:
Local git to retrieve the latest meta-data

git lfs fetch --all

Brings (copy) the changes from the remote repository

git lfs pull


问:
How to add and remove classes to the active slide child 'div' on react slick carousel
If you are on the active slide i want to add a className content_animation to the className="content_text".

And if the slide changes whether you click/swipe the arrows or dots, the active slide will always do the same which is to add a className content_animation to the className="content_text".

Im tyring to achieve it using beforeChange and/or afterChange.

Here is the react slick docs

Below is my code and also here is the complete sandbox code https://codesandbox.io/.

import React, { Component } from "react";
import Slider from "react-slick";

export default class SlideChangeHooks extends Component {
  render() {
    const settings = {
      dots: true,
      infinite: true,
      speed: 1000,
      slidesToShow: 1,
      slidesToScroll: 1,
      beforeChange: (oldIndex, newIndex) => {
        setTimeout(() => {
          const sample = document.querySelector(".content_text");
          sample.classList.remove("content_animation");
          console.log("beforeChange", oldIndex, newIndex);
        });
      },
      afterChange: (index) => {
        setTimeout(() => {
          const sample = document.querySelector(".content_text");
          sample.classList.add("content_animation");
          console.log("afterChange", index);
        });
      }
    };
    return (

        <Slider {...settings}>

1

Lorem Ipsum

2

Lorem Ipsum 2

3

Lorem Ipsum 3

        </Slider>

    );
  }
}```

答:
```<code> const sample = document.querySelector(".content_text");
</code>```

Because you use document.querySelector you take only one element, always the first, and a class never will be removed from other slides. You should use document.querySelectorAll to get all slides to remove the class from all slides.

```<code> const sample = document.querySelector(".content_text");
</code>```

Inside afterChange you should select only active slide and assign a class to it. Slick active slide has a class .slick-active

```<code> beforeChange: (oldIndex, newIndex) => {
    setTimeout(() => {
      const sample = document.querySelectorAll(".content_text");

      for (let i = 0; i < sample.length; i++) {
        sample[i].classList.remove("content_animation");
        console.log("beforeChange", oldIndex, newIndex);
      }

    });
  },
  afterChange: (index) => {
    setTimeout(() => {
      const sample = document.querySelector(".slick-active .content_text");
      sample.classList.add("content_animation");
      console.log("afterChange", index);
    });
  }
</code>```

Body:
 const sample = document.querySelector(".content_text");

Because you use document.querySelector you take only one element, always the first, and a class never will be removed from other slides. You should use document.querySelectorAll to get all slides to remove the class from all slides.

 const sample = document.querySelector(".content_text");

Inside afterChange you should select only active slide and assign a class to it. Slick active slide has a class .slick-active

 beforeChange: (oldIndex, newIndex) => {
    setTimeout(() => {
      const sample = document.querySelectorAll(".content_text");

      for (let i = 0; i < sample.length; i++) {
        sample[i].classList.remove("content_animation");
        console.log("beforeChange", oldIndex, newIndex);
      }

    });
  },
  afterChange: (index) => {
    setTimeout(() => {
      const sample = document.querySelector(".slick-active .content_text");
      sample.classList.add("content_animation");
      console.log("afterChange", index);
    });
  }


问:
SKLearn PCA explained_variance_ration cumsum gives array of 1
I have a problem with PCA. I read that PCA needs clean numeric values. I started my analysis with a dataset called trainDf with shape (1460, 79).

I did my data cleaning and processing by removing empty values, imputing and dropping columns and I got a dataframe transformedData with shape (1458, 69).

Data cleaning steps are:

LotFrontage imputing with mean value

MasVnrArea imputing with 0s (less than 10 cols)

Ordinal encoding for categorical columns

Electrical imputing with most frequent value

I found outliers with IQR and got withoutOutliers with shape (1223, 69).

After this, I looked at histograms and decided to apply PowerTransformer on some features and StandardScaler on others and I got normalizedData.

Now I tried doing PCA and I got this:

pca = PCA().fit(transformedData)

print(pca.explained_variance_ratio_.cumsum())

plt.plot(pca.explained_variance_ratio_.cumsum())
plt.xlabel('number of components')
plt.ylabel('cumulative explained variance')
```
<p>the output of this PCA is the following:</p>
```[0.67454179 0.8541084  0.98180307 0.99979932 0.99986346 0.9999237
 0.99997091 0.99997985 0.99998547 0.99999044 0.99999463 0.99999719
 0.99999791 0.99999854 0.99999909 0.99999961 0.99999977 0.99999988
 0.99999994 0.99999998 0.99999999 1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.        ]
```
<p><img src="https://i.stack.imgur.com/JquTF.png" alt="PCA1" /></p>
<p>Then I tried:</p>
<pre class="lang-py prettyprint-override"><code>pca = PCA().fit(withoutOutliers)

print(pca.explained_variance_ratio_.cumsum())

plt.plot(pca.explained_variance_ratio_.cumsum())
plt.xlabel('number of components')
plt.ylabel('cumulative explained variance')
</code>```

out:

```<code>[0.68447278 0.86982875 0.99806386 0.99983727 0.99989606 0.99994353
 0.99997769 0.99998454 0.99998928 0.99999299 0.9999958  0.99999775
 0.99999842 0.99999894 0.99999932 0.99999963 0.9999998  0.9999999
 0.99999994 0.99999998 0.99999999 1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.        ]
</code>```

Finally:

pca = PCA().fit(normalizedData)

print(pca.explained_variance_ratio_.cumsum())

plt.plot(pca.explained_variance_ratio_.cumsum())
plt.xlabel('number of components')
plt.ylabel('cumulative explained variance')
```
<p>Out:</p>
```[1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.
 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.
 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
```

How is it possible that the last execution gives such an output?

Here are data distributions

transformedData

withoutOutliers

normalizedData

I'll add any further data if necessary, thanks in advance to any who can help!

答:
In short, all data should be scaled before applying PCA (for example using a StandardScaler).

I got the answer on Data science stackexchange.

Body:
I have a problem with PCA. I read that PCA needs clean numeric values. I started my analysis with a dataset called trainDf with shape (1460, 79).

I did my data cleaning and processing by removing empty values, imputing and dropping columns and I got a dataframe transformedData with shape (1458, 69).

Data cleaning steps are:

LotFrontage imputing with mean value

MasVnrArea imputing with 0s (less than 10 cols)

Ordinal encoding for categorical columns

Electrical imputing with most frequent value

I found outliers with IQR and got withoutOutliers with shape (1223, 69).

After this, I looked at histograms and decided to apply PowerTransformer on some features and StandardScaler on others and I got normalizedData.

Now I tried doing PCA and I got this:

pca = PCA().fit(transformedData)

print(pca.explained_variance_ratio_.cumsum())

plt.plot(pca.explained_variance_ratio_.cumsum())
plt.xlabel('number of components')
plt.ylabel('cumulative explained variance')

the output of this PCA is the following:

[0.67454179 0.8541084  0.98180307 0.99979932 0.99986346 0.9999237
 0.99997091 0.99997985 0.99998547 0.99999044 0.99999463 0.99999719
 0.99999791 0.99999854 0.99999909 0.99999961 0.99999977 0.99999988
 0.99999994 0.99999998 0.99999999 1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.        ]

Then I tried:

pca = PCA().fit(withoutOutliers)

print(pca.explained_variance_ratio_.cumsum())

plt.plot(pca.explained_variance_ratio_.cumsum())
plt.xlabel('number of components')
plt.ylabel('cumulative explained variance')

out:

[0.68447278 0.86982875 0.99806386 0.99983727 0.99989606 0.99994353
 0.99997769 0.99998454 0.99998928 0.99999299 0.9999958  0.99999775
 0.99999842 0.99999894 0.99999932 0.99999963 0.9999998  0.9999999
 0.99999994 0.99999998 0.99999999 1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.        ]

Finally:

pca = PCA().fit(normalizedData)

print(pca.explained_variance_ratio_.cumsum())

plt.plot(pca.explained_variance_ratio_.cumsum())
plt.xlabel('number of components')
plt.ylabel('cumulative explained variance')

Out:

[1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.
 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.
 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]

How is it possible that the last execution gives such an output?

Here are data distributions

transformedData

withoutOutliers

normalizedData

I'll add any further data if necessary, thanks in advance to any who can help!


问:
C# Split a List in Columns
I am trying to split a List in C# and display the results in columns like this:

```<code>ID 1  ID 2
ID 3  ID 4
ID 5  ID 6
</code>```

Instead of displaying them like this:

```<code>ID 1
ID 2
ID 3
ID 4
ID 5
ID 6
</code>```

This is my list:

```<code>private List<ID> IDs = new List<ID>();
</code>```

And I'm trying to do something like this:

```<code>int chunkNumber = 1;
foreach (int[] chunk in Enumerable.Range(0, 8).Chunk(3))
{
    Console.WriteLine($"Chunk {chunkNumber++}:");
    foreach (int item in chunk)
    {
        Console.WriteLine($"    {item}");
    }

    Console.WriteLine();
}
</code>```

Any help on how to accomplish this?
Thanks

答:
just use Write instead of WriteLine

```<code>foreach (int item in chunk)
{
    Console.Write($"    {item}");
}
</code>```

or this if you like it more

```<code>Console.Write($"    ID {item}");
</code>```

Title: C# Split a List in Columns

Body:
I am trying to split a List in C# and display the results in columns like this:

ID 1  ID 2
ID 3  ID 4
ID 5  ID 6

Instead of displaying them like this:

ID 1
ID 2
ID 3
ID 4
ID 5
ID 6

This is my list:

private List<ID> IDs = new List<ID>();

And I'm trying to do something like this:

int chunkNumber = 1;
foreach (int[] chunk in Enumerable.Range(0, 8).Chunk(3))
{
    Console.WriteLine($"Chunk {chunkNumber++}:");
    foreach (int item in chunk)
    {
        Console.WriteLine($"    {item}");
    }

    Console.WriteLine();
}

Any help on how to accomplish this?
Thanks

Body:
just use Write instead of WriteLine

foreach (int item in chunk)
{
    Console.Write($"    {item}");
}

or this if you like it more

Console.Write($"    ID {item}");


问:
Scalar Variables from Perl to Python?
I am translating a program from perl to python and I really don't know how to translate a scalar variable to python. My problem is that I want to call the first value that comes in based on all the scalar variables used in the code, a scalar variable when mentioned it refers to the value assigned to it.

the specific area was

```<code>my $min = $_[0];
my $max = $_[1];
</code>```

So these two variables were assigned a value before hand, now what I am trying to do is call my min and let it be the first value that comes, then I want my max to be called as the second value that comes in. Basically, trying to gather the info that was generated to min and max and now bring it to here. Do not understand how to do this in python.

The thing is that I have 3-5 different values assigned to min and also to max, I dont know how to bring in the value.

i am the one who put the question, but I logged in as i think a temporary user and it got deleted. Thanks!

答:
I think you're talking about subroutine arguments.  The big diff between perl and python with function calls (in python they are more like methods..) is that python can pass different things as a single argument, as a regular operation, and while perl can do this, it is rare.  So if you are calling a 'function' in python you need to be aware of what the argument 'is'.  Is it an 'array' (list or dict or tuple) or scalar variable or string or a byte.  If it is a string or a byte then python 3.x introduces a lot of strict typing and syntax checking which will cause a lot of headaches initially; whereas perl converts between strings and bytes quite easily, python does not (because python wants to force data types for unicode strings).

The upshot is to reference just the name (no $name like in perl) and manually keep track of what the argument's type is:

```<code>arg1 = 50
arg2 = 70
myPythonFunc(arg1, arg2)

....
def myPythonFunc(arg1, arg2):
    if (arg1 > arg2):
        return arg2
    ...
</code>```

If you are really destined to use arrays (there's more advantages to using individual arguments because of default values and named args and such though), then:

```<code>args = [ 50, 70 ]
myPythonFunc(args)

....
def myPythonFunc(args):
    if (args[0] > args[1]):
        return args[1]
    ...
</code>```

Read this: http://diveintopython.net/native_data_types/lists.html

OwnerDisplayName: MIT

Title: Scalar Variables from Perl to Python?

Body:
I am translating a program from perl to python and I really don't know how to translate a scalar variable to python. My problem is that I want to call the first value that comes in based on all the scalar variables used in the code, a scalar variable when mentioned it refers to the value assigned to it.

the specific area was

my $min = $_[0];
my $max = $_[1];

So these two variables were assigned a value before hand, now what I am trying to do is call my min and let it be the first value that comes, then I want my max to be called as the second value that comes in. Basically, trying to gather the info that was generated to min and max and now bring it to here. Do not understand how to do this in python.

The thing is that I have 3-5 different values assigned to min and also to max, I dont know how to bring in the value.

i am the one who put the question, but I logged in as i think a temporary user and it got deleted. Thanks!

Body:
I think you're talking about subroutine arguments.  The big diff between perl and python with function calls (in python they are more like methods..) is that python can pass different things as a single argument, as a regular operation, and while perl can do this, it is rare.  So if you are calling a 'function' in python you need to be aware of what the argument 'is'.  Is it an 'array' (list or dict or tuple) or scalar variable or string or a byte.  If it is a string or a byte then python 3.x introduces a lot of strict typing and syntax checking which will cause a lot of headaches initially; whereas perl converts between strings and bytes quite easily, python does not (because python wants to force data types for unicode strings).

The upshot is to reference just the name (no $name like in perl) and manually keep track of what the argument's type is:

arg1 = 50
arg2 = 70
myPythonFunc(arg1, arg2)

....
def myPythonFunc(arg1, arg2):
    if (arg1 > arg2):
        return arg2
    ...

If you are really destined to use arrays (there's more advantages to using individual arguments because of default values and named args and such though), then:

args = [ 50, 70 ]
myPythonFunc(args)

....
def myPythonFunc(args):
    if (args[0] > args[1]):
        return args[1]
    ...

Read this: http://diveintopython.net/native_data_types/lists.html

ContentLicense: CC BY-SA 3.0


问:
java.lang.IllegalAccessError: class org.gradle.internal.compiler.java.ClassNameCollector cannot access class com.sun.tools.javac.code.Symbol$
I'm trying to build the application with Java SE 11 and Gradle 7.0, and it builds using the IDE however when I try to build it using the terminal I get this error. How can I fix it.</p>
```<code>java.lang.IllegalAccessError: class org.gradle.internal.compiler.java.ClassNameCollector (in unnamed module @0x1d7a8227) cannot access class com.sun.tools.javac.code.Symbol$TypeSymbol (in module jdk.compiler) because module jdk.compiler does not export com.sun.tools.javac.code to unnamed module @0x1d7a8227
</code>```

答: Downgrading from open jdk 17 to 11 worked for me.</p>

Body:
I'm trying to build the application with Java SE 11 and Gradle 7.0, and it builds using the IDE however when I try to build it using the terminal I get this error. How can I fix it.

java.lang.IllegalAccessError: class org.gradle.internal.compiler.java.ClassNameCollector (in unnamed module @0x1d7a8227) cannot access class com.sun.tools.javac.code.Symbol$TypeSymbol (in module jdk.compiler) because module jdk.compiler does not export com.sun.tools.javac.code to unnamed module @0x1d7a8227


问:
How to display the most frequently occurring letter and the number of matches using streams?
I have a method that creates a list of random English letters and counts how many times each letter appears in the list. How to display only the letter that occurs most often and how many times does this letter occur in this list?</p>
```<code>public class StreamPractice {

    public static void main(String[] args) {
        System.out.println(mostFrequentlyOccurringLetter());
    }

    private static Map<String, Integer> mostFrequentlyOccurringLetter() {
        return new Random().ints(100, 65, 91)
                .mapToObj(i -> String.valueOf((char) i))
                .collect(Collectors.toMap(Function.identity(), value -> 1, Integer::sum));
    }

}
</code>```

答:
```<code>Map<String, Integer> map = new Random().ints(100, 65, 91)
        .mapToObj(i -> String.valueOf((char) i))
        .collect(Collectors.toMap(Function.identity(), value -> 1, Integer::sum));
map.entrySet().stream().sorted(Map.Entry.<String,Integer>comparingByValue().reversed())
        .findFirst();
</code>```

Body:
I have a method that creates a list of random English letters and counts how many times each letter appears in the list. How to display only the letter that occurs most often and how many times does this letter occur in this list?

public class StreamPractice {

    public static void main(String[] args) {
        System.out.println(mostFrequentlyOccurringLetter());
    }

    private static Map<String, Integer> mostFrequentlyOccurringLetter() {
        return new Random().ints(100, 65, 91)
                .mapToObj(i -> String.valueOf((char) i))
                .collect(Collectors.toMap(Function.identity(), value -> 1, Integer::sum));
    }

}


问:
Integrate AWS XRay HttpClientBuilder with Spring Webclient
I am using Spring Webclient for my microservices for external calls. I am trying to Integrate AWS XRay in our microservices. But to get the traces of Outgoing HTTP calls in xray, I have to use XRay HttpClientBuilder. Is there any way i can integrate XRAY HttpClientBuilder with webclient?</p>

答: XRay java SDK currently only supports downstream HTTP Requests with Apache clients. Alternatively, you can checkout the AWS Distro for OpenTelemetry Java agent (docs), which is a ready-to-use OpenTelemetry auto-instrumentation agent that's compatible with the X-Ray backend and supports Spring WebClient.</p>


问:
How to modify existing claims in JWT from Keycloak for OIDC flow?
I'm generating JWTs for a service for authentication and we're using Keycloak as the OAuth server.

I've set up a realm R, a client C, and a user U. I setup a protocol mapper to include "C" in the "aud". I generated the JWTtoken for U and when I check the payload, I see "aud": ["C", "account"]. Which is great, I wanted C to be present. But I do not want "account" to be present in the "aud".

How do I configure this in keycloak? Similarly, the scope reads - "scope": "email profile test-client-rhs" and I wish to remove "email profile" from it. I've been googling around a lot and trying out different stuff in Keycloak but I can't get this to work somehow.

答:
I generated the JWTtoken for U and when I check the payload, I see
"aud": ["C", "account"]. Which is great, I wanted C to be present. But
I do not want "account" to be present in the "aud".

Instead of an audience Mapper you can use a Hardcoded claim Mapper with:

Token Claim Name set to aud

Claim value set to C

Add to access token set to ON

this mapper will override the original claim "aud": "account" with "aud": "C"

Like so:

(Old Keycloak UI)

(For the NEW Keycloak UI)

Go to the tab Client Scopes

Click on the scope -dedicated (e.g., test-dedicated in my example)

Click on Configure a new mapper

Select Hardcoded claim, and then fill up

Click on Save.

The client will be the client that you are using to authenticate against.

How do I configure this in keycloak? Similarly, the scope reads -
"scope": "email profile test-client-rhs" and I wish to remove "email
profile" from it.

For this you need to go to:

The realm where the client is

Go to clients and select the client

Click on the tab "Client Scopes"

(For the Old Keycloak UI)

Remove the scopes email and profile from "Assigned Default Client Scopes"

like so:

(For the NEW Keycloak UI)

change the scopes email and profile from Default to Optional, Like so:


问:
Working with Forms (POST request to REST API) in Flutter
I have decent backend/frontend experience, but I'm new to Flutter.

I looked at a lot of tutorials, but didn't come up with anything :(

the tutorials do not use the latest flutter_bloc (<7-8), and the logic structure is fundamentally different there

the tutorials cover simple actions (clicked on the button - received data from the REST API), but does not say how to interact with forms that send POST / GET data

the tutorials show how to create a model based on JSON, but what if the JSON structure is different depending on the validation on the backend?

What I want to achieve (using flutter_bloc 8):

When clicking on "Create post" send a POST request (REST API)

If JSON response is status = 'error' - display errors in each field (TextFormField/decoration/errorText:<error_message>)

If the JSON response is status = 'success' - go to another screen and display the post from data (post_id, title, content).

P.S. I know that it is possible to validate data without sending a request to the API, but I want to understand the mechanism of how the field is converted (when we forward the data from the JSON response to the errorText).

If someone has time to show step by step how to do this - I would be very grateful, like many other beginners.

JSON structure (status='error'):

```<code>{
   "status":"error",
   "errors":{
      "title":[
         "Title can't be empty"
      ],
      "content":[
         "Post content can't be empty"
      ]
   }
}
</code>```

JSON structure (status='success'):

```<code>{
   "status":"success",
   "data":{
      "post_id":321,
      "title":"Test title",
      "content":"Test content"
   }
}
</code>```

create_post_screen.dart

```<code>import 'package:flutter/material.dart';

class CreatePostScreen extends StatelessWidget {
  const CreatePostScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(15.0),
          child: Form(
            child: Column(
              children: [
                TextFormField(
                  decoration: const InputDecoration(
                    hintText: 'Post title',
                  ),
                ),
                TextFormField(
                  decoration: const InputDecoration(
                    hintText: 'Post content',
                  ),
                  minLines: 5,
                  maxLines: null,
                ),
                ElevatedButton(
                  child: const Text('Create post'),
                  onPressed: () {},
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
</code>```

Initial screen

Display errors from API response (if status='error')

答:
Create a status field for your state maybe something like this

```<code>    enum LoadingStatus {
        loading,
        idle,
        error,
        success
    }

    class Status {
        final LoadingStatus status;
        final String error;

        Status(this.status, this.error);
     }
</code>```

Create a state with a statuses map and the key would be the textfield's title so {'post title': Status}

```<code>class CreatePostState {
  const CreatePostState(this.statuses);

  final Map<String, Status> statuses;
  //and whatever fields you need
  CreatePostState copyWith(
      {Map<String, Status> statuses}){
        return CreatePostState(statuses);
      }
}
</code>```

Your bloc event would look something like this

```<code>    try {
      statuses = state.statuses;
      statuses['Post Title'] = Status(LoadingStatus.loading);
      emit(CreatePostState(statuses));
      await api.call()
      statuses['Post Title'] = Status(LoadingStatus.success);
      emit(CreatePostState(statuses));
    } catch (e) {
      statuses['Post Title'] = Status(LoadingStatus.error);
      emit(CreatePostState(statuses));

    }
</code>```

add BlocProvider and BlocBuilder as parent to Scaffold

Body:
I have decent backend/frontend experience, but I'm new to Flutter.

I looked at a lot of tutorials, but didn't come up with anything :(

the tutorials do not use the latest flutter_bloc (<7-8), and the logic structure is fundamentally different there

the tutorials cover simple actions (clicked on the button - received data from the REST API), but does not say how to interact with forms that send POST / GET data

the tutorials show how to create a model based on JSON, but what if the JSON structure is different depending on the validation on the backend?

What I want to achieve (using flutter_bloc 8):

When clicking on "Create post" send a POST request (REST API)

If JSON response is status = 'error' - display errors in each field (TextFormField/decoration/errorText:<error_message>)

If the JSON response is status = 'success' - go to another screen and display the post from data (post_id, title, content).

P.S. I know that it is possible to validate data without sending a request to the API, but I want to understand the mechanism of how the field is converted (when we forward the data from the JSON response to the errorText).

If someone has time to show step by step how to do this - I would be very grateful, like many other beginners.

JSON structure (status='error'):

{
   "status":"error",
   "errors":{
      "title":[
         "Title can't be empty"
      ],
      "content":[
         "Post content can't be empty"
      ]
   }
}

JSON structure (status='success'):

{
   "status":"success",
   "data":{
      "post_id":321,
      "title":"Test title",
      "content":"Test content"
   }
}

create_post_screen.dart

import 'package:flutter/material.dart';

class CreatePostScreen extends StatelessWidget {
  const CreatePostScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(15.0),
          child: Form(
            child: Column(
              children: [
                TextFormField(
                  decoration: const InputDecoration(
                    hintText: 'Post title',
                  ),
                ),
                TextFormField(
                  decoration: const InputDecoration(
                    hintText: 'Post content',
                  ),
                  minLines: 5,
                  maxLines: null,
                ),
                ElevatedButton(
                  child: const Text('Create post'),
                  onPressed: () {},
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Initial screen

Display errors from API response (if status='error')

Body:
Create a status field for your state maybe something like this

    enum LoadingStatus {
        loading,
        idle,
        error,
        success
    }

    class Status {
        final LoadingStatus status;
        final String error;

        Status(this.status, this.error);
     }

Create a state with a statuses map and the key would be the textfield's title so {'post title': Status}

class CreatePostState {
  const CreatePostState(this.statuses);

  final Map<String, Status> statuses;
  //and whatever fields you need
  CreatePostState copyWith(
      {Map<String, Status> statuses}){
        return CreatePostState(statuses);
      }
}

Your bloc event would look something like this

    try {
      statuses = state.statuses;
      statuses['Post Title'] = Status(LoadingStatus.loading);
      emit(CreatePostState(statuses));
      await api.call()
      statuses['Post Title'] = Status(LoadingStatus.success);
      emit(CreatePostState(statuses));
    } catch (e) {
      statuses['Post Title'] = Status(LoadingStatus.error);
      emit(CreatePostState(statuses));

    }

add BlocProvider and BlocBuilder as parent to Scaffold


问:
Most useful animation in web or desktop application
Many animation effects are simply gratuitous eye candy -- however, there are situations where animations effectively communicate to the user what's going on.
What are some of your favorite uses for animations, and what specific animation type would you use?

E.g.: Animate items downwards when a new item is inserted into a list

答:
I believe that all visual changes should not be swift. Be it status notification, window maximized/minimized, or data deleted/added. I cannot find a reference, but usually it is recommended that all animations should not be around 1-2 seconds, matching human's response time.

My favorite uses of animation is not in a commercial software (though Apple is good at this) but a research paper called Phosphor which I consider one of the great UI ideas that have not yet implemented into major operating systems.

OwnerDisplayName: Jen

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: puri


问:
C++: Is it a bad idea to use the value of a function returning shared_ptr directly?
For example:

```<code>boost::shared_ptr<int> test() {
    boost::shared_ptr<int> x(new int(3));
    return x;
}

void function() {
    int y = *test();
    ...
}
</code>```

Is it also a bad idea to use shared_ptr to avoid copying the whole object? Like a vector of matrices/images for example.

答:
In your example, that's fine, since you're making a copy of the int.

If you get the int as a reference, then after that line, it would be a dangling reference, since the shared pointer would go out of scope, deleting its target.

Is it also a bad idea to use shared_ptr to avoid copying the whole object? Like a vector of matrices/images for example.

Using shared_ptr will avoid copying just as using a naked pointer will avoid copying - decide whether you want to avoid copying (first), and then choose which sort of pointer you should use.

For a vector of matrices or images, you may want to use a std::vector of boost::shared_ptr, or a boost::ptr_vector, or some other container that makes the memory management easy for you.

Body:
For example:

boost::shared_ptr<int> test() {
    boost::shared_ptr<int> x(new int(3));
    return x;
}

void function() {
    int y = *test();
    ...
}

Is it also a bad idea to use shared_ptr to avoid copying the whole object? Like a vector of matrices/images for example.


问:
Basic routing in Laravel gives me a 404 error
I'm trying to do basic routing using Laravel. But when I click on the link, the page displays a 404 error even though it was working earlier. I've made a folder that contains all the Blade files.

Blade

```<code><a href="agenda/lack-of-water" class="text-decoration-none text-dark">
    Lack of Water
</a>
</code>```

Controller

```<code>public function water()
{
    // ...
    return view('agenda.lack-of-water');
}
</code>```

Routes

```<code>Route::get('agenda/lack-of-water', 'App\Http\Controller\AgendazController@water')
    ->name('agenda/lack-of-water');
</code>```

答: I figured it out. I had to use a different controller as I was using AgendazController instead of AgendaController</p>

Body:
I'm trying to do basic routing using Laravel. But when I click on the link, the page displays a 404 error even though it was working earlier. I've made a folder that contains all the Blade files.

Blade

    Lack of Water

Controller

public function water()
{
    // ...
    return view('agenda.lack-of-water');
}

Routes

Route::get('agenda/lack-of-water', 'App\Http\Controller\AgendazController@water')
    ->name('agenda/lack-of-water');


问:
Why is my html displaying a snippet of js as body text?
I wanna preface this by saying I'm very new at this and learning as I go so there may be several mistakes in this and I'm open to all helpful feedback!

I created this bit of animated text forked from a codepen pen using a combo of html/css/js and it's running exactly as it should be, except a little while after the animated text finishes loading, it adds a portion of my nested js as visible html text. I think it has something to do with a rogue unclosed ">" somewhere because the portion of js that it's mistakenly displaying exists between two unrelated ">" and "<". Can anyone explain why this is happening? TIA! full code is as follows:

<!DOCTYPE html>

    <meta charset='UTF-8'/>

     hmmm
     seems I've gotten myself all turned around...
     could've sworn the road was back that way...
     I guess uncertainty seems appropriate
     for matters of this world
     only thing I can really be certain of these days
     is that I'm so-and-so and I exist
     anyhow, looking back is a bad habit, y'know
     while we're both here,
     might as well take a look around...
     ...well?
     you gonna do somethin'?
     or are you just gonna stand there and bleed?<type>

```

答:
<!DOCTYPE html>

    <meta charset='UTF-8'/>

     hmmm
     seems I've gotten myself all turned around...
     could've sworn the road was back that way...
     I guess uncertainty seems appropriate
     for matters of this world
     only thing I can really be certain of these days
     is that I'm so-and-so and I exist

     anyhow, looking back is a bad habit, y'know
     while we're both here,
     might as well take a look around...
     ...well?
     you gonna do somethin'?
     or are you just gonna stand there and bleed?```
</body>
  <script type="text/javascript">

            function setupTypewriter(t) {
        var HTML = t.innerHTML;

        t.innerHTML = "";

        var cursorPosition = 0,
            tag = "",
            writingTag = false,
            tagOpen = false,
            typeSpeed = 105,
          tempTypeSpeed = 0;

        var linePause = 1500;

        var type = function() {

            if (writingTag === true) {
                tag += HTML[cursorPosition];
            }

            if (HTML[cursorPosition] === "<") {
                tempTypeSpeed = 0;
                if (tagOpen) {
                    tagOpen = false;
                    writingTag = true;
                } else {
                    tag = "";
                    tagOpen = true;
                    writingTag = true;
                    tag += HTML[cursorPosition];
                }
            }
            if (!writingTag && tagOpen) {
                tag.innerHTML += HTML[cursorPosition];
            }
            if (!writingTag && !tagOpen) {
                if (HTML[cursorPosition] === " ") {
                    tempTypeSpeed = 0;
                }
                else if (HTML[cursorPosition] === "\n")
                  {
                    console.log("newline detected");
                    tempTypeSpeed = linePause;
                  }
                else {
                    tempTypeSpeed = (Math.random() * typeSpeed) + 0;
                }
                t.innerHTML += HTML[cursorPosition];
            }
            if (writingTag === true && HTML[cursorPosition] === ">") {
                tempTypeSpeed = (Math.random() * typeSpeed) + 0;
                writingTag = false;
                if (tagOpen) {
                    var newSpan = document.createElement("span");
                    t.appendChild(newSpan);
                    newSpan.innerHTML = tag;
                    tag = newSpan.firstChild;
                }
            }

            cursorPosition += 1;
            if (cursorPosition < HTML.length - 1) {
                setTimeout(type, tempTypeSpeed);
            }

        };
              return {
            type: type
        };
    }

    var typer = document.getElementById('typewriter');

    typewriter = setupTypewriter(typewriter);

    typewriter.type();
      </script>
</html></code>```

Body:
<!DOCTYPE html>
<html lang='en'>
  <head>
    <meta charset='UTF-8'/>
    <style type="text/css">

        .var-highlight{
          color: #07573e; font-style: italic;
        }
        .string-highlight{
          color: rgba(253, 149, 90, 0.8);
        }

        #typewriter{
            font-size: 0.7em;
            margin: 0;
            font-family: "Courier New";

            &:after{
              animation: blink 500ms linear infinite alternate;
            }
        }

        @-webkit-keyframes blink{
          0%{opacity: 0;}
          100%{opacity: 1;}
        }

        @-moz-keyframes blink{
          0%{opacity: 0;}
          100%{opacity: 1;}
        }

        @keyframes blink{
          0%{opacity: 0;}
          100%{opacity: 1;}
        }

    </style>
  </head>
  <body>
        <pre id="typewriter">
    <span> hmmm
     seems I've gotten myself all turned around...
     could've sworn the road was back that way...
     I guess uncertainty seems appropriate
     for matters of this world
     only thing I can really be certain of these days
     is that</span> <span class="var-highlight">I'm so-and-so and I exist</span>
     <span>
     anyhow, looking back is a bad habit, y'know
     while we're both here,
     might as well take a look around...
     ...well?
     you gonna do somethin'?
     or are you just gonna stand there and bleed?</span></pre>
</body>
  <script type="text/javascript">

            function setupTypewriter(t) {
        var HTML = t.innerHTML;

        t.innerHTML = "";

        var cursorPosition = 0,
            tag = "",
            writingTag = false,
            tagOpen = false,
            typeSpeed = 105,
          tempTypeSpeed = 0;

        var linePause = 1500;

        var type = function() {

            if (writingTag === true) {
                tag += HTML[cursorPosition];
            }

            if (HTML[cursorPosition] === "<") {
                tempTypeSpeed = 0;
                if (tagOpen) {
                    tagOpen = false;
                    writingTag = true;
                } else {
                    tag = "";
                    tagOpen = true;
                    writingTag = true;
                    tag += HTML[cursorPosition];
                }
            }
            if (!writingTag && tagOpen) {
                tag.innerHTML += HTML[cursorPosition];
            }
            if (!writingTag && !tagOpen) {
                if (HTML[cursorPosition] === " ") {
                    tempTypeSpeed = 0;
                }
                else if (HTML[cursorPosition] === "\n")
                  {
                    console.log("newline detected");
                    tempTypeSpeed = linePause;
                  }
                else {
                    tempTypeSpeed = (Math.random() * typeSpeed) + 0;
                }
                t.innerHTML += HTML[cursorPosition];
            }
            if (writingTag === true && HTML[cursorPosition] === ">") {
                tempTypeSpeed = (Math.random() * typeSpeed) + 0;
                writingTag = false;
                if (tagOpen) {
                    var newSpan = document.createElement("span");
                    t.appendChild(newSpan);
                    newSpan.innerHTML = tag;
                    tag = newSpan.firstChild;
                }
            }

            cursorPosition += 1;
            if (cursorPosition < HTML.length - 1) {
                setTimeout(type, tempTypeSpeed);
            }

        };
              return {
            type: type
        };
    }

    var typer = document.getElementById('typewriter');

    typewriter = setupTypewriter(typewriter);

    typewriter.type();
      </script>
</html>