问:
Create GSI on an attribute which has the value of Set
So i want to create a simple Dynamodb table called reminders which at the moment has 3 columns :

reminder_id : This is the hash key

reminder_tag: I want to have a global secondary index on this field . But at the same time i want to ensure that the tags attribute should have the datatype of Set . Because there can be multiple tags on a reminder.

reminder_title: I also want to have a global secondary index on this field. This will be a string field.

I checked the documentation : https://boto3.amazonaws.com/v1/documentation/api/latest/reference/customizations/dynamodb.html#valid-dynamodb-types on what are the possible datatypes available in Boto3 .

So i have come up with this script :

```<code>import boto3

def create_reminders_table():
    """Just create the reminders table."""
    session = boto3.session.Session(profile_name='dynamo_local')
    dynamodb = session.resource('dynamodb', endpoint_url="http://localhost:8000")
    table = dynamodb.create_table(
        TableName='Reminders',
        KeySchema=[
            {
                'AttributeName': 'reminder_id',
                'KeyType': 'HASH'
            }
        ],
        AttributeDefinitions=[
            {
                'AttributeName': 'reminder_id',
                'AttributeType': 'S'
            },
            {
                'AttributeName': 'reminder_tag',
                'AttributeType': 'SS'
            },
            {
                'AttributeName': 'reminder_title',
                'AttributeType': 'S'
            }
        ],
        GlobalSecondaryIndexes=[
            {
                'IndexName': 'ReminderTagGsi',
                'KeySchema': [
                    {
                        'AttributeName': 'reminder_tag',
                        'KeyType': 'HASH'
                    }
                ],
                'Projection': {
                    'ProjectionType': 'INCLUDE',
                    'NonKeyAttributes': [
                        'reminder_title'
                    ]
                }
            },
            {
                'IndexName': 'ReminderTitleGsi',
                'KeySchema': [
                    {
                        'AttributeName': 'reminder_title',
                        'KeyType': 'HASH'
                    }
                ],
                'Projection': {
                    'ProjectionType': 'KEYS_ONLY'
                }
            }
        ],
        BillingMode='PAY_PER_REQUEST'
    )
    return table

if __name__ == '__main__':
    movie_table = create_reminders_table()
    print("Table status:", movie_table.table_status)
</code>```

But when i run this i get the below issue:

```<code>botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the CreateTable operation: Member must satisfy enum value set: [B, N, S]
</code>```

I searched and came across this question asked by someone which has the same issue : https://forums.aws.amazon.com/thread.jspa?messageID=613970

Can someone please help me with this since the solution of not providing a datatype either does not work .

Also is it possible to have an index on a an attribute which is of value Set ? I mean i should enable the user to search for reminders with a tag , and for doing that i need to have a set.

Request someone to please help me regarding this.

答:
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html

“Each primary key attribute must be a scalar (meaning that it can hold only a single value). The only data types allowed for primary key attributes are string, number, or binary. There are no such restrictions for other, non-key attributes.”

Body:
So i want to create a simple Dynamodb table called reminders which at the moment has 3 columns :

reminder_id : This is the hash key

reminder_tag: I want to have a global secondary index on this field . But at the same time i want to ensure that the tags attribute should have the datatype of Set . Because there can be multiple tags on a reminder.

reminder_title: I also want to have a global secondary index on this field. This will be a string field.

I checked the documentation : https://boto3.amazonaws.com/v1/documentation/api/latest/reference/customizations/dynamodb.html#valid-dynamodb-types on what are the possible datatypes available in Boto3 .

So i have come up with this script :

import boto3

def create_reminders_table():
    """Just create the reminders table."""
    session = boto3.session.Session(profile_name='dynamo_local')
    dynamodb = session.resource('dynamodb', endpoint_url="http://localhost:8000")
    table = dynamodb.create_table(
        TableName='Reminders',
        KeySchema=[
            {
                'AttributeName': 'reminder_id',
                'KeyType': 'HASH'
            }
        ],
        AttributeDefinitions=[
            {
                'AttributeName': 'reminder_id',
                'AttributeType': 'S'
            },
            {
                'AttributeName': 'reminder_tag',
                'AttributeType': 'SS'
            },
            {
                'AttributeName': 'reminder_title',
                'AttributeType': 'S'
            }
        ],
        GlobalSecondaryIndexes=[
            {
                'IndexName': 'ReminderTagGsi',
                'KeySchema': [
                    {
                        'AttributeName': 'reminder_tag',
                        'KeyType': 'HASH'
                    }
                ],
                'Projection': {
                    'ProjectionType': 'INCLUDE',
                    'NonKeyAttributes': [
                        'reminder_title'
                    ]
                }
            },
            {
                'IndexName': 'ReminderTitleGsi',
                'KeySchema': [
                    {
                        'AttributeName': 'reminder_title',
                        'KeyType': 'HASH'
                    }
                ],
                'Projection': {
                    'ProjectionType': 'KEYS_ONLY'
                }
            }
        ],
        BillingMode='PAY_PER_REQUEST'
    )
    return table

if __name__ == '__main__':
    movie_table = create_reminders_table()
    print("Table status:", movie_table.table_status)

But when i run this i get the below issue:

botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the CreateTable operation: Member must satisfy enum value set: [B, N, S]

I searched and came across this question asked by someone which has the same issue : https://forums.aws.amazon.com/thread.jspa?messageID=613970

Can someone please help me with this since the solution of not providing a datatype either does not work .

Also is it possible to have an index on a an attribute which is of value Set ? I mean i should enable the user to search for reminders with a tag , and for doing that i need to have a set.

Request someone to please help me regarding this.


来源: stackexchange

问:
Are there any JavaScript static analysis tools?
I'm used to having my compiler complain when I do something stupid like a typo on a variable name but JavaScript has a habit of letting this pass.

Are there any static analysis tools for JavaScript?

答:
I agree that JSLint is the best place to start.  Note that JavaScript Lint is distinct from JSLint.  I’d also suggest checking out JSure, which in my limited testing did better than either of them, though with some rough edges in the implementation—the Intel Mac version crashed on startup for me, though the PowerPC version ran fine even on Intel, and the Linux version ran fine as well.  (The developer, Berke Durak, said he'd get back to me when this was fixed, but I haven't heard from him.)

Don’t expect as much from JavaScript static analysis as you get from a good C checker.  As Durak told me, “any non-trivial analysis is very difficult due to Javascript's dynamic nature.”

(Another, even more obscure Mac-only bug, this time with JSLint’s Konfabulator widget:  Dragging a BBEdit document icon onto the widget moves the document to the trash.  The developer, Douglas Crockford, hadn’t tried the widget on a Mac.)

10 August 2009:  Today at the Static Analysis Symposium, Simon Holm Jensen presented a paper on TAJS: Type Analyzer for JavaScript, written with Anders Møller and Peter Thiemann.  The paper doesn’t mention the above tools, but Jensen told me he’d looked at some of them and wasn’t impressed.  The code for TAJS should be available sometime this summer.

OwnerDisplayName: Mat

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Flash Sheridan


问:
Stenciljs having troubles testing emitted event with Jest
I'm writing an input component using stencil and I'm having troubles testing the emitted event which is fired on a click or enter key press.
The component:

```<code>    export class Input {
    .
    .
      private inputRef?: HTMLInputElement;
      @Event() inputEvent: EventEmitter<{}>;
    .
    .
    render() {
     return (
      <div class="status">
          <div class="input-wrapper">
            <input onKeyUp = {event => this.handleKeyDown(event)} ref={el => this.inputRef = el as HTMLInputElement}/>
          </div>
      </div>);
     }
      private handleKeyDown(e: KeyboardEvent): void {
        this.dispatchSearchEvent(e);
      }

      private dispatchSearchEvent(e){
        this.inputEvent.emit({type: "event-name", event: e, data: (this.inputRef as HTMLInputElement).value});
      }
    }
</code>```

conponent.spec.jsx:

```<code>  it('fires an event upon enter key press', async () => {
    const component = new InputFields();
    jest.spyOn(component, 'event-name');

      const keyUpEvent = new Event("keyup", {
        key: "enter",
        keyCode: 13,
        which: 13,
        shiftKey: false,
        ctrlKey: false,
        metaKey: false
      });

      keyUpEvent.target = {value: "some input value"}
      component.handleKeyDown(keyUpEvent);

      component.inputEvent = { emit: jest.fn().mockReturnValue(Promise.resolve()), };

      expect(component.inputEvent.emit).toHaveBeenCalled();
  });
</code>```

Having an error:

```<code>Cannot spy the event-name property because it is not a function; undefined given instead

  356 |   it('fires an event upon enter key press', async () => {
  357 |     const component = new Input();
> 358 |     jest.spyOn(component, 'event-name');
      |          ^
  359 |
  360 |       const keyUpEvent = new Event("keyup", {
  361 |         key: "enter",
</code>```

答:
The error message is trying to tell you that your Input component does not have a function named event-name. spyOn is for spying on functions not events.

In E2E testing you can use E2EElement.spyOnEvent for events:

```<code>const page = await newE2EPage({html: '<my-input></my-input>'});
const component = await page.find('my-input');
const spy = await component.spyOnEvent('inputEvent');
await component.type('x');
expect(spy).toHaveReceivedEventTimes(1);
expect(spy.firstEvent.detail.data).toBe('x');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm writing an input component using stencil and I'm having troubles testing the emitted event which is fired on a click or enter key press.
The component:

    export class Input {
    .
    .
      private inputRef?: HTMLInputElement;
      @Event() inputEvent: EventEmitter<{}>;
    .
    .
    render() {
     return (

            <input onKeyUp = {event => this.handleKeyDown(event)} ref={el => this.inputRef = el as HTMLInputElement}/>

);
     }
      private handleKeyDown(e: KeyboardEvent): void {
        this.dispatchSearchEvent(e);
      }

      private dispatchSearchEvent(e){
        this.inputEvent.emit({type: "event-name", event: e, data: (this.inputRef as HTMLInputElement).value});
      }
    }

conponent.spec.jsx:

  it('fires an event upon enter key press', async () => {
    const component = new InputFields();
    jest.spyOn(component, 'event-name');

      const keyUpEvent = new Event("keyup", {
        key: "enter",
        keyCode: 13,
        which: 13,
        shiftKey: false,
        ctrlKey: false,
        metaKey: false
      });

      keyUpEvent.target = {value: "some input value"}
      component.handleKeyDown(keyUpEvent);

      component.inputEvent = { emit: jest.fn().mockReturnValue(Promise.resolve()), };

      expect(component.inputEvent.emit).toHaveBeenCalled();
  });

Having an error:

Cannot spy the event-name property because it is not a function; undefined given instead

  356 |   it('fires an event upon enter key press', async () => {
  357 |     const component = new Input();
> 358 |     jest.spyOn(component, 'event-name');
      |          ^
  359 |
  360 |       const keyUpEvent = new Event("keyup", {
  361 |         key: "enter",

Body:
The error message is trying to tell you that your Input component does not have a function named event-name. spyOn is for spying on functions not events.

In E2E testing you can use E2EElement.spyOnEvent for events:

const page = await newE2EPage({html: '<my-input></my-input>'});
const component = await page.find('my-input');
const spy = await component.spyOnEvent('inputEvent');
await component.type('x');
expect(spy).toHaveReceivedEventTimes(1);
expect(spy.firstEvent.detail.data).toBe('x');


问:
using same variable that is created in function into another function
I want to use 'number' variable that was created out of the function and use it in  couple functions and also give it an initial value 0, but it gives "local variable 'number' referenced before assignment" error at the last line of code.How could I fix it?Thanks in advance.</p>
```<code>lst_img=[img0,img1,img2,img3,img4]
number=0

def go_forward():

    global number
    number+=1
    shwimage.grid_forget()
    global shwimage1
    shwimage1=Label(image=lst_img[number])
    shwimage1.grid(row=0,column=0,columnspan=3)

def go_back():

   if number==0:
      shwimage.grid_forget()
   shwimage1.grid_forget()
   shwimage2=Label(image=lst_img[number-1])
   shwimage2.grid(row=0,column=0,columnspan=3)
   number-=1  # local variable 'number' referenced before assignment
</code>```

答:
A reason you get the error, local variable 'number' referenced before assignment, is you did not used global keyword to declare that you will use THE number variable even in go_back().

A simple solution is to use global in the go_back(), as follows:

```<code>def go_back():
   global number # -> as you did in `go_forward()`.
   if number==0:
      shwimage.grid_forget()
   shwimage1.grid_forget()
   shwimage2=Label(image=lst_img[number-1])
   shwimage2.grid(row=0,column=0,columnspan=3)
   number-=1  # local variable 'number' referenced before assignment
</code>```

However, you need to play it safe when using global because it makes hard to track variable changes. Instead, it would be better to pass number value as an argument in the functions.

For more information to use global keyword, see an answer of the question here: Why are global variables evil?

In addition, I recommend you to read this article, Alternatives to Using Globals in Python

Body:
I want to use 'number' variable that was created out of the function and use it in  couple functions and also give it an initial value 0, but it gives "local variable 'number' referenced before assignment" error at the last line of code.How could I fix it?Thanks in advance.

lst_img=[img0,img1,img2,img3,img4]
number=0

def go_forward():

    global number
    number+=1
    shwimage.grid_forget()
    global shwimage1
    shwimage1=Label(image=lst_img[number])
    shwimage1.grid(row=0,column=0,columnspan=3)

def go_back():

   if number==0:
      shwimage.grid_forget()
   shwimage1.grid_forget()
   shwimage2=Label(image=lst_img[number-1])
   shwimage2.grid(row=0,column=0,columnspan=3)
   number-=1  # local variable 'number' referenced before assignment

Body:
A reason you get the error, local variable 'number' referenced before assignment, is you did not used global keyword to declare that you will use THE number variable even in go_back().

A simple solution is to use global in the go_back(), as follows:

def go_back():
   global number # -> as you did in `go_forward()`.
   if number==0:
      shwimage.grid_forget()
   shwimage1.grid_forget()
   shwimage2=Label(image=lst_img[number-1])
   shwimage2.grid(row=0,column=0,columnspan=3)
   number-=1  # local variable 'number' referenced before assignment

However, you need to play it safe when using global because it makes hard to track variable changes. Instead, it would be better to pass number value as an argument in the functions.

For more information to use global keyword, see an answer of the question here: Why are global variables evil?

In addition, I recommend you to read this article, Alternatives to Using Globals in Python


问:
SQL determine business days passed since beginning of month using calendar table
I have a calendar table with all dates and a column indicating whether its a business day.

For example

Date
Business_Day

1/1/2021
False

1/2/2021
False

1/3/2021
True

...
I have another table with dates and would like to determine how many business days have elapsed since the beginning of that month.
For example:

Date
Business_Days_Passed

1/1/2022
0

1/2/2022
0

1/3/2022
1

1/4/2022
2

1/15/2022
10

2/2/2022
2

2/11/2022
9

2/12/2022
9

Is there a way to do this using standard sql?  I was thinking of creating some kind of UDF but there may be an easier way?  This using snowflake so there is access to all common date functions and window/udf functions

答:
I think you can accomplish this with a simple join and a window function. I am assuming your date is formatted yyyy-mm-dd which would allow left(date,7) to get the year-month. If not, just use a different function to extract year-month for aggregating per month.

```<code>select a.date,
       count(b.business_day) over (partition by left(a.date,7) order by a.date) business_days_elapsed
from table a
     left join calendar_table b on a.date=b.date and b.business_day='True'
group by a.date, b.business_day; --in case your data is not deduped before window function is applied
</code>```

Body:
I think you can accomplish this with a simple join and a window function. I am assuming your date is formatted yyyy-mm-dd which would allow left(date,7) to get the year-month. If not, just use a different function to extract year-month for aggregating per month.

select a.date,
       count(b.business_day) over (partition by left(a.date,7) order by a.date) business_days_elapsed
from table a
     left join calendar_table b on a.date=b.date and b.business_day='True'
group by a.date, b.business_day; --in case your data is not deduped before window function is applied


问:
Cannot access emit property while testing click event on Vue 3
I'm new to testing and I'm trying to test a component with Vue test-utils, but I'm having trouble when I try to test a click on a imported component.

This is my test file:

  import { Table, Input } from 'ant-design-vue';
  import { CheckOutlined, EditOutlined } from '@ant-design/icons-vue';

  import { shallowMount } from '@vue/test-utils';
  let wrapper;
  beforeEach(() => {
    wrapper = shallowMount(TableEditable, {
      global: {
        components: {
          'a-table': Table,
          'a-input': Input,
          'check-outlined': CheckOutlined,
          'edit-outlined': EditOutlined,
        }
      },
      emits: ['edit', 'save'],
      props: {
        tableData: {
          "data":[
            {"id":"0","monday":"0"}],
          "columns":[
            {"title":"Mon","dataIndex":"monday","slots":{"customRender":"monday"}}]
        },
        dataSrc: [{"id":"0","monday":"0","tuesday":"0","wednesday":"0","thursday":"0","friday":"0","saturday":"9","sunday":"10","key":"0"}]
      }
    })
  })

  describe('first test', () => {
    it('first test: check if theres a class name', () => {
      expect(wrapper.classes()).toContain('tableEditable')
    })
    it('click and emit buttons', async () => {
        await wrapper.findComponent({ref: 'edit-outlined'})
        await wrapper.trigger('click')
        expect(wrapper.emitted()).toHaveProperty('edit')

      })
  })
```
<p>This is my component:</p>
<pre class="lang-html prettyprint-override"><code>  <template>
     <a-table bordered :data-source="dataSrc" :columns="tableData.columns" :pagination="false" class="tableEditable">
      <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]="{ column, text, record }" :key="col">
        <div class="editable-cell">
          <div v-if="editableTableData[record.key + '|' + column.key] !== undefined" class="editable-cell-input-wrapper">
            <a-input v-model:value="editableTableData[record.key + '|' + column.key]" @pressEnter="save(record.key, column.key)" type="number" />
            <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>
    </a-table>
  </template>
  <script>

  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,
      tableData: Object,
      dataSrc: Array,
      editableDataProp: Object
    },
    emits: ['edit', 'save'],
    components: {
      CheckOutlined,
      EditOutlined,
      InputMultipleButton
    },
    data(){
      return {
        editableTableData: this.editableDataProp
      }
    },
    methods: {
      edit(row, column) {
        this.$emit('edit', row, column)
      },
      save(row, column) {
        this.$emit('save', row, column)
      }
    }
  }
  </script>
  <style>
</code>```

And this is the error I get when I run npm test

```<code>  > vue-cli-service test:unit "TableEditable.spec.js"

   FAIL  tests/unit/components/crudForm/TableEditable.spec.js
    checkbox first tests
    ✓ first test: check if theres a class name (18ms)
    ✕ click and emit buttons (7ms)

    ● checkbox first tests › click and emit buttons

    expect(received).toHaveProperty(path)

    Expected path: "edit"
    Received path: []

    Received value: {"click": [[{"isTrusted": false}]]}

      38 |       // await wrapper.vm.$nextTick()
      39 |       await wrapper.trigger('click')
    > 40 |       expect(wrapper.emitted()).toHaveProperty('edit')
       |                     ^
      41 |
      42 |     })
      43 | })

      at Object.<anonymous> (tests/unit/components/crudForm/TableEditable.spec.js:40:39)

  Test Suites: 1 failed, 1 total
  Tests:     1 failed, 1 passed, 2 total
  Snapshots: 0 total
  Time:      4.653s
  Ran all test suites matching /TableEditable.spec.js/i.
</code>```

As I said, sorry if this is a simple error but I'm starting to learn tests so I don't have a lot of experience. If someone needs more information please let me know. Thanks in advance!

答:
As far as I can tell expect(wrapper.emitted()).toHaveProperty('edit') should work.

So I think the issue is that the click is not working as you expect

you have

await wrapper.findComponent({ref: 'edit-outlined'})
await wrapper.trigger('click')
```
<p>which will</p>
<ul>
<li>find the <code>edit-outlined</code> button in the wrapper</li>
<li>click on the component/wrapper (NOT the button)</li>
</ul>
<p>to fix that, you can try chaining it like this:</p>
<pre class="lang-js prettyprint-override"><code>await wrapper
  .findComponent({ref: 'edit-outlined'})
  .trigger('click');
</code>```

The trigger here is assigned to the result of findComponent

Update

I believe wrapper.findComponent({ref: 'edit-outlined'}) is not finding the component. When using ref it will look for components that have that value in the ref attribute.

you have

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

```
<p><code>edit-outlined</code> is the name/type of the component, and not a ref.</p>
<p>you could change it to</p>
<pre class="lang-html prettyprint-override"><code><div v-else class="editable-cell-text-wrapper">
  {{ text || ' ' }}
  <edit-outlined ref="edit-outlined" class="editable-cell-icon" @click="edit(record.key, column.key)" />
</div>
</code>```

which would put it into this.$refs internal object (this.$refs['edit-outlined'] specifically) which would make it accessible using  wrapper.findComponent({ref: 'edit-outlined'}).

You should also be able to change the way you target that element which should make it work without changing the code you are testing.

findcomponent has three type you can pass as the selector argument.

{Component|ref|string} selector

If you only have one instance or EditOutlined, you can target that using the Component type like this:

const btn = wrapper.findComponent(EditOutlined);
expect(btn.exists()).toBe(true);
await btn.trigger('click');
```

also, it's a good idea to add these: expect(btn.exists()).toBe(true); They also act as a "sanity test" and make sure when you get an error that you are looking in the right place.

Body:
I'm new to testing and I'm trying to test a component with Vue test-utils, but I'm having trouble when I try to test a click on a imported component.

This is my test file:

  import { Table, Input } from 'ant-design-vue';
  import { CheckOutlined, EditOutlined } from '@ant-design/icons-vue';

  import { shallowMount } from '@vue/test-utils';
  let wrapper;
  beforeEach(() => {
    wrapper = shallowMount(TableEditable, {
      global: {
        components: {
          'a-table': Table,
          'a-input': Input,
          'check-outlined': CheckOutlined,
          'edit-outlined': EditOutlined,
        }
      },
      emits: ['edit', 'save'],
      props: {
        tableData: {
          "data":[
            {"id":"0","monday":"0"}],
          "columns":[
            {"title":"Mon","dataIndex":"monday","slots":{"customRender":"monday"}}]
        },
        dataSrc: [{"id":"0","monday":"0","tuesday":"0","wednesday":"0","thursday":"0","friday":"0","saturday":"9","sunday":"10","key":"0"}]
      }
    })
  })

  describe('first test', () => {
    it('first test: check if theres a class name', () => {
      expect(wrapper.classes()).toContain('tableEditable')
    })
    it('click and emit buttons', async () => {
        await wrapper.findComponent({ref: 'edit-outlined'})
        await wrapper.trigger('click')
        expect(wrapper.emitted()).toHaveProperty('edit')

      })
  })

This is my component:

  <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]="{ column, text, record }" :key="col">

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

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

      </template>

  </template>

Body:
As far as I can tell expect(wrapper.emitted()).toHaveProperty('edit') should work.

So I think the issue is that the click is not working as you expect

you have

await wrapper.findComponent({ref: 'edit-outlined'})
await wrapper.trigger('click')

which will

find the edit-outlined button in the wrapper

click on the component/wrapper (NOT the button)

to fix that, you can try chaining it like this:

await wrapper
  .findComponent({ref: 'edit-outlined'})
  .trigger('click');

The trigger here is assigned to the result of findComponent

Update

I believe wrapper.findComponent({ref: 'edit-outlined'}) is not finding the component. When using ref it will look for components that have that value in the ref attribute.

you have

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

edit-outlined is the name/type of the component, and not a ref.

you could change it to

<div v-else class="editable-cell-text-wrapper">
  {{ text || ' ' }}
  <edit-outlined ref="edit-outlined" class="editable-cell-icon" @click="edit(record.key, column.key)" />
</div>

which would put it into this.$refs internal object (this.$refs['edit-outlined'] specifically) which would make it accessible using  wrapper.findComponent({ref: 'edit-outlined'}).

You should also be able to change the way you target that element which should make it work without changing the code you are testing.

findcomponent has three type you can pass as the selector argument.

{Component|ref|string} selector

If you only have one instance or EditOutlined, you can target that using the Component type like this:

const btn = wrapper.findComponent(EditOutlined);
expect(btn.exists()).toBe(true);
await btn.trigger('click');

also, it's a good idea to add these: expect(btn.exists()).toBe(true); They also act as a "sanity test" and make sure when you get an error that you are looking in the right place.


问:
For Kotlin Extended Button, how to include style?
I have extended the Button class within Kotlin:

```<code>class TabButton @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : Button(context, attrs, defStyleAttr) {

    override fun onInitializeAccessibilityNodeInfo(info: AccessibilityNodeInfo?) {
        super.onInitializeAccessibilityNodeInfo(info)

        info?.text?.let {
            info.text = getContentDescription(it.toString())
        }
    }

    private fun getContentDescription(input: String): String {
        return this.resources.getString(R.string.tab_button_content_desc, input)
    }
}
</code>```

in order to get the appropriate Content Description.  However, this TabButton is ignoring/not receiving the style associated with the button:

```<code><com.foo.widgets.TabButton
    android:id="@+id/selection_scheduled"
    style="@style/Widget.Button.Filter"
</code>```

What in my TabButton extension am I missing so that recognizes and applies the style?

答:
I’m AFK, so sorry if this wrong. I can’t test it.

You should subclass either AppCompatButton or MaterialButton (if you’re using a Material Components theme). The layout  inflater knows how to replace Button elements with one of these based on the theme, but it’s impossible to replace your button in a way that works since you’re not subclassing one of these.

Also, instead of using 0 as the default for the defStyleAttr, you should use whatever the superclass passes for that value. Look at the two-argument constructor of whichever of the two button classes you choose to subclass.

Body:
I have extended the Button class within Kotlin:

class TabButton @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : Button(context, attrs, defStyleAttr) {

    override fun onInitializeAccessibilityNodeInfo(info: AccessibilityNodeInfo?) {
        super.onInitializeAccessibilityNodeInfo(info)

        info?.text?.let {
            info.text = getContentDescription(it.toString())
        }
    }

    private fun getContentDescription(input: String): String {
        return this.resources.getString(R.string.tab_button_content_desc, input)
    }
}

in order to get the appropriate Content Description.  However, this TabButton is ignoring/not receiving the style associated with the button:

<com.foo.widgets.TabButton
    android:id="@+id/selection_scheduled"
    style="@style/Widget.Button.Filter"

What in my TabButton extension am I missing so that recognizes and applies the style?


问:
Firebase storage percentChanges() method returns NaN
I am trying to build a firebase storage service from an angular client, which will upload a user profile image and return uploadProgress$ and DdownloadUrl$ observables.

uploadProgress$ is a Observable which will store the percentChanges() value and
downloadUrl$ is a Observable which will contain the getDownloadURL() value.

When binding the uploadProgress$ to angular using the [value] = "uploadProgress$ | async" pipe it returns NaN.

I am able to receive the image link when the upload has finished.

My code is as follows:

firebase-storage.service

```<code>import { Injectable } from '@angular/core';
import {
  AngularFireStorage,
  AngularFireUploadTask,
} from '@angular/fire/compat/storage';
import { finalize, from, Observable, switchMap } from 'rxjs';
import { imageFile } from '../models/file-upload';

interface FilesUploadMetadata {
  downloadUrl$: Observable<string>;
  uploadProgress$: Observable<number | undefined>;
}

@Injectable({
  providedIn: 'root',
})
export class FirebaseStorageService {
  constructor(private fireStorage: AngularFireStorage) {}

  uploadFileAndGetMetadata(
    fileToUpload: imageFile,
    mediaFolderPath: string,
    userName: string
  ): FilesUploadMetadata {
    const filePath = `${mediaFolderPath}/${userName}_profileImage`;
    const storageRef = this.fireStorage.ref(filePath);
    const uploadTask: AngularFireUploadTask = this.fireStorage.upload(filePath, fileToUpload);

    uploadTask
      .snapshotChanges()
      .pipe(
        finalize(() => {
          storageRef.getDownloadURL().subscribe((downloadURL) => {
            fileToUpload.url = downloadURL;
            fileToUpload.name = fileToUpload.file.name;
          });
        })
      )
      .subscribe();

    return {
      uploadProgress$: uploadTask.percentageChanges(),
      downloadUrl$: storageRef.getDownloadURL(),
    };
  }
}
</code>```

user-profile.component.ts

```<code>upload() {
    this.submitted = true;
    const file: File = this.selectedFile.item(0) as File;
    this.currentFileUpload = new imageFile(file);
    const userName = this.currentUser.username;
    const mediaFolderPath = `Profile/${this.currentUser.email}/profileImage/`;
    const { uploadProgress$, downloadUrl$ } =
      this.firebaseService.uploadFileAndGetMetadata(
        this.currentFileUpload,
        mediaFolderPath,
        userName
      );
    uploadProgress$.subscribe((percent) => {
      console.log(typeof percent);
      console.log(percent);
    });
    downloadUrl$.subscribe((downloadUrl) => {
      console.log(downloadUrl);
    });
  }
}
</code>```

user-profile.component.html

```<code><div *ngIf="submitted">
<mat-progress-bar [value]="uploadProgress$ | async" mode="determinate">
</mat-progress-bar>
</div>
</code>```

答: const { uploadProgress$, downloadUrl$ } is local. It's only available inside the function. You must create it outside as public.

Body:
I am trying to build a firebase storage service from an angular client, which will upload a user profile image and return uploadProgress$ and DdownloadUrl$ observables.

uploadProgress$ is a Observable which will store the percentChanges() value and
downloadUrl$ is a Observable which will contain the getDownloadURL() value.

When binding the uploadProgress$ to angular using the [value] = "uploadProgress$ | async" pipe it returns NaN.

I am able to receive the image link when the upload has finished.

My code is as follows:

firebase-storage.service

import { Injectable } from '@angular/core';
import {
  AngularFireStorage,
  AngularFireUploadTask,
} from '@angular/fire/compat/storage';
import { finalize, from, Observable, switchMap } from 'rxjs';
import { imageFile } from '../models/file-upload';

interface FilesUploadMetadata {
  downloadUrl$: Observable<string>;
  uploadProgress$: Observable<number | undefined>;
}

@Injectable({
  providedIn: 'root',
})
export class FirebaseStorageService {
  constructor(private fireStorage: AngularFireStorage) {}

  uploadFileAndGetMetadata(
    fileToUpload: imageFile,
    mediaFolderPath: string,
    userName: string
  ): FilesUploadMetadata {
    const filePath = `${mediaFolderPath}/${userName}_profileImage`;
    const storageRef = this.fireStorage.ref(filePath);
    const uploadTask: AngularFireUploadTask = this.fireStorage.upload(filePath, fileToUpload);

    uploadTask
      .snapshotChanges()
      .pipe(
        finalize(() => {
          storageRef.getDownloadURL().subscribe((downloadURL) => {
            fileToUpload.url = downloadURL;
            fileToUpload.name = fileToUpload.file.name;
          });
        })
      )
      .subscribe();

    return {
      uploadProgress$: uploadTask.percentageChanges(),
      downloadUrl$: storageRef.getDownloadURL(),
    };
  }
}

user-profile.component.ts

upload() {
    this.submitted = true;
    const file: File = this.selectedFile.item(0) as File;
    this.currentFileUpload = new imageFile(file);
    const userName = this.currentUser.username;
    const mediaFolderPath = `Profile/${this.currentUser.email}/profileImage/`;
    const { uploadProgress$, downloadUrl$ } =
      this.firebaseService.uploadFileAndGetMetadata(
        this.currentFileUpload,
        mediaFolderPath,
        userName
      );
    uploadProgress$.subscribe((percent) => {
      console.log(typeof percent);
      console.log(percent);
    });
    downloadUrl$.subscribe((downloadUrl) => {
      console.log(downloadUrl);
    });
  }
}

user-profile.component.html

<mat-progress-bar [value]="uploadProgress$ | async" mode="determinate">
</mat-progress-bar>


问:
Invalid ELF Header - Argon2 package
I am running to an error that says "Invalid ELF header" for a package called "argon2". When uploading my code to AWS Lambda through the serverless framework. The code runs perfectly when running locally.

Development on MacOS Big Sur version 11.4

Image of the error I am getting

I've researched a little bit on the error and people are saying to use Docker to compile the packages and then send to Lambda. I haven't worked with Docker much and wanted to explore other options before attempting the docker solution.

Any guidance or help would be much appreciated! I've been stuck on this bug for over a day or two.

答:
Just to add. To deploy to Lambda you would (eventually) need to send your files in a zip. And to bundle your project efficiently you would need a bundler like Webpack. The problem is, argon2 and any other hash implementations like bcrypt use node-pre-gyp dependency that doesn't work well with bundler. So the options are:

Just zip the entire project and everything inside node_modules. This means including everything that isn't used which can be massive.

When using Webpack exclude argon2 from the config with the consequence that it has to be manually installed in target environment.

Use a pure js version of argon2 which is much slower.

If you use it to manage passwords then you can drop it for a cloud service like AWS KMS that offers secure symmetric keys. However these keys encrypt, not hash so for the better or worse you can decrypt the passwords back to plain text.

Remember that hashing performance itself is proportional to memory and CPU. So running a hashing algorithm for fast result could mean high Lambda bill.

Title: Invalid ELF Header - Argon2 package


问:
Numpy Attribute Error : Float object has no attribtue 'arctan2'
I have been trying to implement this piece of code but since I am very new to numpy I have less idea about this error.

```<code>import numpy as np
from sympy import *
import matplotlib.pyplot as plt

def asSpherical(coord):
    x=coord[0]
    y=coord[1]
    z=coord[2]
    azimuth = np.arctan2(y,x)
    elevation = np.arctan2(z,np.sqrt(x**2 + y**2))
    r = np.sqrt(x**2 + y**2 + z**2)
    return [azimuth, elevation, r]

def ecefToEnu(lamb, phi, coord_set):
    # @param1 is lattitude
    # @param2 is longitude
    # @param3 is coordinate set in form of a list

    # R matrix of size 3x3
    # This transforms the ECEF coordinates to ENU
    trans_matrix = [
        [-np.sin(lamb), np.cos(lamb), 0],
        [-(np.cos(lamb))*np.sin(phi), -
         np.sin(lamb)*np.sin(phi), np.cos(phi)],
        [np.cos(lamb)*np.cos(phi), np.sin(lamb)*np.cos(phi), sin(phi)]
    ]
    # Performs the matrix multiplication
    enu_coords = np.matmul(trans_matrix, coord_set)
    # Returns a list of Cartesian Coordinates
    sph_coords = asSpherical(enu_coords)
    return sph_coords

coord_list = []
print("Enter the latitude")
latitude = float(input())
print("Enter the coordinate list:")
print("Enter X:")
coord_list.append(float(input()))
print("Enter Y:")
coord_list.append(float(input()))
print("Enter Z:")
coord_list.append(float(input()))
phiDegSet = np.arange(-180, 180, 1)
Nset = len(phiDegSet)
t0 = np.linspace(0, 24, Nset)
t0 = list(t0)

res = []
for i in range(0, 360):
    temp_list = ecefToEnu(latitude, phiDegSet[i], coord_list)
    res.append(temp_list)
elevDegSet = []
for i in res:
    elevDegSet.append(i[1])
</code>```

Which gives me an error:

```<code>    elevation = np.arctan2(z,np.sqrt(x**2 + y**2))
AttributeError: 'Float' object has no attribute 'arctan2'
</code>```

I am already passing the value to the function as float. Even the importing numpy works fine.

答:
I added a print statement right before the arctan:

```<code>def asSpherical(coord):
    x=coord[0]
    y=coord[1]
    z=coord[2]
    print(x,y,z)
    azimuth = np.arctan2(y,x)
    ...
</code>```

and got this run:

```<code>....
ter the latitude
45
Enter the coordinate list:
Enter X:
45
Enter Y:
45
Enter Z:
45
-14.65116910723749 -76.54620448997258 -37.062720709188 - 45.0*sin(180)
Traceback (most recent call last):
  File "stack71078990.py", line 52, in <module>
    temp_list = ecefToEnu(latitude, phiDegSet[i], coord_list)
  File "stack71078990.py", line 31, in ecefToEnu
    sph_coords = asSpherical(enu_coords)
  File "stack71078990.py", line 11, in asSpherical
    elevation = np.arctan2(z,np.sqrt(x**2 + y**2))
AttributeError: 'Add' object has no attribute 'arctan2'
</code>```

z is -37.062720709188 - 45.0*sin(180), where sin(180) a sympy expression.

I see sin(phi) in the trans_matrix expression. Because of the from sympy import *, sin (as opposed to np.sin) is a sympy function.

Removing that import (as I commented) raises:

```<code>Traceback (most recent call last):
  File "stack71078990.py", line 52, in <module>
    temp_list = ecefToEnu(latitude, phiDegSet[i], coord_list)
  File "stack71078990.py", line 26, in ecefToEnu
    [np.cos(lamb)*np.cos(phi), np.sin(lamb)*np.cos(phi), sin(phi)]
NameError: name 'sin' is not defined
</code>```

Changing that to np.sin (like the other functions in the definition), lets the script run without error.

Body:
I have been trying to implement this piece of code but since I am very new to numpy I have less idea about this error.

import numpy as np
from sympy import *
import matplotlib.pyplot as plt

def asSpherical(coord):
    x=coord[0]
    y=coord[1]
    z=coord[2]
    azimuth = np.arctan2(y,x)
    elevation = np.arctan2(z,np.sqrt(x**2 + y**2))
    r = np.sqrt(x**2 + y**2 + z**2)
    return [azimuth, elevation, r]

def ecefToEnu(lamb, phi, coord_set):
    # @param1 is lattitude
    # @param2 is longitude
    # @param3 is coordinate set in form of a list

    # R matrix of size 3x3
    # This transforms the ECEF coordinates to ENU
    trans_matrix = [
        [-np.sin(lamb), np.cos(lamb), 0],
        [-(np.cos(lamb))*np.sin(phi), -
         np.sin(lamb)*np.sin(phi), np.cos(phi)],
        [np.cos(lamb)*np.cos(phi), np.sin(lamb)*np.cos(phi), sin(phi)]
    ]
    # Performs the matrix multiplication
    enu_coords = np.matmul(trans_matrix, coord_set)
    # Returns a list of Cartesian Coordinates
    sph_coords = asSpherical(enu_coords)
    return sph_coords

coord_list = []
print("Enter the latitude")
latitude = float(input())
print("Enter the coordinate list:")
print("Enter X:")
coord_list.append(float(input()))
print("Enter Y:")
coord_list.append(float(input()))
print("Enter Z:")
coord_list.append(float(input()))
phiDegSet = np.arange(-180, 180, 1)
Nset = len(phiDegSet)
t0 = np.linspace(0, 24, Nset)
t0 = list(t0)

res = []
for i in range(0, 360):
    temp_list = ecefToEnu(latitude, phiDegSet[i], coord_list)
    res.append(temp_list)
elevDegSet = []
for i in res:
    elevDegSet.append(i[1])

Which gives me an error:

    elevation = np.arctan2(z,np.sqrt(x**2 + y**2))
AttributeError: 'Float' object has no attribute 'arctan2'

I am already passing the value to the function as float. Even the importing numpy works fine.

Body:
I added a print statement right before the arctan:

def asSpherical(coord):
    x=coord[0]
    y=coord[1]
    z=coord[2]
    print(x,y,z)
    azimuth = np.arctan2(y,x)
    ...

and got this run:

....
ter the latitude
45
Enter the coordinate list:
Enter X:
45
Enter Y:
45
Enter Z:
45
-14.65116910723749 -76.54620448997258 -37.062720709188 - 45.0*sin(180)
Traceback (most recent call last):
  File "stack71078990.py", line 52, in <module>
    temp_list = ecefToEnu(latitude, phiDegSet[i], coord_list)
  File "stack71078990.py", line 31, in ecefToEnu
    sph_coords = asSpherical(enu_coords)
  File "stack71078990.py", line 11, in asSpherical
    elevation = np.arctan2(z,np.sqrt(x**2 + y**2))
AttributeError: 'Add' object has no attribute 'arctan2'

z is -37.062720709188 - 45.0*sin(180), where sin(180) a sympy expression.

I see sin(phi) in the trans_matrix expression. Because of the from sympy import *, sin (as opposed to np.sin) is a sympy function.

Removing that import (as I commented) raises:

Traceback (most recent call last):
  File "stack71078990.py", line 52, in <module>
    temp_list = ecefToEnu(latitude, phiDegSet[i], coord_list)
  File "stack71078990.py", line 26, in ecefToEnu
    [np.cos(lamb)*np.cos(phi), np.sin(lamb)*np.cos(phi), sin(phi)]
NameError: name 'sin' is not defined

Changing that to np.sin (like the other functions in the definition), lets the script run without error.


问:
What Role or Scopes Does An Azure Service Principal Need to Create Applications
I currently create a service principal using the Azure CLI:

az ad sp create-for-rbac --name foo --role Contributor

I need the service principal to have enough permissions to create/modify/delete various Azure AD resources including Applications, other Service Principals and Service Principal Passwords. When I use the above service principal to create other service principals, I currently get 403 Forbidden errors.

I have also tried using the 'Owner' and 'User Access Administrator' roles but these still give me a 403 error. What do I need to add to the above Azure CLI command or what additional role assignments do I need to add?

I'd like to use the service principal in a Pulumi program with their Azure AD provider (based on Terraform's Azure AD provider). See:

https://github.com/pulumi/pulumi-azuread/issues/246

答:
You need to give your service principal "App admin" permissions. This allows you to create application registrations and also set their credentials. And it does not give it rights to do anything else such as manage users and groups. If your intent is to include those, you need to add additional roles to the service principal.

https://learn.microsoft.com/en-us/azure/active-directory/roles/permissions-reference#application-administrator


问:
if statement php?
i don't know why but this is not working:

I am working on an Ajax send , i have send a value to a PHP script which parses the values and store the values in a php variable.
and now:

```<code>$id = $_GET['id'];
$url = $_GET['url'];
$check = $_GET['check'];
$filid = mysql_real_escape_string($id);
$filurl = mysql_real_escape_string($url);

if($check == 'true'){
    $insert  = "INSERT INTO tab (id,url) VALUES ('$filid','$filurl')";
    mysql_query($insert) or die(mysql_error());
}
</code>```

I am confirmed that my Ajax code is working , i'm not sure about php.When i remove the if statement and directly put the data into my database , it's working.

I'm new so please tolerate.
I hope someone can point me out my mistakes are.

Thanks!

答: I think you probably want to check for true, rather than 'true' - you're looking for a string of text that happens to spell true, not the boolean true/false.

Title: if statement php?

Body:
i don't know why but this is not working:

I am working on an Ajax send , i have send a value to a PHP script which parses the values and store the values in a php variable.
and now:

$id = $_GET['id'];
$url = $_GET['url'];
$check = $_GET['check'];
$filid = mysql_real_escape_string($id);
$filurl = mysql_real_escape_string($url);

if($check == 'true'){
    $insert  = "INSERT INTO tab (id,url) VALUES ('$filid','$filurl')";
    mysql_query($insert) or die(mysql_error());
}

I am confirmed that my Ajax code is working , i'm not sure about php.When i remove the if statement and directly put the data into my database , it's working.

I'm new so please tolerate.
I hope someone can point me out my mistakes are.

Thanks!


问:
Nested Query returns nothing
In my table (named checkout) in the database I have the

price (price of the item)

discount (what percentage of discount it had, eg 50 (for 50%))

howmany (which is the quantity of the product)

date (which is the current date)

I want my query to fetch the sum of the prices that had no discount on it and the sum of the prices that had discount on it for the year that we have and group it based on the month.

In the first SELECT I get the price multiplied by the quantity and it's without discount (works perfectly fine) but when I added the sub Query, the Query does not work. Any suggestions?

The (price*(1-(discount/100) in the Sub Query, first gets the discount for example 30/100=0.3 then it substracts it from the 1 (1-0.3=0.7 ) then I multiplied it with the price (price*0.7) and it returns the price with the discount

```<code>$sqlQuery = "SELECT sum(price*howmany) as price,
             (SELECT sum((price*(1-(discount/100))*howmany) as price
                    FROM checkout
                    WHERE '$year'=YEAR(date) AND discount IS NOT NULL
                    GROUP BY Month(date)
                    ORDER BY Month(date)) as discountPrice
             FROM checkout
             WHERE '$year'=YEAR(date) AND discount IS NULL
             GROUP BY Month(date)
             ORDER BY Month(date) ";
</code>```

答:
you don't need a subquery. You can put the discount condition inside the SUM() calls.

```<code>SELECT
    MONTH(date) AS month,
    SUM(IF(discount IS NULL, price, 0) * howmany) AS price,
    SUM(IF(discount IS NOT NULL, price*(1-(discount/100))*howmany, 0) AS discountPrice
FROM checkout
WHERE YEAR(date) = $year
GROUP BY month
ORDER BY month
</code>```

See need to return two sets of data with two different where clauses

Title: Nested Query returns nothing

Body:
In my table (named checkout) in the database I have the

price (price of the item)

discount (what percentage of discount it had, eg 50 (for 50%))

howmany (which is the quantity of the product)

date (which is the current date)

I want my query to fetch the sum of the prices that had no discount on it and the sum of the prices that had discount on it for the year that we have and group it based on the month.

In the first SELECT I get the price multiplied by the quantity and it's without discount (works perfectly fine) but when I added the sub Query, the Query does not work. Any suggestions?

The (price*(1-(discount/100) in the Sub Query, first gets the discount for example 30/100=0.3 then it substracts it from the 1 (1-0.3=0.7 ) then I multiplied it with the price (price*0.7) and it returns the price with the discount

$sqlQuery = "SELECT sum(price*howmany) as price,
             (SELECT sum((price*(1-(discount/100))*howmany) as price
                    FROM checkout
                    WHERE '$year'=YEAR(date) AND discount IS NOT NULL
                    GROUP BY Month(date)
                    ORDER BY Month(date)) as discountPrice
             FROM checkout
             WHERE '$year'=YEAR(date) AND discount IS NULL
             GROUP BY Month(date)
             ORDER BY Month(date) ";

Body:
you don't need a subquery. You can put the discount condition inside the SUM() calls.

SELECT
    MONTH(date) AS month,
    SUM(IF(discount IS NULL, price, 0) * howmany) AS price,
    SUM(IF(discount IS NOT NULL, price*(1-(discount/100))*howmany, 0) AS discountPrice
FROM checkout
WHERE YEAR(date) = $year
GROUP BY month
ORDER BY month

See need to return two sets of data with two different where clauses


问:
If I can have multiple factory methods in a creator class, why would I ever need the abstract factory pattern?
The abstract factory pattern is useful when we have families of related classes, and we want to instantiate them without relying on the implementation. However, what's wrong with using the factory method pattern in such a situation?

Let's say that we want to construct cross-platform UI elements, e.g. TextBox and Button for Windows and macOS and treat them abstractly. This is the typical situation in which we use the abstract factory pattern, and we can do so by defining the following:

AbstractUIElementsFactory interface

WindowsUIElementsFactory implements AbstractUIElementsFactory

MacUIElementsFactory implements AbstractUIElementsFactory

TextBox abstract class

MacTextBox extends TextBox

WindowsTextBox extends TextBox

Button abstract class

MacButton extends Button

WindowsButton extends Button

and the application would decide which concrete factory to create (based on some OS discovery mechanism) and pass it to a UIApplication class, which instantiates a TextBox and a Button, and calls display on them (which are abstract methods that simply return a String).

The code for this situation:

package abstractFactory;

abstract class Button {
    public abstract void display();
}

class MacButton extends Button {
    public void display() {
        System.out.println("macButton");
    }
}

class WindowsButton extends Button {

    @Override
    public void display() {
        System.out.println("winButton");
    }
}

abstract class TextBox {
    public abstract void display();
}

class MacTextBox extends TextBox {

    @Override
    public void display() {
        System.out.println("macTextBox");
    }
}

class WinTextBox extends TextBox {

    @Override
    public void display() {
        System.out.println("winTextBox");
    }
}

interface UICreatorAbstractFactory {
    Button getButton();
    TextBox getTextBox();
}

class MacFactory implements UICreatorAbstractFactory {

    @Override
    public Button getButton() {
        return new MacButton();
    }

    @Override
    public TextBox getTextBox() {
        return new MacTextBox();
    }
}

class WindowsFactory implements UICreatorAbstractFactory {

    @Override
    public Button getButton() {
        return new WindowsButton();
    }

    @Override
    public TextBox getTextBox() {
        return new WinTextBox();
    }
}

class UIApplication {
    private UICreatorAbstractFactory factory;

    UIApplication(UICreatorAbstractFactory _factory) {
        factory = _factory;
    }

    public void displayUI() {
        factory.getButton().display();
        factory.getTextBox().display();
    }
}

public class Main {
    public static void main(String[] args) {
        new UIApplication(new MacFactory()).displayUI();
    }
}
```
<p>This implementation allows us to get UI elements transparently from factory implementations and also UI elements implementations, which is largely why we would use the pattern.</p>
<p>Using the same <code>TextBox</code>, <code>Button</code>, and their derivatives, we can have a factory method implementation with two factory methods in the <em>creator</em>, <code>UICreator</code>, each of which returns an abstract UI element. And we derive the <em>creator</em> and make two specializations <code>WindowsUICreator</code>, and <code>MacUICreator</code>, and each of which returns the appropriate concrete UI element, as follows:</p>
<pre class="lang-java prettyprint-override"><code>abstract class UICreator {

    public void displayUI() {
        getButton().display();
        getTextBox().display();
    }

    protected abstract Button getButton();
    protected abstract TextBox getTextBox();

}

class WindowsUICreator extends UICreator {

    @Override
    protected Button getButton() {
        return new WindowsButton();
    }

    @Override
    protected TextBox getTextBox() {
        return new WinTextBox();
    }
}

class MacUICreator extends UICreator {

    @Override
    protected Button getButton() {
        return new MacButton();
    }

    @Override
    protected TextBox getTextBox() {
        return new MacTextBox();
    }
}

public class Main {

    public static void main(String[] args) {
        new MacUICreator().displayUI();
    }
}
</code>```

What are the downsides of this design? I believe it provides the needed decoupling by not having to deal with any concrete classes, and also provides the proper extensibility in the sense that we can introduce new UI elements and give them new factory methods, or newly supported OSs and implement concrete creators for them. And if we can use the factory method pattern in the exact situation the abstract factory pattern was designed for, I don't understand why do we have it at all?

答:
I would like to show you an image from Saurav Satpathy's blog here which quickly can explain why you want abstract factory over factory method at times.

The argument for dependency injection and collection of related objects makes a lot of sense and here is a coded example by a great creator The Refactoring Guru on Abstract Factory and here is his example on factory method. The main difference between the examples in my opinion is the abstract factory better depicts the complexity of factories that create multiple types of objects. Additionally, it effectively divides the code in more classes, making each class simpler to understand (but creating more classes in total, of course).

Keep in mind this is not a very in depth analysis as of now, I want to see other people's opinions on the matter and give it some time to think for myself. I may come back in a couple of days with an edit (currently a bit busy, but I sneaked a quick opinion for you)

Edit #1 Inheritance

"Favor object composition over class inheritance. Inheritance breaks encapsulation, implement abstract classes, do not inherit concrete classes! - The Gang of Four on Design Patterns"

So object inheritance if you read the GoF's book: "Design Patterns Elements of Reusable Object-Oriented Software" is discouraged, especially when systems become more and more complex or higher in scope. Edit influenced by @FelipeLlinares great point indeed.

Body:
The abstract factory pattern is useful when we have families of related classes, and we want to instantiate them without relying on the implementation. However, what's wrong with using the factory method pattern in such a situation?

Let's say that we want to construct cross-platform UI elements, e.g. TextBox and Button for Windows and macOS and treat them abstractly. This is the typical situation in which we use the abstract factory pattern, and we can do so by defining the following:

AbstractUIElementsFactory interface

WindowsUIElementsFactory implements AbstractUIElementsFactory

MacUIElementsFactory implements AbstractUIElementsFactory

TextBox abstract class

MacTextBox extends TextBox

WindowsTextBox extends TextBox

Button abstract class

MacButton extends Button

WindowsButton extends Button

and the application would decide which concrete factory to create (based on some OS discovery mechanism) and pass it to a UIApplication class, which instantiates a TextBox and a Button, and calls display on them (which are abstract methods that simply return a String).

The code for this situation:

package abstractFactory;

abstract class Button {
    public abstract void display();
}

class MacButton extends Button {
    public void display() {
        System.out.println("macButton");
    }
}

class WindowsButton extends Button {

    @Override
    public void display() {
        System.out.println("winButton");
    }
}

abstract class TextBox {
    public abstract void display();
}

class MacTextBox extends TextBox {

    @Override
    public void display() {
        System.out.println("macTextBox");
    }
}

class WinTextBox extends TextBox {

    @Override
    public void display() {
        System.out.println("winTextBox");
    }
}

interface UICreatorAbstractFactory {
    Button getButton();
    TextBox getTextBox();
}

class MacFactory implements UICreatorAbstractFactory {

    @Override
    public Button getButton() {
        return new MacButton();
    }

    @Override
    public TextBox getTextBox() {
        return new MacTextBox();
    }
}

class WindowsFactory implements UICreatorAbstractFactory {

    @Override
    public Button getButton() {
        return new WindowsButton();
    }

    @Override
    public TextBox getTextBox() {
        return new WinTextBox();
    }
}

class UIApplication {
    private UICreatorAbstractFactory factory;

    UIApplication(UICreatorAbstractFactory _factory) {
        factory = _factory;
    }

    public void displayUI() {
        factory.getButton().display();
        factory.getTextBox().display();
    }
}

public class Main {
    public static void main(String[] args) {
        new UIApplication(new MacFactory()).displayUI();
    }
}

This implementation allows us to get UI elements transparently from factory implementations and also UI elements implementations, which is largely why we would use the pattern.

Using the same TextBox, Button, and their derivatives, we can have a factory method implementation with two factory methods in the creator, UICreator, each of which returns an abstract UI element. And we derive the creator and make two specializations WindowsUICreator, and MacUICreator, and each of which returns the appropriate concrete UI element, as follows:

abstract class UICreator {

    public void displayUI() {
        getButton().display();
        getTextBox().display();
    }

    protected abstract Button getButton();
    protected abstract TextBox getTextBox();

}

class WindowsUICreator extends UICreator {

    @Override
    protected Button getButton() {
        return new WindowsButton();
    }

    @Override
    protected TextBox getTextBox() {
        return new WinTextBox();
    }
}

class MacUICreator extends UICreator {

    @Override
    protected Button getButton() {
        return new MacButton();
    }

    @Override
    protected TextBox getTextBox() {
        return new MacTextBox();
    }
}

public class Main {

    public static void main(String[] args) {
        new MacUICreator().displayUI();
    }
}

What are the downsides of this design? I believe it provides the needed decoupling by not having to deal with any concrete classes, and also provides the proper extensibility in the sense that we can introduce new UI elements and give them new factory methods, or newly supported OSs and implement concrete creators for them. And if we can use the factory method pattern in the exact situation the abstract factory pattern was designed for, I don't understand why do we have it at all?


问:
Chess with PyGame: TypeError: unhashable type: 'list'
I'm trying to make a chess game, I'm watching a tutorial of 2021 using Python 3.9. I'm using 3.10 and maybe thats the reason thats not working. Anyways, let me show you the code:

```<code>import pygame as p
import Engine

WIDTH = HEIGHT = 512
DIMENSION = 8 # Las dimensiones del tablero son 8x8
SQ_SIZE = HEIGHT // DIMENSION
MAX_FPS = 15 # Para las animaciones
IMAGES = {}

def loadImages():
    pieces = ["bR", "bN", "bB", "bQ", "bK", "wR", "wN", "wB", "wQ", "wK"]
    for piece in pieces:
        IMAGES[piece] = p.transform.scale(p.image.load("images/" + piece + ".png"), (SQ_SIZE, SQ_SIZE))
    # Nota: Podemos acceder a una imagen diciendo "IMAGES[pieza]"

def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    gs = Engine.GameState()
    print(gs.board)
    loadImages() # Solo hazlo una vez, antes del loop
    running = True
    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
        drawGameState(screen, gs)
        clock.tick(MAX_FPS)
        p.display.flip()

def drawGameState(screen, gs):
    drawBoard(screen) # Dibuja los cuadrados del tablero
    # Pon que se puedan marcar algunas piezas (despues)
    drawPieces(screen, gs.board) # Dibuja las piezas encima de los cuadrados

def drawBoard(screen):
    colors = [p.Color("#f0d9b5"), p.Color("#b58863")]
    for r in range(DIMENSION):
        for c in range(DIMENSION):
            color = colors[((r+c) % 2)]
            p.draw.rect(screen, color, p.Rect(c*SQ_SIZE, r*SQ_SIZE, SQ_SIZE, SQ_SIZE))

def drawPieces(screen, board):
    for r in range(DIMENSION):
        for c in range(DIMENSION):
            piece = board[[r][c]]
            if piece != "--": # No es un cuadrado vacío
                screen.blit(IMAGES[piece], p.Rect(c*SQ_SIZE, r*SQ_SIZE, SQ_SIZE, SQ_SIZE))

if __name__ == "__main__":
    main()
</code>```

Thats the main file, and here's the engine file:

```<code>class GameState():
    def __init__(self):
        # El tablero es una lista 2D de 8x8, cada elemento tiene 2 caracteres
        # El primero caracter representa el color, ya sea "w" para blanco o "b" para negro
        # El segundo caracter representra la figura ya sea "R" para torre, "N" para caballo, "B" para alfil, "Q" para reyna, "K" para rey y "P" para peon
        # "--" Representa un espacio vacio
        self.board = [
            ["bR", "bN", "bB", "bQ", "bK", "bB", "bN", "bR"],
            ["bP", "bP", "bP", "bP", "bP", "bP"," bP", "bP"],
            ["--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--"],
            ["wP", "wP", "wP", "wP", "wP", "wP"," wP", "wP"],
            ["wR", "wN", "wB", "wQ", "wK", "wB", "wN", "wR"]]
        self.whiteToMove = True
        self.moveLog = []
</code>```

The error is on line 54:

```<code>screen.blit(IMAGES[piece], p.Rect(c*SQ_SIZE, r*SQ_SIZE, SQ_SIZE, SQ_SIZE))
</code>```

TypeError: unhashable type: 'list'

The code is exactly the same as in the tutorial. Sorry if I don't understand many things, I'm relatively new in Python.

答:
The issue is in your drawPieces function. You should change to piece = board[r][c]. When doing double indexing, you do not need to wrap in another square bracket (In fact, it is logically wrong to do that). Kindly refer to this article for more info on how to index a 2d Array (since your board variable is a 2d array)

The reason why board[[r][c]] is wrong is because:

When indexing a list, inside each square bracket pair can only be ONE THING

Inside the first bracket pair is [r][c]

Python will evaluate [r][c] as "The list [r] with index[c]". For example, when r = 0 and c = 0 --> [0][0] --> is going to be equivalent to

lis = [0]
value = lis[0] # --> value = 0
```

Therefore, eventually [r][c], if not index out of range, will returns an Integer

After [r][c] -> [0][0] -> 0, Python evaluation will become board[0]

piece = board[0] is a LIST --> The 0th index of board is the list ["bR", "bN", "bB", "bQ", "bK", "bB", "bN", "bR"]

Then you try to IMAGES[piece]. IMAGES is a dict; you were trying to use piece (which is a list) as a key to this IMAGES dict. list is not hashable, so Python errors out. The rule is only immutable data types can be used as dictionary keys, like string, tuple, integer, etc.

Case in point, when doing multiple indexing, just use board[1][2][3], no need to wrap the indexes in another big bracket pair (unless you have very specific special logic)

Body:
I'm trying to make a chess game, I'm watching a tutorial of 2021 using Python 3.9. I'm using 3.10 and maybe thats the reason thats not working. Anyways, let me show you the code:

import pygame as p
import Engine

WIDTH = HEIGHT = 512
DIMENSION = 8 # Las dimensiones del tablero son 8x8
SQ_SIZE = HEIGHT // DIMENSION
MAX_FPS = 15 # Para las animaciones
IMAGES = {}

def loadImages():
    pieces = ["bR", "bN", "bB", "bQ", "bK", "wR", "wN", "wB", "wQ", "wK"]
    for piece in pieces:
        IMAGES[piece] = p.transform.scale(p.image.load("images/" + piece + ".png"), (SQ_SIZE, SQ_SIZE))
    # Nota: Podemos acceder a una imagen diciendo "IMAGES[pieza]"

def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    gs = Engine.GameState()
    print(gs.board)
    loadImages() # Solo hazlo una vez, antes del loop
    running = True
    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
        drawGameState(screen, gs)
        clock.tick(MAX_FPS)
        p.display.flip()

def drawGameState(screen, gs):
    drawBoard(screen) # Dibuja los cuadrados del tablero
    # Pon que se puedan marcar algunas piezas (despues)
    drawPieces(screen, gs.board) # Dibuja las piezas encima de los cuadrados

def drawBoard(screen):
    colors = [p.Color("#f0d9b5"), p.Color("#b58863")]
    for r in range(DIMENSION):
        for c in range(DIMENSION):
            color = colors[((r+c) % 2)]
            p.draw.rect(screen, color, p.Rect(c*SQ_SIZE, r*SQ_SIZE, SQ_SIZE, SQ_SIZE))

def drawPieces(screen, board):
    for r in range(DIMENSION):
        for c in range(DIMENSION):
            piece = board[[r][c]]
            if piece != "--": # No es un cuadrado vacío
                screen.blit(IMAGES[piece], p.Rect(c*SQ_SIZE, r*SQ_SIZE, SQ_SIZE, SQ_SIZE))

if __name__ == "__main__":
    main()

Thats the main file, and here's the engine file:

class GameState():
    def __init__(self):
        # El tablero es una lista 2D de 8x8, cada elemento tiene 2 caracteres
        # El primero caracter representa el color, ya sea "w" para blanco o "b" para negro
        # El segundo caracter representra la figura ya sea "R" para torre, "N" para caballo, "B" para alfil, "Q" para reyna, "K" para rey y "P" para peon
        # "--" Representa un espacio vacio
        self.board = [
            ["bR", "bN", "bB", "bQ", "bK", "bB", "bN", "bR"],
            ["bP", "bP", "bP", "bP", "bP", "bP"," bP", "bP"],
            ["--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--"],
            ["wP", "wP", "wP", "wP", "wP", "wP"," wP", "wP"],
            ["wR", "wN", "wB", "wQ", "wK", "wB", "wN", "wR"]]
        self.whiteToMove = True
        self.moveLog = []

The error is on line 54:

screen.blit(IMAGES[piece], p.Rect(c*SQ_SIZE, r*SQ_SIZE, SQ_SIZE, SQ_SIZE))

TypeError: unhashable type: 'list'

The code is exactly the same as in the tutorial. Sorry if I don't understand many things, I'm relatively new in Python.

Body:
The issue is in your drawPieces function. You should change to piece = board[r][c]. When doing double indexing, you do not need to wrap in another square bracket (In fact, it is logically wrong to do that). Kindly refer to this article for more info on how to index a 2d Array (since your board variable is a 2d array)

The reason why board[[r][c]] is wrong is because:

When indexing a list, inside each square bracket pair can only be ONE THING

Inside the first bracket pair is [r][c]

Python will evaluate [r][c] as "The list [r] with index[c]". For example, when r = 0 and c = 0 --> [0][0] --> is going to be equivalent to

lis = [0]
value = lis[0] # --> value = 0

Therefore, eventually [r][c], if not index out of range, will returns an Integer

After [r][c] -> [0][0] -> 0, Python evaluation will become board[0]

piece = board[0] is a LIST --> The 0th index of board is the list ["bR", "bN", "bB", "bQ", "bK", "bB", "bN", "bR"]

Then you try to IMAGES[piece]. IMAGES is a dict; you were trying to use piece (which is a list) as a key to this IMAGES dict. list is not hashable, so Python errors out. The rule is only immutable data types can be used as dictionary keys, like string, tuple, integer, etc.

Case in point, when doing multiple indexing, just use board[1][2][3], no need to wrap the indexes in another big bracket pair (unless you have very specific special logic)


答:
There was a column that was not needed - Timepoint_yrs, select out the column and then it should work.  When we use the 'Timepoint_yrs' also in the code, it will look for the match for the value corresponding to that column as well

```<code>library(dplyr)
library(tidyr)
DF %>%
   ungroup %>%
   select(-Timepoint_yrs) %>%
   pivot_wider(names_from = Timepoint, values_from = mean_AD)
</code>```

-output

```<code># A tibble: 74 × 5
   ID    Sex         bl    flu1    flu2
   <fct> <chr>    <dbl>   <dbl>   <dbl>
 1 33714 Male   0.00103 0.00106 0.00106
 2 35377 Female 0.00106 0.00101 0.00107
 3 40556 Male   0.00114 0.00111 0.00105
 4 40798 Male   0.00111 0.00113 0.00111
 5 40800 Male   0.00105 0.00105 0.00106
 6 40815 Male   0.00111 0.00108 0.00107
 7 50848 Male   0.00109 0.00110 0.00109
 8 52183 Male   0.00110 0.00109 0.00108
 9 52461 Male   0.00104 0.00106 0.00106
10 53320 Male   0.00112 0.00113 0.00112
# … with 64 more rows
</code>```

Title: pivot wider not working with group_by in R

Body:
I have the following data set:

structure(list(ID = structure(c(1L, 2L, 9L, 10L, 11L, 12L, 14L,
15L, 16L, 19L, 20L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L,
31L, 32L, 33L, 35L, 36L, 37L, 38L, 39L, 40L, 42L, 43L, 46L, 47L,
48L, 49L, 50L, 51L, 52L, 53L, 55L, 56L, 57L, 58L, 60L, 61L, 62L,
66L, 67L, 68L, 71L, 72L, 73L, 74L, 75L, 81L, 84L, 85L, 93L, 95L,
96L, 104L, 107L, 109L, 116L, 126L, 133L, 135L, 138L, 139L, 146L,
150L, 154L, 164L, 165L, 1L, 2L, 9L, 10L, 11L, 12L, 14L, 15L,
16L, 19L, 20L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L,
32L, 33L, 35L, 36L, 37L, 38L, 39L, 40L, 42L, 43L, 46L, 47L, 48L,
49L, 50L, 51L, 52L, 53L, 55L, 56L, 57L, 58L, 60L, 61L, 62L, 66L,
67L, 68L, 71L, 72L, 73L, 74L, 75L, 81L, 84L, 85L, 93L, 95L, 96L,
104L, 107L, 109L, 116L, 126L, 133L, 135L, 138L, 139L, 146L, 150L,
154L, 164L, 165L, 1L, 2L, 9L, 10L, 11L, 12L, 14L, 15L, 16L, 19L,
20L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L,
35L, 36L, 37L, 38L, 39L, 40L, 42L, 43L, 46L, 47L, 48L, 49L, 50L,
51L, 52L, 53L, 55L, 56L, 57L, 58L, 60L, 61L, 62L, 66L, 67L, 68L,
71L, 72L, 73L, 74L, 75L, 81L, 84L, 85L, 93L, 95L, 96L, 104L,
107L, 109L, 116L, 126L, 133L, 135L, 138L, 139L, 146L, 150L, 154L,
164L, 165L), .Label = c("33714", "35377", "38623", "38806", "39593",
"39820", "39951", "40286", "40556", "40798", "40800", "40815",
"43762", "50848", "52183", "52461", "52577", "53202", "53320",
"53873", "54153", "54206", "54581", "55122", "55267", "55462",
"55612", "55920", "56022", "56307", "56420", "56679", "57405",
"57445", "57480", "57725", "57809", "58004", "58215", "58229",
"58503", "59326", "59327", "59344", "59361", "59865", "60099",
"60100", "60280", "60384", "60429", "60493", "60503", "60575",
"60603", "60664", "60846", "61415", "61656", "61749", "61883",
"62081", "62210", "62285", "62937", "62983", "63327", "63329",
"64081", "64328", "64418", "64507", "64596", "65178", "65250",
"65302", "65478", "65480", "65487", "65572", "65802", "65935",
"65974", "65975", "65978", "65991", "65995", "66013", "66154",
"66237", "66245", "66389", "66396", "66460", "66572", "66589",
"67174", "73230", "73525", "73539", "73677", "73942", "73953",
"74034", "74113", "74114", "74427", "74439", "74607", "74641",
"74657", "74794", "74800", "74836", "74942", "74952", "74962",
"74969", "74977", "74985", "74989", "75220", "75229", "75407",
"75653", "75732", "75735", "75757", "75895", "75898", "76381",
"76559", "76574", "76594", "76595", "76746", "76751", "76755",
"76759", "76775", "77088", "77091", "77099", "77134", "77188",
"77203", "77252", "77304", "77413", "77453", "77528", "77556",
"77585", "77668", "78262", "79724", "79730", "79850", "79977",
"80052", "80819", "80901", "80932", "81064", "81065", "81071",
"81098", "81142", "81175"), class = "factor"), Timepoint_yrs = c(0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 2L, 2L, 2L, 1L, 2L,
2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 2L, 1L,
2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L,
1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 2L, 3L, 3L, 2L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 3L, 3L, 3L, 2L, 3L, 2L, 3L, 2L,
3L, 3L, 3L, 2L, 3L, 3L, 3L, 2L, 3L, 2L, 3L, 2L, 2L, 2L, 3L, 3L,
3L, 3L, 3L, 3L, 2L, 3L, 2L, 2L, 2L, 2L, 3L, 3L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 3L, 2L, 2L, 2L, 2L, 3L, 2L, 2L, 2L, 2L), Sex = c("Male",
"Female", "Male", "Male", "Male", "Male", "Male", "Male", "Male",
"Male", "Male", "Male", "Male", "Male", "Male", "Male", "Female",
"Female", "Male", "Female", "Male", "Female", "Female", "Male",
"Female", "Female", "Male", "Female", "Male", "Male", "Female",
"Female", "Male", "Male", "Male", "Female", "Female", "Female",
"Male", "Male", "Female", "Female", "Male", "Female", "Male",
"Male", "Male", "Female", "Female", "Female", "Male", "Male",
"Male", "Male", "Male", "Male", "Male", "Male", "Female", "Female",
"Female", "Female", "Female", "Male", "Male", "Female", "Male",
"Male", "Male", "Female", "Male", "Female", "Male", "Male", "Male",
"Female", "Male", "Male", "Male", "Male", "Male", "Male", "Male",
"Male", "Male", "Male", "Male", "Male", "Male", "Male", "Female",
"Female", "Male", "Female", "Male", "Female", "Female", "Male",
"Female", "Female", "Male", "Female", "Male", "Male", "Female",
"Female", "Male", "Male", "Male", "Female", "Female", "Female",
"Male", "Male", "Female", "Female", "Male", "Female", "Male",
"Male", "Male", "Female", "Female", "Female", "Male", "Male",
"Male", "Male", "Male", "Male", "Male", "Male", "Female", "Female",
"Female", "Female", "Female", "Male", "Male", "Female", "Male",
"Male", "Male", "Female", "Male", "Female", "Male", "Male", "Male",
"Female", "Male", "Male", "Male", "Male", "Male", "Male", "Male",
"Male", "Male", "Male", "Male", "Male", "Male", "Male", "Female",
"Female", "Male", "Female", "Male", "Female", "Female", "Male",
"Female", "Female", "Male", "Female", "Male", "Male", "Female",
"Female", "Male", "Male", "Male", "Female", "Female", "Female",
"Male", "Male", "Female", "Female", "Male", "Female", "Male",
"Male", "Male", "Female", "Female", "Female", "Male", "Male",
"Male", "Male", "Male", "Male", "Male", "Male", "Female", "Female",
"Female", "Female", "Female", "Male", "Male", "Female", "Male",
"Male", "Male", "Female", "Male", "Female", "Male", "Male"),
    Timepoint = c("bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
    "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
    "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
    "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
    "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
    "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
    "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
    "bl", "bl", "bl", "bl", "bl", "bl", "flu1", "flu1", "flu1",
    "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
    "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
    "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
    "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
    "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
    "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
    "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
    "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
    "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu2",
    "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
    "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
    "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
    "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
    "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
    "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
    "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
    "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
    "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
    "flu2"), mean_AD = c(0.0010333, 0.00105981, 0.00113736, 0.001108715,
    0.00104864, 0.00110772, 0.00109096, 0.00109855, 0.00104169,
    0.00112465, 0.001096525, 0.000985059, 0.001098955, 0.001069465,
    0.00105376, 0.00106878, 0.00110388, 0.00108702, 0.001162835,
    0.001070955, 0.0010971, 0.00111695, 0.001060525, 0.00108797,
    0.00103262, 0.001117605, 0.001061707, 0.001156365, 0.00104431,
    0.00109114, 0.001053765, 0.001045395, 0.00106441, 0.00108481,
    0.0011145, 0.001095115, 0.001099075, 0.001057, 0.001096125,
    0.00109696, 0.001064795, 0.00108024, 0.00102137, 0.001103185,
    0.00111948, 0.001110965, 0.00103784, 0.00104419, 0.00101302,
    0.00108785, 0.001098765, 0.001052415, 0.0010976, 0.001064385,
    0.001129705, 0.001076575, 0.001049785, 0.00103181, 0.001078155,
    0.001129015, 0.001024814, 0.00109171, 0.001007862, 0.001099885,
    0.00109162, 0.001060665, 0.00106572, 0.00106803, 0.00113409,
    0.001052505, 0.001138575, 0.00108723, 0.001046765, 0.001090765,
    0.001060205, 0.0010143, 0.001106365, 0.00113328, 0.001045545,
    0.001081185, 0.001102495, 0.00108775, 0.001055425, 0.001130705,
    0.00115777, 0.00105974, 0.001089395, 0.001069105, 0.001054605,
    0.00107229, 0.001128765, 0.001111455, 0.001111155, 0.001095955,
    0.001108905, 0.001077275, 0.00104525, 0.00111458, 0.001110655,
    0.001114555, 0.00110557, 0.001167755, 0.0010552, 0.00110002,
    0.00104991, 0.001069695, 0.001101185, 0.001066815, 0.00109388,
    0.001079455, 0.001097655, 0.001106855, 0.00108804, 0.001102495,
    0.001077445, 0.00104224, 0.001064015, 0.00110557, 0.00112483,
    0.001093865, 0.00105965, 0.001048305, 0.0010719, 0.001098505,
    0.001073105, 0.001049325, 0.001097175, 0.00111584, 0.001122035,
    0.001036422, 0.001016249, 0.001015195, 0.00110143, 0.001121325,
    0.001047755, 0.001063235, 0.001079355, 0.001086495, 0.001074005,
    0.00109106, 0.00103907, 0.0010907, 0.001101685, 0.001017475,
    0.00113138, 0.001086615, 0.001076375, 0.001088265, 0.00106309,
    0.00106822, 0.001052205, 0.001106125, 0.001060125, 0.00106945,
    0.001092695, 0.00107696, 0.001063425, 0.001116725, 0.00105891,
    0.001054205, 0.00109295, 0.00109387, 0.00101807, 0.001066195,
    0.001120295, 0.001111565, 0.001088595, 0.00102183, 0.0010934,
    0.00111935, 0.00105371, 0.00108314, 0.0011006, 0.001079585,
    0.001127775, 0.001140825, 0.00106203, 0.001118035, 0.00103535,
    0.00099512, 0.001078955, 0.00108867, 0.0010789, 0.001030445,
    0.00106243, 0.001028545, 0.00108679, 0.00105624, 0.001110145,
    0.00107318, 0.00106523, 0.001103515, 0.00112404, 0.001064455,
    0.001040425, 0.001059305, 0.00106362, 0.001079395, 0.00107183,
    0.0010652, 0.00106983, 0.00111722, 0.00114111, 0.001059649,
    0.001029902, 0.001062825, 0.001102155, 0.001122135, 0.00103623,
    0.00108648, 0.001081035, 0.001110075, 0.001039397, 0.001057715,
    0.0010338, 0.001071455, 0.001072065, 0.001032233, 0.00111996,
    0.00106407, 0.0010693, 0.001104395)), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -222L), groups = structure(list(
    ID = structure(c(1L, 2L, 9L, 10L, 11L, 12L, 14L, 15L, 16L,
    19L, 20L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L,
    32L, 33L, 35L, 36L, 37L, 38L, 39L, 40L, 42L, 43L, 46L, 47L,
    48L, 49L, 50L, 51L, 52L, 53L, 55L, 56L, 57L, 58L, 60L, 61L,
    62L, 66L, 67L, 68L, 71L, 72L, 73L, 74L, 75L, 81L, 84L, 85L,
    93L, 95L, 96L, 104L, 107L, 109L, 116L, 126L, 133L, 135L,
    138L, 139L, 146L, 150L, 154L, 164L, 165L), .Label = c("33714",
    "35377", "38623", "38806", "39593", "39820", "39951", "40286",
    "40556", "40798", "40800", "40815", "43762", "50848", "52183",
    "52461", "52577", "53202", "53320", "53873", "54153", "54206",
    "54581", "55122", "55267", "55462", "55612", "55920", "56022",
    "56307", "56420", "56679", "57405", "57445", "57480", "57725",
    "57809", "58004", "58215", "58229", "58503", "59326", "59327",
    "59344", "59361", "59865", "60099", "60100", "60280", "60384",
    "60429", "60493", "60503", "60575", "60603", "60664", "60846",
    "61415", "61656", "61749", "61883", "62081", "62210", "62285",
    "62937", "62983", "63327", "63329", "64081", "64328", "64418",
    "64507", "64596", "65178", "65250", "65302", "65478", "65480",
    "65487", "65572", "65802", "65935", "65974", "65975", "65978",
    "65991", "65995", "66013", "66154", "66237", "66245", "66389",
    "66396", "66460", "66572", "66589", "67174", "73230", "73525",
    "73539", "73677", "73942", "73953", "74034", "74113", "74114",
    "74427", "74439", "74607", "74641", "74657", "74794", "74800",
    "74836", "74942", "74952", "74962", "74969", "74977", "74985",
    "74989", "75220", "75229", "75407", "75653", "75732", "75735",
    "75757", "75895", "75898", "76381", "76559", "76574", "76594",
    "76595", "76746", "76751", "76755", "76759", "76775", "77088",
    "77091", "77099", "77134", "77188", "77203", "77252", "77304",
    "77413", "77453", "77528", "77556", "77585", "77668", "78262",
    "79724", "79730", "79850", "79977", "80052", "80819", "80901",
    "80932", "81064", "81065", "81071", "81098", "81142", "81175"
    ), class = "factor"), .rows = structure(list(c(1L, 75L, 149L
    ), c(2L, 76L, 150L), c(3L, 77L, 151L), c(4L, 78L, 152L),
        c(5L, 79L, 153L), c(6L, 80L, 154L), c(7L, 81L, 155L),
        c(8L, 82L, 156L), c(9L, 83L, 157L), c(10L, 84L, 158L),
        c(11L, 85L, 159L), c(12L, 86L, 160L), c(13L, 87L, 161L
        ), c(14L, 88L, 162L), c(15L, 89L, 163L), c(16L, 90L,
        164L), c(17L, 91L, 165L), c(18L, 92L, 166L), c(19L, 93L,
        167L), c(20L, 94L, 168L), c(21L, 95L, 169L), c(22L, 96L,
        170L), c(23L, 97L, 171L), c(24L, 98L, 172L), c(25L, 99L,
        173L), c(26L, 100L, 174L), c(27L, 101L, 175L), c(28L,
        102L, 176L), c(29L, 103L, 177L), c(30L, 104L, 178L),
        c(31L, 105L, 179L), c(32L, 106L, 180L), c(33L, 107L,
        181L), c(34L, 108L, 182L), c(35L, 109L, 183L), c(36L,
        110L, 184L), c(37L, 111L, 185L), c(38L, 112L, 186L),
        c(39L, 113L, 187L), c(40L, 114L, 188L), c(41L, 115L,
        189L), c(42L, 116L, 190L), c(43L, 117L, 191L), c(44L,
        118L, 192L), c(45L, 119L, 193L), c(46L, 120L, 194L),
        c(47L, 121L, 195L), c(48L, 122L, 196L), c(49L, 123L,
        197L), c(50L, 124L, 198L), c(51L, 125L, 199L), c(52L,
        126L, 200L), c(53L, 127L, 201L), c(54L, 128L, 202L),
        c(55L, 129L, 203L), c(56L, 130L, 204L), c(57L, 131L,
        205L), c(58L, 132L, 206L), c(59L, 133L, 207L), c(60L,
        134L, 208L), c(61L, 135L, 209L), c(62L, 136L, 210L),
        c(63L, 137L, 211L), c(64L, 138L, 212L), c(65L, 139L,
        213L), c(66L, 140L, 214L), c(67L, 141L, 215L), c(68L,
        142L, 216L), c(69L, 143L, 217L), c(70L, 144L, 218L),
        c(71L, 145L, 219L), c(72L, 146L, 220L), c(73L, 147L,
        221L), c(74L, 148L, 222L)), ptype = integer(0), class = c("vctrs_list_of",
    "vctrs_vctr", "list"))), row.names = c(NA, -74L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE))

Which looks like:

# A tibble: 222 x 5
# Groups:   ID [74]
   ID    Timepoint_yrs Sex    Timepoint mean_AD
   <fct>         <int> <chr>  <chr>       <dbl>
 1 33714             0 Male   bl        0.00103
 2 35377             0 Female bl        0.00106
 3 40556             0 Male   bl        0.00114
 4 40798             0 Male   bl        0.00111
 5 40800             0 Male   bl        0.00105
 6 40815             0 Male   bl        0.00111
 7 50848             0 Male   bl        0.00109
 8 52183             0 Male   bl        0.00110
 9 52461             0 Male   bl        0.00104
10 53320             0 Male   bl        0.00112
# ... with 212 more rows

I want to pivot mean_AD wider across Timepoint. However, I get this odd result of NA values in some columns:

DF_wide<- DF %>%
  pivot_wider(names_from = Timepoint, values_from = mean_AD)

# A tibble: 221 x 6
# Groups:   ID [74]
   ID    Timepoint_yrs Sex         bl  flu1  flu2
   <fct>         <int> <chr>    <dbl> <dbl> <dbl>
 1 33714             0 Male   0.00103    NA    NA
 2 35377             0 Female 0.00106    NA    NA
 3 40556             0 Male   0.00114    NA    NA
 4 40798             0 Male   0.00111    NA    NA
 5 40800             0 Male   0.00105    NA    NA
 6 40815             0 Male   0.00111    NA    NA
 7 50848             0 Male   0.00109    NA    NA
 8 52183             0 Male   0.00110    NA    NA
 9 52461             0 Male   0.00104    NA    NA
10 53320             0 Male   0.00112    NA    NA
# ... with 211 more rows

The original DF posted above was created with:

 DF %>%
  group_by(ID) %>%
  mutate(Timepoint_yrs = Age - min(Age)) %>%
  filter(Age < 35) %>%
  dplyr::select(ID, Timepoint_yrs, Sex, Timepoint, mean_AD)

Expected output missing the Timepoint_yrs: (If I remove the group_by and mutate code lines, the pivot_wider function works properly.)

# A tibble: 74 x 5
   ID    Sex         bl    flu1    flu2
   <fct> <chr>    <dbl>   <dbl>   <dbl>
 1 33714 Male   0.00103 0.00106 0.00106
 2 35377 Female 0.00106 0.00101 0.00107
 3 40556 Male   0.00114 0.00111 0.00105
 4 40798 Male   0.00111 0.00113 0.00111
 5 40800 Male   0.00105 0.00105 0.00106
 6 40815 Male   0.00111 0.00108 0.00107
 7 50848 Male   0.00109 0.00110 0.00109
 8 52183 Male   0.00110 0.00109 0.00108
 9 52461 Male   0.00104 0.00106 0.00106
10 53320 Male   0.00112 0.00113 0.00112
# ... with 64 more rows

I'm not sure why this is not working?

Body:
There was a column that was not needed - Timepoint_yrs, select out the column and then it should work.  When we use the 'Timepoint_yrs' also in the code, it will look for the match for the value corresponding to that column as well

library(dplyr)
library(tidyr)
DF %>%
   ungroup %>%
   select(-Timepoint_yrs) %>%
   pivot_wider(names_from = Timepoint, values_from = mean_AD)

-output

# A tibble: 74 × 5
   ID    Sex         bl    flu1    flu2
   <fct> <chr>    <dbl>   <dbl>   <dbl>
 1 33714 Male   0.00103 0.00106 0.00106
 2 35377 Female 0.00106 0.00101 0.00107
 3 40556 Male   0.00114 0.00111 0.00105
 4 40798 Male   0.00111 0.00113 0.00111
 5 40800 Male   0.00105 0.00105 0.00106
 6 40815 Male   0.00111 0.00108 0.00107
 7 50848 Male   0.00109 0.00110 0.00109
 8 52183 Male   0.00110 0.00109 0.00108
 9 52461 Male   0.00104 0.00106 0.00106
10 53320 Male   0.00112 0.00113 0.00112
# … with 64 more rows


问:
Cannot update UI using the UI thread Dispatcher?
I designed a WPF application based on MVVM pattern and I need to get large amount of data from a webservice, and i do it with a BackgroundWorker inside the ViewModel. To modify the observable collection i have to use a dispatcher and the problem is here, even if i pass by reference UI Dispatcher it dosen't work, it is like I use the inner dispatcher and my application get freezed until all data are retrived.

I try to get the UI Dispatcher in several ways, Dispatcher.CurrentDispatcher, Application.Dispatcher, App.Current.Dispatcher... doing some researches I read that it should be works, does someone have any suggestions?

Thank you
Marco

Update

Here some code: This is how I pass the Dispatcher to the ModelView

```<code>void AppWindow_Loaded(object sender, RoutedEventArgs e)
{
     this.DataContext = new ModelViewApplication(System.Windows.Threading.Dispatcher.CurrentDispatcher);
}
</code>```

Then I try to get data in this way

```<code>public ModelViewApplication(Dispatcher _dispatcher)
{
    BackgroundWorker bw = new BackgroundWorker();
    bw.DoWork += new DoWorkEventHandler(getData);
    bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(completedData);

    bw.RunWorkerAsync();
}

public void getData(object sender, DoWorkEventArgs e)
{
    _dispatcher.Invoke(DispatcherPriority.Normal,
        new Action(
            delegate()
                 {
                 //Connect to webservice and retrieve data
                 ....
                 }));
}
</code>```

It seems like the multithread dosen't work

答:
Use the BackgroundWorker to get your data, then use the RunWorkerCompleted to update the ObservableCollection. You shouldn't need the Dispatcher at all

```<code>public ModelViewApplication()
{
    BackgroundWorker bw = new BackgroundWorker();
    bw.DoWork += new DoWorkEventHandler(getData);
    bw.RunWorkerCompleted += completedData;

    bw.RunWorkerAsync();
}

public void getData(object sender, DoWorkEventArgs e)
{
    //Connect to webservice and retrieve data
    e.Result = WebService.GetData();
}

private void completedData(object sender, RunWorkerCompletedEventArgs e)
{
    MyCollection = new ObservableCollection<SomeClass>((IList)e.Results);
}
</code>```

Body:
I designed a WPF application based on MVVM pattern and I need to get large amount of data from a webservice, and i do it with a BackgroundWorker inside the ViewModel. To modify the observable collection i have to use a dispatcher and the problem is here, even if i pass by reference UI Dispatcher it dosen't work, it is like I use the inner dispatcher and my application get freezed until all data are retrived.

I try to get the UI Dispatcher in several ways, Dispatcher.CurrentDispatcher, Application.Dispatcher, App.Current.Dispatcher... doing some researches I read that it should be works, does someone have any suggestions?

Thank you
Marco

Update

Here some code: This is how I pass the Dispatcher to the ModelView

void AppWindow_Loaded(object sender, RoutedEventArgs e)
{
     this.DataContext = new ModelViewApplication(System.Windows.Threading.Dispatcher.CurrentDispatcher);
}

Then I try to get data in this way

public ModelViewApplication(Dispatcher _dispatcher)
{
    BackgroundWorker bw = new BackgroundWorker();
    bw.DoWork += new DoWorkEventHandler(getData);
    bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(completedData);

    bw.RunWorkerAsync();
}

public void getData(object sender, DoWorkEventArgs e)
{
    _dispatcher.Invoke(DispatcherPriority.Normal,
        new Action(
            delegate()
                 {
                 //Connect to webservice and retrieve data
                 ....
                 }));
}

It seems like the multithread dosen't work

Body:
Use the BackgroundWorker to get your data, then use the RunWorkerCompleted to update the ObservableCollection. You shouldn't need the Dispatcher at all

public ModelViewApplication()
{
    BackgroundWorker bw = new BackgroundWorker();
    bw.DoWork += new DoWorkEventHandler(getData);
    bw.RunWorkerCompleted += completedData;

    bw.RunWorkerAsync();
}

public void getData(object sender, DoWorkEventArgs e)
{
    //Connect to webservice and retrieve data
    e.Result = WebService.GetData();
}

private void completedData(object sender, RunWorkerCompletedEventArgs e)
{
    MyCollection = new ObservableCollection<SomeClass>((IList)e.Results);
}


问:
Expected 2D array, got 1D array instead, how to solve the one with dataset
```<code>dataset = pd.read_csv('Folsom_irradiance.csv', encoding='gbk')
dataset = pd.DataFrame(dataset)
dataPOV = dataset['ghi']
dataPOV = np.array(dataPOV).reshape(-1,1)
print("dataPOV:",dataPOV.shape)
N1=70000
N2 = N1+10000
dataAll = dataPOV[:N2,:]

global scaler
scaler = StandardScaler(copy=True,with_mean=True,with_std=True)
dataAll = scaler.fit_transform(dataAll)
</code>```
```<code>ValueError: Expected 2D array, got 1D array instead:
array=[-1.21897049 -1.22302263 -1.21675063 ...  1.6377127   1.56019364
  1.84912833].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
</code>```

got this error, how do i reshape the it ?, not sure what i'm doing wrong here

答:
You need a minimal reproducible example. This works</p>
```<code>import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler

dataset = pd.DataFrame(data=np.random.random((100000, 2)), columns=['ghi', 'jkl'])
dataPOV = dataset['ghi']
dataPOV = np.array(dataPOV).reshape(-1,1)
N1=70000
N2 = N1+10000
dataAll = dataPOV[:N2,:]
scaler = StandardScaler(copy=True,with_mean=True,with_std=True)
dataAll = scaler.fit_transform(dataAll)
</code>```

Body:
dataset = pd.read_csv('Folsom_irradiance.csv', encoding='gbk')
dataset = pd.DataFrame(dataset)
dataPOV = dataset['ghi']
dataPOV = np.array(dataPOV).reshape(-1,1)
print("dataPOV:",dataPOV.shape)
N1=70000
N2 = N1+10000
dataAll = dataPOV[:N2,:]

global scaler
scaler = StandardScaler(copy=True,with_mean=True,with_std=True)
dataAll = scaler.fit_transform(dataAll)

ValueError: Expected 2D array, got 1D array instead:
array=[-1.21897049 -1.22302263 -1.21675063 ...  1.6377127   1.56019364
  1.84912833].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

got this error, how do i reshape the it ?, not sure what i'm doing wrong here

Body:
You need a minimal reproducible example. This works

import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler

dataset = pd.DataFrame(data=np.random.random((100000, 2)), columns=['ghi', 'jkl'])
dataPOV = dataset['ghi']
dataPOV = np.array(dataPOV).reshape(-1,1)
N1=70000
N2 = N1+10000
dataAll = dataPOV[:N2,:]
scaler = StandardScaler(copy=True,with_mean=True,with_std=True)
dataAll = scaler.fit_transform(dataAll)