问:
iText7 pdfHTML - TOC Generation
My use case for pdfHTML generation is as follows.

I have several individual reports being generated in HTML format by external API's (say Rep1.html, Rep2.html,..,Rep10.html)

I have an Orchestrating API that need to merge these HTML files as a SINGLE pdf document

Assume that Step 2 can read these files from a source directory

Question: In the pdf Merge process, how do I create a TOC that references all 10 reports? There is an earlier post from Alexy (Adding Table of Content with pdfHTML in iText7) that addresses this for a Single HTML file which entails adding a special tag [data-toc] by parsing the HTML file

In my case, when the individual html files are created, I can also create the required special tags. So if it a given that the individual html files will have the special tag, how do I render the TOC with the page numbers that will reflect the content location of the final pdf doc?

Title: iText7 pdfHTML - TOC Generation


来源: stackexchange

问:
Cannot add or update a child row. Sequalize
I have a problem from create or update database with sequalize.
I have a 4 tables. Orders | OrderDrinkConfig | OrderAlcoFreeDrink | AlcoFreeDrinks. Relationship look like this

My post route look like this
`

```<code>router.post('/', async function (req, res, next) {
    const { bootle, unit, size, alcoFreeDrinks } = req.body;
    const order = req.elInstance; // from midleware order ref
    if (!order) {
        Utils.errorHandle(404, res, 'Nie można stworzyć konfiguracji drinków. Zamówienie nie istnieje');
        return;
    }

    if (!bootle && !unit && !size) {
        Utils.errorHandle(400, res, 'Nie przesłano wymaganych danych');
        return;
    }

    const el = await OrderDrinkConfig.create({ bootle, unit, size });
    if (el) {
        try {
            await el.setAlcoFreeDrinks(alcoFreeDrinks);
            await el.save();
            order.setOrderDrinkConfig(el.id).then(() => res.send(el)).catch(err => next(err));
            // await el.setAlcoFreeDrinks([1]);
        } catch (err) {
            next(err)
        }
    } else {
        next(err);
    }
});
</code>```

I make post request and apps crashing with error

```<code> sqlMessage: 'Cannot add or update a child row: a foreign key constraint fails (`weddingHouse`.`OrderAlcoFreeDrinks`, CONSTRAINT `OrderAlcoFreeDrinks_ibfk_1` FOREIGN KEY (`orderDrinkConfigId`) REFERENCES `Orders` (`id`))',
    sql: 'INSERT INTO `OrderAlcoFreeDrinks` (`OrderDrinkConfigId`,`AlcoFreeDrinkId`) VALUES (49,1);',
    parameters: undefined
</code>```

`

i try create new instance OrderDrinkConfig and next save id to Order.drinkId but dont work

ContentLicense: CC BY-SA 4.0

Body:
I have a problem from create or update database with sequalize.
I have a 4 tables. Orders | OrderDrinkConfig | OrderAlcoFreeDrink | AlcoFreeDrinks. Relationship look like this

My post route look like this
`

router.post('/', async function (req, res, next) {
    const { bootle, unit, size, alcoFreeDrinks } = req.body;
    const order = req.elInstance; // from midleware order ref
    if (!order) {
        Utils.errorHandle(404, res, 'Nie można stworzyć konfiguracji drinków. Zamówienie nie istnieje');
        return;
    }

    if (!bootle && !unit && !size) {
        Utils.errorHandle(400, res, 'Nie przesłano wymaganych danych');
        return;
    }

    const el = await OrderDrinkConfig.create({ bootle, unit, size });
    if (el) {
        try {
            await el.setAlcoFreeDrinks(alcoFreeDrinks);
            await el.save();
            order.setOrderDrinkConfig(el.id).then(() => res.send(el)).catch(err => next(err));
            // await el.setAlcoFreeDrinks([1]);
        } catch (err) {
            next(err)
        }
    } else {
        next(err);
    }
});

I make post request and apps crashing with error

 sqlMessage: 'Cannot add or update a child row: a foreign key constraint fails (`weddingHouse`.`OrderAlcoFreeDrinks`, CONSTRAINT `OrderAlcoFreeDrinks_ibfk_1` FOREIGN KEY (`orderDrinkConfigId`) REFERENCES `Orders` (`id`))',
    sql: 'INSERT INTO `OrderAlcoFreeDrinks` (`OrderDrinkConfigId`,`AlcoFreeDrinkId`) VALUES (49,1);',
    parameters: undefined

`

i try create new instance OrderDrinkConfig and next save id to Order.drinkId but dont work


问:
How to check in an efficient way if a Philips HUE motion sensor detects motion?
I am coding a little app that is checking whenever a Philips HUE motion sensor detects presence in a quite reactive way.

At the moment I am polling its presence status every 2 seconds using the HUE V1 API: get-sensor

I am wondering if there is a better/efficient way to do it since this application is running on a little controller, so I would like to avoid to stress it with continuous polling and I also wondering if doing that will also drain out the sensor battery in a few days.


问:
Qt on Android crashes with "java.lang.UnsatisfiedLinkError"
From some devices we keep getting crash reports, with the following stack frame:

```<code>Exception java.lang.UnsatisfiedLinkError:
  at java.lang.Runtime.load0 (Runtime.java:929)
  at java.lang.System.load (System.java:1625)
  at org.qtproject.qt5.android.QtNative$4.run (QtNative.java:505)
  at org.qtproject.qt5.android.QtThread$2.run (QtThread.java:87)
  at org.qtproject.qt5.android.QtThread$1.run (QtThread.java:61)
  at java.lang.Thread.run (Thread.java:1012)
</code>```

Unfortunately, as you may see, the stack frame nowhere mentions the missing dependency.

The crash occurs during app's initialization, not even the window gets rendered.

Qt 5.15.2

Ideas?

Body:
From some devices we keep getting crash reports, with the following stack frame:

Exception java.lang.UnsatisfiedLinkError:
  at java.lang.Runtime.load0 (Runtime.java:929)
  at java.lang.System.load (System.java:1625)
  at org.qtproject.qt5.android.QtNative$4.run (QtNative.java:505)
  at org.qtproject.qt5.android.QtThread$2.run (QtThread.java:87)
  at org.qtproject.qt5.android.QtThread$1.run (QtThread.java:61)
  at java.lang.Thread.run (Thread.java:1012)

Unfortunately, as you may see, the stack frame nowhere mentions the missing dependency.

The crash occurs during app's initialization, not even the window gets rendered.

Qt 5.15.2

Ideas?


问:
Jest - Changing process.env value takes effect only in the next test case
I'm faced with the following issue. I'm testing a functionality with different behaviour based on process.env.NODE_ENV variable. Here is a short snippet of logic I aim to test

  if (process.env.NODE_ENV === 'production') {
    // this is what I aim to cover
  }
```
<p>Here is a snippet of my suite:</p>
<pre class="lang-js prettyprint-override"><code>  test('case 1', () => {
    const result = method.call()

    expect(result).toEqual(something)
  })

  test('case 2, with process.env.NODE_ENV set to "production"', () => {
    process.env.NODE_ENV = 'production'

    const result = method.call()

    expect(result).toEqual(somethingElse)
  })
</code>```

After running the tests, the conditional requirement regarding NODE_ENV being set to production is not met and if statement from the first snippet is not covered. There's a peculiar thing I noticed with a scenario like this:

  test('case 1', () => {
    process.env.NODE_ENV = 'production'

    const result = method.call()

    expect(result).toEqual(something)
  })

  test('case 2, with process.env.NODE_ENV set to "production"', () => {
    const result = method.call()

    expect(result).toEqual(somethingElse)
  })
```

Now tests behave as I want them to, meaning process.env.NODE_ENV is set to production in case 2 and the if statement is covered. Can anyone explain why this happens? It appears as if the change of process.env takes effect only in the next suites.

Body:
I'm faced with the following issue. I'm testing a functionality with different behaviour based on process.env.NODE_ENV variable. Here is a short snippet of logic I aim to test

  if (process.env.NODE_ENV === 'production') {
    // this is what I aim to cover
  }

Here is a snippet of my suite:

  test('case 1', () => {
    const result = method.call()

    expect(result).toEqual(something)
  })

  test('case 2, with process.env.NODE_ENV set to "production"', () => {
    process.env.NODE_ENV = 'production'

    const result = method.call()

    expect(result).toEqual(somethingElse)
  })

After running the tests, the conditional requirement regarding NODE_ENV being set to production is not met and if statement from the first snippet is not covered. There's a peculiar thing I noticed with a scenario like this:

  test('case 1', () => {
    process.env.NODE_ENV = 'production'

    const result = method.call()

    expect(result).toEqual(something)
  })

  test('case 2, with process.env.NODE_ENV set to "production"', () => {
    const result = method.call()

    expect(result).toEqual(somethingElse)
  })

Now tests behave as I want them to, meaning process.env.NODE_ENV is set to production in case 2 and the if statement is covered. Can anyone explain why this happens? It appears as if the change of process.env takes effect only in the next suites.


问:
Yocto add pre-built binaries
I have the issue with adding pre-compiled binaries to Yocto image

I need to add pre-built binaries to Yocto image. All binaries linked statically. I created the layer, added it. This is bb:
`

```<code>DESCRIPTION = "Test release"
SECTION = "test"
LICENSE = "CLOSED"
SRC_URI += "file://opt/test"
S = "${WORKDIR}"
#### part of the recipe ####
do_install () {
        install -d ${D}/opt
        cp -R --no-dereference --preserve=mode,links -v ${WORKDIR}/opt/* ${D}/opt/
}
FILES:${PN} += "${base_prefix}/opt/test"
INSANE_SKIP_${PN} = "file-rdeps"

`
but I have error:

`ERROR: test-1.0-r0 do_package_qa: QA Issue: /opt/test contained in package platform requires libssl.so.1.1()(64bit), but no providers found in RDEPENDS:test? [file-rdeps]`

Can anyone help?
</code>```

Title: Yocto add pre-built binaries

Body:
I have the issue with adding pre-compiled binaries to Yocto image

I need to add pre-built binaries to Yocto image. All binaries linked statically. I created the layer, added it. This is bb:
`

DESCRIPTION = "Test release"
SECTION = "test"
LICENSE = "CLOSED"
SRC_URI += "file://opt/test"
S = "${WORKDIR}"
#### part of the recipe ####
do_install () {
        install -d ${D}/opt
        cp -R --no-dereference --preserve=mode,links -v ${WORKDIR}/opt/* ${D}/opt/
}
FILES:${PN} += "${base_prefix}/opt/test"
INSANE_SKIP_${PN} = "file-rdeps"

`
but I have error:

`ERROR: test-1.0-r0 do_package_qa: QA Issue: /opt/test contained in package platform requires libssl.so.1.1()(64bit), but no providers found in RDEPENDS:test? [file-rdeps]`

Can anyone help?


问:
How can you write to a buffer with wav.NewEncoder instead of a file in Golang?
```<code>package main

import (
    "bytes"
    "fmt"

    "github.com/go-audio/wav"
)

func main() {
    buf := &bytes.Buffer{}

    encoder := wav.NewEncoder(buf, 44100, 16, 1, 1)
    if err := encoder.Write([]int16{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}); err != nil {
        panic(err)
    }
    if err := encoder.Close(); err != nil {
        panic(err)
    }

    // Print the contents of the buffer.
    fmt.Println(buf.String())
}

</code>```

This returns: cannot use buf (variable of type *bytes.Buffer) as type io.WriteSeeker in argument to wav.NewEncoder:
*bytes.Buffer does not implement io.WriteSeeker (missing Seek method)

This is not the same as using io.Readseeker as in Using an io.WriteSeeker without a File in Go (1 answer)
io.WriteSeeker and io.ReadSeeker from []byte or file (3 answers)

Body:
package main

import (
    "bytes"
    "fmt"

    "github.com/go-audio/wav"
)

func main() {
    buf := &bytes.Buffer{}

    encoder := wav.NewEncoder(buf, 44100, 16, 1, 1)
    if err := encoder.Write([]int16{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}); err != nil {
        panic(err)
    }
    if err := encoder.Close(); err != nil {
        panic(err)
    }

    // Print the contents of the buffer.
    fmt.Println(buf.String())
}

This returns: cannot use buf (variable of type *bytes.Buffer) as type io.WriteSeeker in argument to wav.NewEncoder:
*bytes.Buffer does not implement io.WriteSeeker (missing Seek method)

This is not the same as using io.Readseeker as in Using an io.WriteSeeker without a File in Go (1 answer)
io.WriteSeeker and io.ReadSeeker from []byte or file (3 answers)


问:
Using CData to migrate data from SQL Server to MariaDB?
I am trying to migrate a table called table1 in SQL Server with the following details:

username
account_name
description
change_date

nvarchar(255)
nvarchar(255)
nvarchar(255)
date

primary_key

I am using CData to migrate this table to my MariaDB database. If anyone here is familiar with CData, the command I am using to migrate the table is REPLICATE [dbo].[table1]. When I run the code in CData, I am getting an error stating: BLOB/TEXT column 'username' used in key specification without key length (1170). I don't understand this error because I do not have a BLOB/TEXT column in my table anywhere. When migrating the data to MariaDB, nvarchar should convert to varchar (which it has done for my other tables so not sure why this is causing an issue here). Is it because it's the primary key? I can't delete the PK on this table, I need it there so I'm not sure how to fix this issue.


问:
Vue.js + Element-ui Upload: how to call method before-upload
the upload working fine except handleBeforeUpload didn't call, anything I miss?

I want to limit user select file to csv type only.

I am using vue3 with composition api with Element-plus ui. I know that Element-plus official website have a complete example but it's using typescript.

element-plus version = "element-plus": "^2.2.16",

Thank you in advance.

<template>

                Response CSV

            <el-upload
                v-model:file-list="fileList"
                class="upload-demo"
                action=""
                :before-upload="handleBeforeUpload"
                :multiple="false"
                :limit="1"
                :auto-upload="false"
            >
                <template #trigger>
                    <el-button type="primary">select file</el-button>
                </template>
                <el-button class="ml-3" type="success" @click="submitForm" :disabled="hasSelectedFile">
                    upload to server
                </el-button>
            </el-upload>

                <CsvTable :data="cvsFiles"/>

</template>

```

Edit:
I found this example online, and it work.
just can't figure out what is the difference.
https://codepen.io/pen?editors=1111

Body:
the upload working fine except handleBeforeUpload didn't call, anything I miss?

I want to limit user select file to csv type only.

I am using vue3 with composition api with Element-plus ui. I know that Element-plus official website have a complete example but it's using typescript.

element-plus version = "element-plus": "^2.2.16",

Thank you in advance.

<template>

                Response CSV

            <el-upload
                v-model:file-list="fileList"
                class="upload-demo"
                action=""
                :before-upload="handleBeforeUpload"
                :multiple="false"
                :limit="1"
                :auto-upload="false"
            >
                <template #trigger>
                    <el-button type="primary">select file</el-button>
                </template>
                <el-button class="ml-3" type="success" @click="submitForm" :disabled="hasSelectedFile">
                    upload to server
                </el-button>
            </el-upload>

                <CsvTable :data="cvsFiles"/>

</template>

Edit:
I found this example online, and it work.
just can't figure out what is the difference.
https://codepen.io/pen?editors=1111


问:
How do I make my program have the decimal value and character that goes with it?
I want to convert Binary to a Character using JavaScript. I already have a binary to decimal converter. Now I need a decimal to Char converter. What is the best way to make my program have the decimal value of each Char without using a ton of separate variables, or a ton of if statements to determine the char? I am only working with ASCII.

Note:
I am not running it in a web browser. I am just running it directly in VS Code if that makes a difference

Edit:
I have a bin to dec converter. Now I need to convert dec to char.

I'm not really sure what to try.


问:
How to Embed Barcode Scanner to Website and Append result to url?
I want to embed a barcode scanner to website and when the barcode is scanned, the result will be appended to an url parameter for ex. https://example.com/?barcoderesult=xxxxxxxxxx and then redirected there

If there are any free or at least where to start reading because I am totally lost. I tried mebja barcode scanner but did not achieve the expected results.


问:
Flutter. Why does the keyboard (focus) appear and immediately disappear when i click on the input?
The question will be about the Flutter application.

There are two pages. On the first form with text inputs. On the second ListView.builder()

If i first open the page with the ListView, and then the page with the form. Then when i click on the input, the keyboard first appears for a moment and the focus and keyboard immediately disappear. And so it continues until the application is restarted.

But if i first open the form, then the inputs work fine.

What could be the problem?

P.S. Tried both unfocus() and wrapping the form or list in Focus, nothing helps!

Video of problem:
https://www.veed.io/view/24122e64-e6a4-430f-a914-4e25a62f1959?sharingWidget=true&panel=share

ListView:
If I remove the list from the second page, then the form on the first page working correctly anyway

```<code>_controller = ScrollController(initialScrollOffset: _leftPadding);

ListView.builder(
  controller: _controller,
  scrollDirection: Axis.horizontal,
  itemCount: null,
  itemBuilder: (context, index) {
     /// Some code here thats returned Container()
  }
);
</code>```

Form and TextField without any controllers:

```<code>Form(key: formKey, child: Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
       TextFormField(
         minLines: 10,
         maxLines: 15,
         keyboardType: TextInputType.multiline,
         textCapitalization: TextCapitalization.sentences,
         validator: validator,
         /// Simple TextFormField only with validator
       )
    ]
));
</code>```

Body:
The question will be about the Flutter application.

There are two pages. On the first form with text inputs. On the second ListView.builder()

If i first open the page with the ListView, and then the page with the form. Then when i click on the input, the keyboard first appears for a moment and the focus and keyboard immediately disappear. And so it continues until the application is restarted.

But if i first open the form, then the inputs work fine.

What could be the problem?

P.S. Tried both unfocus() and wrapping the form or list in Focus, nothing helps!

Video of problem:
https://www.veed.io/view/24122e64-e6a4-430f-a914-4e25a62f1959?sharingWidget=true&panel=share

ListView:
If I remove the list from the second page, then the form on the first page working correctly anyway

_controller = ScrollController(initialScrollOffset: _leftPadding);

ListView.builder(
  controller: _controller,
  scrollDirection: Axis.horizontal,
  itemCount: null,
  itemBuilder: (context, index) {
     /// Some code here thats returned Container()
  }
);

Form and TextField without any controllers:

Form(key: formKey, child: Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
       TextFormField(
         minLines: 10,
         maxLines: 15,
         keyboardType: TextInputType.multiline,
         textCapitalization: TextCapitalization.sentences,
         validator: validator,
         /// Simple TextFormField only with validator
       )
    ]
));


问:
How to download a file from RStudio server using a function?
I'm trying to download a local file I have on RStudio hosted on a server, but programmatically with a script/function (instead of clicking Files > Check on file > More > Export in the UI).

I've tried with download.file() but it requires an url (instead of the local file) and destfile instead of simply downloading it in my browser as any file downloads.

Is it even possible to achieve with a function I don't know of? Maybe with system() somehow? Ideally if it's resilient to any tool running R, say Jupyter notebooks. Thanks!


问:
Why is my component not rendering in react-router-dom v6 using hashrouter?
Using react-router-dom v6.5.0

index.js

```<code>ReactDOM.render(
  <HashRouter history={history} >
    <Provider store={store}>
      <SnackbarProvider
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'right',
        }}
      >
        <App />
      </SnackbarProvider>
    </Provider>
  </HashRouter>,
  document.getElementById('root')
);
</code>```

App.js

```<code>const App = (props) => {
  return (
        <div>
            <Suspense fallback={<div>Loading...</div>}>
              <Routes>
                <Route path='/*' element={<Splashpage userInfo={userInfo.toJS()} />}/>
                <Route path='cats' element={<Cats />} />
              </Routes >
        </div >
  );
};
</code>```

My splashpage loads fine, although it has an extra "/" in the url. But when I go to "#cats" (using hashrouter) it says no routes matched. Changing the route path to "/cats" doesn't work either. However "/#/cats" renders Cats. How can I make it so Cats renders on "#cats"?

Body:
Using react-router-dom v6.5.0

index.js

ReactDOM.render(
  <HashRouter history={history} >
    <Provider store={store}>
      <SnackbarProvider
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'right',
        }}
      >
        <App />
      </SnackbarProvider>
    </Provider>
  </HashRouter>,
  document.getElementById('root')
);

App.js

const App = (props) => {
  return (

            <Suspense fallback={
Loading...
}>
              <Routes>
                <Route path='/*' element={<Splashpage userInfo={userInfo.toJS()} />}/>
                <Route path='cats' element={<Cats />} />
              </Routes >

  );
};

My splashpage loads fine, although it has an extra "/" in the url. But when I go to "#cats" (using hashrouter) it says no routes matched. Changing the route path to "/cats" doesn't work either. However "/#/cats" renders Cats. How can I make it so Cats renders on "#cats"?


问:
React unable to get the value of the child attribute of the object
I have the following object in formikValues,

```<code>formikValues: {
TEST_8496_DROPDOWN: "2"
}

</code>```

Below is my full code snippet,

```<code>const gridDataOptionsSource = getGridDataOptionsSource(field);
  let optionsDropdownValue;
  if (gridDataOptionsSource) {
    optionsDropdownValue = formikValues?.gridDataOptionsSource;

</code>```

I expect my optionsDropdownValue to be "2".
Still, my optionsDropdownValue is undefined. What am I doing wrong?

Body:
I have the following object in formikValues,

formikValues: {
TEST_8496_DROPDOWN: "2"
}

Below is my full code snippet,

const gridDataOptionsSource = getGridDataOptionsSource(field);
  let optionsDropdownValue;
  if (gridDataOptionsSource) {
    optionsDropdownValue = formikValues?.gridDataOptionsSource;

I expect my optionsDropdownValue to be "2".
Still, my optionsDropdownValue is undefined. What am I doing wrong?


问:
How to make a PayPal payment between 2 clients?
I don't have a great idea on how PayPal works and I'm working on an android app ( using Nodejs for backend )   where customers sell and buy products from each other ( a market place ) .

For example :

Customer A is selling a product

Customer B is going to buy the product that A is selling and going to pay him using PayPal .

How can I make  this transaction happen and make sure the money goes to A .


问:
Unable to set public static property of object that is mocked
I'm trying to mock a static method of a class.  I'm using mockery + phpunit to create the mock but Im getting an error when trying to set a global static variable.

My Mock

```<code>$mock = Mockery::mock('alias:'.S3::class);

$mock->shouldReceive('deleteObjects')->times(3)->andReturn(true);
</code>```

My Code I'm Testing

```<code>$status = array(
    'status' => 'failes'
);
S3::$bucket = env('AWS_S3_CLINIC_LOGOS_BUCKET');

$this->Clinic->recursive = -1;
$uuid = $this->Clinic->findById($clinicId,array('uuid'))['Clinic']['uuid'];

$paths = array(
    'locations' => 'clinics' . DS . $uuid . DS. 'locations',
    'services' => 'clinics'. DS . $uuid. DS .'services',
    'appIcon' => 'clinics'.DS.$uuid. DS . 'app-icon.png'
);

foreach($paths as $path){
    $response = S3::deleteObjects($path);
}

if($response){
    $status = array(
        'status' => 'completed',
        'resource' => 'PFE Asset Delete'
    );
}

return $status;
}
</code>```

The S3::$bucket throws an error Access to undeclared static property: S3::$bucket. But when I do S3::deleteObjects it returns true so I know my mock is working. Do I need to call a different mockery function to intercept the bucket set or is this just impossible to do with mockery?

Body:
I'm trying to mock a static method of a class.  I'm using mockery + phpunit to create the mock but Im getting an error when trying to set a global static variable.

My Mock

$mock = Mockery::mock('alias:'.S3::class);

$mock->shouldReceive('deleteObjects')->times(3)->andReturn(true);

My Code I'm Testing

$status = array(
    'status' => 'failes'
);
S3::$bucket = env('AWS_S3_CLINIC_LOGOS_BUCKET');

$this->Clinic->recursive = -1;
$uuid = $this->Clinic->findById($clinicId,array('uuid'))['Clinic']['uuid'];

$paths = array(
    'locations' => 'clinics' . DS . $uuid . DS. 'locations',
    'services' => 'clinics'. DS . $uuid. DS .'services',
    'appIcon' => 'clinics'.DS.$uuid. DS . 'app-icon.png'
);

foreach($paths as $path){
    $response = S3::deleteObjects($path);
}

if($response){
    $status = array(
        'status' => 'completed',
        'resource' => 'PFE Asset Delete'
    );
}

return $status;
}

The S3::$bucket throws an error Access to undeclared static property: S3::$bucket. But when I do S3::deleteObjects it returns true so I know my mock is working. Do I need to call a different mockery function to intercept the bucket set or is this just impossible to do with mockery?


问:
React-Dropzone-Uploader unable to test file upload
I am building a site in Typescript with REACT.  I am using react-dropzone-uploader to handle file uploads in a form.  Uploads work in the broswer just fine.

However, I cannot get upload() from Testing Library to work.

The code examples from test Library work with their jsx and when modified with my helper methods.  However, When I copy the same basic logic to my react-dropzone-uploader code it doesn't work. The onChangeEvent never seems to fire.

Works

```<code>test('upload file', async () =>
   {
    renderWithProviders(
      <div>
        <label htmlFor="file-uploader">Upload file:
          <input id="file-uploader" type="file" />
        </label>
      </div>
    );

    const file = new File(['hello'], 'hello.png', {type: 'image/png'});
    const input = screen.getByLabelText(startsWith('Upload file'));

    screen.debug(input);

    await userEvent.upload(input, file);

    expect(input.files[0]).toBe(file);
    expect(input.files.item(0)).toBe(file);
    expect(input.files).toHaveLength(1);
  })
</code>```

Doesn't Work

```<code> test('FileUpload widget displays successfully', async () =>
  {
    const uploadDone = jest.fn();
    renderWithProviders(<FileUpload whenUploadComplete={uploadDone} />);

    const dropZone = screen.getByLabelText(startsWith('Drag and Drop a File,'));

    expect(dropZone).toBeInTheDocument();
    screen.debug(dropZone);

    expect(screen.getByTestId('dzu-input-id')).toBeInTheDocument();

    //resolves a file from project root instead of file.
    const logoFile = loadLocalFile(path.resolve('./src/images/logo.svg'));

    //await userEvent.upload(screen.getByTestId('dzu-input-id'), logoFile);
    await userEvent.upload(dropZone, logoFile);

    expect(uploadDone).toHaveBeenCalled()
   });
</code>```

FileUpload Wrapper for react-dropzone-uploader

```<code>import React from 'react';
import Dropzone,
       { IDropzoneProps, IFileWithMeta, StatusValue }
       from "react-dropzone-uploader";
import './FileUpload.css'; //copy of React-dropzone-uploader default css
import { theme } from "../shared/theme";
import * as mime from 'mime-types';

export interface fileUploadProps {
  uploadUrl?: string; //allows override for testing
  whenUploadComplete(file: File): void;
}

//TODO: move to test files later
export const devDoNothingUploadUrl = 'https://httpbin.org/post';

export const defaultUploadUrl = devDoNothingUploadUrl;

const FileUpload: React.FC<fileUploadProps> = (props) =>
{
  const { uploadUrl, whenUploadComplete } = props;
  const uploadToUrl = uploadUrl ? uploadUrl : defaultUploadUrl;

  //TODO: MUI Snackbar
  const message = (msg: string) => { console.log(msg); } //{ alert(msg); }

  //TODO: S3 https://react-dropzone-uploader.js.org/docs/s3
  //const getUploadParams = ({meta}:IFileWithMeta) =>
  const getUploadParams: IDropzoneProps['getUploadParams'] = () =>
  { return { url: uploadToUrl } }

  const handleChangeStatus: IDropzoneProps['onChangeStatus'] =
                            ({ meta, file, remove }, status) =>
  {
    setTimeout(() => {}, 1000);
    //console.log(status, meta);
    switch(status)
    {
      case 'ready':
      case 'preparing':
        message(`${meta.name} Preparing for Upload`);
        break;
      case 'started':
      case 'uploading':
      case 'restarted':
        message(`${meta.name} InProgress`);
        break;
      case 'error_file_size':
      case 'error_upload':
      case 'error_upload_params':
      case 'error_validation':
      case 'exception_upload':
      case 'rejected_file_type':
      case 'rejected_max_files':
        message(`${meta.name} ERROR!`);
        //TODO: code to catch and log error
        break;
      case 'done':
        whenUploadComplete(file);
        break;
      case 'headers_received':
        message(`${meta.name} Upload Complete!`);
        //remove();
    }
    return { meta: { meta } };
  }

  const logStatusChange: IDropzoneProps['onChangeStatus'] =
                         ({ meta }, status) =>
  { console.log(status, meta, meta.name) }

  const handleSubmit = (files: IFileWithMeta[], allFiles: IFileWithMeta[]) =>
  {
    console.log('files-meta:' + files.map(f => f.meta));
    allFiles.forEach(f => f.remove());
  }

  return (
    <Dropzone
      maxFiles={1} multiple={false}
      inputContent='Drag and Drop a File, or Click to Browse.'
      getUploadParams={getUploadParams}
      onChangeStatus={handleChangeStatus}
      //onChangeStatus={logStatusChange}
      //onSubmit={handleSubmit}
      styles={{ inputLabel: { color: theme.palette.text.secondary }, }}
      submitButtonDisabled={true}
    />
  )
}

export default FileUpload;
</code>```

So How can I test Uploads?

My finish function never gets called, and I can never seem to find updated UI page elements either.  I suspect the userEvent.upload(dropzone, file); isn't triggering some event the browser normally does, so how do I trigger the onChange() for testing?

UPDATE

OnChange Fires, but never gets to 'done' === status

```<code>test('DropZone responds to file upload event', async () =>
   {
      const getUploadParams: IDropzoneProps['getUploadParams'] = () =>
      { return { url: 'https://httpbin.org/post' } }

      const handleChangeStatus = jest.fn();

      renderWithProviders(<Dropzone maxFiles={1} multiple={false}
                                    inputContent='Send a file.'
                                    getUploadParams={getUploadParams}
                                    onChangeStatus={handleChangeStatus}
                          />);

      //const dropZone = screen.getByLabelText(startsWith('Drag and Drop a File,'));
      const dropZone = screen.getByLabelText(startsWith('Send a file'));

      expect(dropZone).toBeInTheDocument();
      screen.debug(dropZone);

      //expect(screen.getByTestId('dzu-input-id')).toBeInTheDocument();

      //resolves from project root instead of file.
      const logoFile = loadLocalFile(path.resolve('./src/images/logo.svg'));

      //await userEvent.upload(screen.getByTestId('dzu-input-id'), logoFile);
      //await userEvent.upload(dropZone, logoFile);
      //await fireEvent.change(dropZone, { target: { file: [logoFile] } });
      await fireEvent.drop(dropZone, { dataTransfer: { files: [logoFile] } });

      expect(handleChangeStatus).toHaveBeenCalled();
   });
</code>```

The key is await fireEvent.drop(dropZone, { dataTransfer: { files: [logoFile] } }); triggers the onChange event.

The Problem is in the Test enviornment, XMLHttpRequest#onReadyStateChange()  never fires with the proper parameters to trigger the callback handler in react-dropzone-uploader.

How do I trigger that callback properly in a JEST test?

Body:
I am building a site in Typescript with REACT.  I am using react-dropzone-uploader to handle file uploads in a form.  Uploads work in the broswer just fine.

However, I cannot get upload() from Testing Library to work.

The code examples from test Library work with their jsx and when modified with my helper methods.  However, When I copy the same basic logic to my react-dropzone-uploader code it doesn't work. The onChangeEvent never seems to fire.

Works

test('upload file', async () =>
   {
    renderWithProviders(

        Upload file:
          <input id="file-uploader" type="file" />

    );

    const file = new File(['hello'], 'hello.png', {type: 'image/png'});
    const input = screen.getByLabelText(startsWith('Upload file'));

    screen.debug(input);

    await userEvent.upload(input, file);

    expect(input.files[0]).toBe(file);
    expect(input.files.item(0)).toBe(file);
    expect(input.files).toHaveLength(1);
  })

Doesn't Work

 test('FileUpload widget displays successfully', async () =>
  {
    const uploadDone = jest.fn();
    renderWithProviders(<FileUpload whenUploadComplete={uploadDone} />);

    const dropZone = screen.getByLabelText(startsWith('Drag and Drop a File,'));

    expect(dropZone).toBeInTheDocument();
    screen.debug(dropZone);

    expect(screen.getByTestId('dzu-input-id')).toBeInTheDocument();

    //resolves a file from project root instead of file.
    const logoFile = loadLocalFile(path.resolve('./src/images/logo.svg'));

    //await userEvent.upload(screen.getByTestId('dzu-input-id'), logoFile);
    await userEvent.upload(dropZone, logoFile);

    expect(uploadDone).toHaveBeenCalled()
   });

FileUpload Wrapper for react-dropzone-uploader

import React from 'react';
import Dropzone,
       { IDropzoneProps, IFileWithMeta, StatusValue }
       from "react-dropzone-uploader";
import './FileUpload.css'; //copy of React-dropzone-uploader default css
import { theme } from "../shared/theme";
import * as mime from 'mime-types';

export interface fileUploadProps {
  uploadUrl?: string; //allows override for testing
  whenUploadComplete(file: File): void;
}

//TODO: move to test files later
export const devDoNothingUploadUrl = 'https://httpbin.org/post';

export const defaultUploadUrl = devDoNothingUploadUrl;

const FileUpload: React.FC<fileUploadProps> = (props) =>
{
  const { uploadUrl, whenUploadComplete } = props;
  const uploadToUrl = uploadUrl ? uploadUrl : defaultUploadUrl;

  //TODO: MUI Snackbar
  const message = (msg: string) => { console.log(msg); } //{ alert(msg); }

  //TODO: S3 https://react-dropzone-uploader.js.org/docs/s3
  //const getUploadParams = ({meta}:IFileWithMeta) =>
  const getUploadParams: IDropzoneProps['getUploadParams'] = () =>
  { return { url: uploadToUrl } }

  const handleChangeStatus: IDropzoneProps['onChangeStatus'] =
                            ({ meta, file, remove }, status) =>
  {
    setTimeout(() => {}, 1000);
    //console.log(status, meta);
    switch(status)
    {
      case 'ready':
      case 'preparing':
        message(`${meta.name} Preparing for Upload`);
        break;
      case 'started':
      case 'uploading':
      case 'restarted':
        message(`${meta.name} InProgress`);
        break;
      case 'error_file_size':
      case 'error_upload':
      case 'error_upload_params':
      case 'error_validation':
      case 'exception_upload':
      case 'rejected_file_type':
      case 'rejected_max_files':
        message(`${meta.name} ERROR!`);
        //TODO: code to catch and log error
        break;
      case 'done':
        whenUploadComplete(file);
        break;
      case 'headers_received':
        message(`${meta.name} Upload Complete!`);
        //remove();
    }
    return { meta: { meta } };
  }

  const logStatusChange: IDropzoneProps['onChangeStatus'] =
                         ({ meta }, status) =>
  { console.log(status, meta, meta.name) }

  const handleSubmit = (files: IFileWithMeta[], allFiles: IFileWithMeta[]) =>
  {
    console.log('files-meta:' + files.map(f => f.meta));
    allFiles.forEach(f => f.remove());
  }

  return (
    <Dropzone
      maxFiles={1} multiple={false}
      inputContent='Drag and Drop a File, or Click to Browse.'
      getUploadParams={getUploadParams}
      onChangeStatus={handleChangeStatus}
      //onChangeStatus={logStatusChange}
      //onSubmit={handleSubmit}
      styles={{ inputLabel: { color: theme.palette.text.secondary }, }}
      submitButtonDisabled={true}
    />
  )
}

export default FileUpload;

So How can I test Uploads?

My finish function never gets called, and I can never seem to find updated UI page elements either.  I suspect the userEvent.upload(dropzone, file); isn't triggering some event the browser normally does, so how do I trigger the onChange() for testing?

UPDATE

OnChange Fires, but never gets to 'done' === status

test('DropZone responds to file upload event', async () =>
   {
      const getUploadParams: IDropzoneProps['getUploadParams'] = () =>
      { return { url: 'https://httpbin.org/post' } }

      const handleChangeStatus = jest.fn();

      renderWithProviders(<Dropzone maxFiles={1} multiple={false}
                                    inputContent='Send a file.'
                                    getUploadParams={getUploadParams}
                                    onChangeStatus={handleChangeStatus}
                          />);

      //const dropZone = screen.getByLabelText(startsWith('Drag and Drop a File,'));
      const dropZone = screen.getByLabelText(startsWith('Send a file'));

      expect(dropZone).toBeInTheDocument();
      screen.debug(dropZone);

      //expect(screen.getByTestId('dzu-input-id')).toBeInTheDocument();

      //resolves from project root instead of file.
      const logoFile = loadLocalFile(path.resolve('./src/images/logo.svg'));

      //await userEvent.upload(screen.getByTestId('dzu-input-id'), logoFile);
      //await userEvent.upload(dropZone, logoFile);
      //await fireEvent.change(dropZone, { target: { file: [logoFile] } });
      await fireEvent.drop(dropZone, { dataTransfer: { files: [logoFile] } });

      expect(handleChangeStatus).toHaveBeenCalled();
   });

The key is await fireEvent.drop(dropZone, { dataTransfer: { files: [logoFile] } }); triggers the onChange event.

The Problem is in the Test enviornment, XMLHttpRequest#onReadyStateChange()  never fires with the proper parameters to trigger the callback handler in react-dropzone-uploader.

How do I trigger that callback properly in a JEST test?


问:
Async array map - can we use map instead of a loop?
Given this JavaScript snipped (not TypeScript!). How can we use map instead of a loop?

```<code>import { serialize } from 'next-mdx-remote/serialize'
...
const helperArray = []
for (const element of arrayOfObjects) {
  helperArray.push({ ...element, description: await serialize(element.description)})
}
</code>```

Thanks!

Body:
Given this JavaScript snipped (not TypeScript!). How can we use map instead of a loop?

import { serialize } from 'next-mdx-remote/serialize'
...
const helperArray = []
for (const element of arrayOfObjects) {
  helperArray.push({ ...element, description: await serialize(element.description)})
}

Thanks!


问:
Visual Studio/ Visual Studio Code C# Intelisense not working
I recently wanted to program in C# for Unity, but the problem is that the offical C# extension from Microsoft dosen't work for me in a script created with Unity, with the new txt trough Windows nor through VS Code directly. I am currently on a mashine that is running Windows 11.

I tried:

Rebooting the PC

Reinstalling the Extension

Reinstalling Visual Studio Code

Trying out Visual Studio and Visual Studio Code Insiders

Trying to install the .NET frameworks

I just want to use the intelisense, syntax highlighting and so on that come with the normal C# VS Code extension.


问:
How can I embed a .ts stream on my website, using m3u8 that works with HLS.js?
I have the URL of the stream that I wanted to embed on my website, using HLS.js but I can't because it has got the format of .ts (Transport Stream).

I have already tried VLC http streaming transconversion but it hasn't worked. If you consider using ffmpeg please let me know how you done it!

Here it is the stream: http://iptvfree1.com:7899/live:.cid.9b5190e69349237e/hGYOfCADiS/160

Sorry about my poor english,and my "noob" thinking about the topic. Thanks


问:
Access VBA how do I combine multiple tables
I currently have a Access Database with 100 tables. I'd like an easy way to combine all of them into a single query. Is there a way to simply have access select all of them?

For more information:
all the tables have the same number of fields they just have different values in each of them.

I'm new to vba so I don't know where to start with this. All I've found online are examples where you have to name every single table.


问:
Headless Wordpress using React and WPGraphql
I have searched for what seems like days and the documentation on WpGraphql is not really that good. I have tried reading the WpGraphql documentation to find how to connect a custom DB Table to WpGraphql. I have also tried to find tutorials or Github repos that have the tags that I am looking for, but I have had no luck.

Essentially, I am trying to use React-Hook-Form as the forms on my site and I want to create custom database tables for each form so I can have better control over the extraction of data than I do now with my site using Gravity Forms. I have insane queries and i would like to simplify my life and make them easier to maintain.

Does anyone know how to or can you point me in the direction of a tutorial in order to accomplish this? I appreciate any help in advance.


问:
Airflow - How to add a sidecar to a DAG that uses KubernetesPodOperator
I want to add a sidecar for a DAG that uses KubernetesPodOperator in the docs there is a suggestion to use pod_mutation_hook without any examples, is there a better way to do it or can someone share a simple example of how to use this function?

The airflow instance running on K8S and the DAG runs in the same cluster.


问:
i have error after importing fontawsome and runnig my react project
i need delete icon on my project . then i imported some command on my component page . i added these code :

```<code>import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faDelete } from '@fortawesome/free-solid-svg-icons'
</code>```

and then added this  <FontAwesomeIcon icon="fa-solid fa-trash" />   inside a button. when I run react I have this error :

```<code>03 {
  opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
  library: 'digital envelope routines',
  reason: 'unsupported',
  code: 'ERR_OSSL_EVP_UNSUPPORTED'
}

Node.js v18.12.1
</code>```

could u please help me for resolving it?
thanks

Body:
i need delete icon on my project . then i imported some command on my component page . i added these code :

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faDelete } from '@fortawesome/free-solid-svg-icons'

and then added this  <FontAwesomeIcon icon="fa-solid fa-trash" />   inside a button. when I run react I have this error :

03 {
  opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
  library: 'digital envelope routines',
  reason: 'unsupported',
  code: 'ERR_OSSL_EVP_UNSUPPORTED'
}

Node.js v18.12.1

could u please help me for resolving it?
thanks


问:
Service Layer Validation for Razor Pages
I have a .net web application using a razor pages. I have a "Services" like studentService, and I have "Repositories" like studentRepository. The StudentService is in the Application layer and the StudentRepository is in the Domain layer. I have razor pages in the webpresentation layer.

I am using dependency injection:

servicesCollection.AddScoped<IStudentService, StudentService>(); servicesCollection.AddScoped<IStudentRepository, StudentRepository>();

The problem is I want to implement certain validation logic in StudentService.

I have been using this as a guide: https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/models-data/validating-with-a-service-layer-cs

The issue is the Guide was written for MVC. The problem in that guide is that the ValidationLogic makes use of the ModelState, which is passed into the StudentService's constructor. This is fine because the StudentService would usually be instantiated in the StudentController, where the ModelState would be passed to the StudentService constructor.

But in my case, for Razor Pages, I am not instantiating the StudentService. I am injecting it.
How should I get the ModelState into the service? Or is there a better approach to this?


问:
Fetch data from API - Why can't I loop through the playedGames[]? JavaScript
I'm trying to loop through the playedGames from an API. I need to place a new game between two teams in a new row in a table. I can only get the same game to be shown - and I can't figure out why. I put playedGames[i] since I hoped it would iterate throw all 13 games- but obviously not :-)

Here's the code:

```<code>        export function getMatchData() {

       return fetch('https://stryk.herokuapp.com/strycket2022')

    .then(function (response) {

      return response.json();

    })

    .then(function (data) {

      for (let i = 0; i < 12; i++) {

        return data.playedGames[i].teams[1].name + " VS " + data.playedGames[i].teams[2].name;

      }

    });
}
</code>```

Body:
I'm trying to loop through the playedGames from an API. I need to place a new game between two teams in a new row in a table. I can only get the same game to be shown - and I can't figure out why. I put playedGames[i] since I hoped it would iterate throw all 13 games- but obviously not :-)

Here's the code:

        export function getMatchData() {

       return fetch('https://stryk.herokuapp.com/strycket2022')

    .then(function (response) {

      return response.json();

    })

    .then(function (data) {

      for (let i = 0; i < 12; i++) {

        return data.playedGames[i].teams[1].name + " VS " + data.playedGames[i].teams[2].name;

      }

    });
}


问:
Create class from inherited class instance
I have simple class:

```<code>class Dog:
    def __init__(self, size):
        self.size = size
        # there can be many fields

    def bar(self):
        print(f"WOOF {self.size}")
</code>```

And two methods I cannot modify:

```<code>def get_dog():
    return Dog("big")

def foo(dog: Dog):
    dog.bar()
</code>```

Now my goal is to expand functionality of Dog.bar so the foo function will call modified version.

```<code>class BigDog(Dog):
    def bar(self):
        print("WOFWOF")
</code>```

So I search for a way of creating BigDog from a Dog instance taken from the get_dog. The problem is I don't know what attributes are in Dog class and what is the implementation on get_dog.

The simplest way I considered was:

```<code>class BigDog:
    def __init__(self, dog: Dog):
        self.dog = dog

    def bar(self):
       ...
</code>```

But now a Dog is not a dog and mypy complains.

How to properly implement BigDog to be subclass of Dog and allow it to be initialized from the Dog instance?

Body:
I have simple class:

class Dog:
    def __init__(self, size):
        self.size = size
        # there can be many fields

    def bar(self):
        print(f"WOOF {self.size}")

And two methods I cannot modify:

def get_dog():
    return Dog("big")

def foo(dog: Dog):
    dog.bar()

Now my goal is to expand functionality of Dog.bar so the foo function will call modified version.

class BigDog(Dog):
    def bar(self):
        print("WOFWOF")

So I search for a way of creating BigDog from a Dog instance taken from the get_dog. The problem is I don't know what attributes are in Dog class and what is the implementation on get_dog.

The simplest way I considered was:

class BigDog:
    def __init__(self, dog: Dog):
        self.dog = dog

    def bar(self):
       ...

But now a Dog is not a dog and mypy complains.

How to properly implement BigDog to be subclass of Dog and allow it to be initialized from the Dog instance?


问:
Finding a value between different columns in Excel
I would like to find the solution to find the Pos that the user choose, then the user gives also a price and the program give him

I've tried:

```<code>V=data.query("KIO" & "UYT")['KIO'].max()
print(data['KIO'])
print(V)
V=data['GREER'].to_numpy()[data['UYT'].to_numpy() & data['HYEU'].to_numpy()].max()
print(V)

</code>```

Body:
I would like to find the solution to find the Pos that the user choose, then the user gives also a price and the program give him

I've tried:

V=data.query("KIO" & "UYT")['KIO'].max()
print(data['KIO'])
print(V)
V=data['GREER'].to_numpy()[data['UYT'].to_numpy() & data['HYEU'].to_numpy()].max()
print(V)


问:
Apply multiple styles in pandas (rows and cell)
I want to apply two styles to a dataframe with pandas and then export it as an excel file.

Style 1 (this one is accomplished):
color the entire row with according column color

Style 2 (get stuck):
if condition 2, color just one cell for a particular column

I want my excel file to look as follow.
The row color is based on values of a certain column (which stores the color code). And the cell color (purple) for 'Timestamp' column is based on whether the time difference from now exceeds 24 hrs.
enter image description here

I managed to get style 1 applied, but don't know how two roadblocks applying style 2:

df.style.apply can be used two times

don't know how to code up highlight_timeout function

```<code># color dataframe based on column 'AlarmColor' with styler
def highlight_rows(row):
    value = row.loc['AlarmColor']
    return ['background-color: {}'.format(value) for r in row]

def highlight_timeout(dt):
    [## something here ##]
    return [## something ##]

# apply pre-defined styles
df = df.style.apply(highlight_rows, axis=1)
styles = df.style.apply(highlight_timeout, subset=['TimeStamp'])   # <- this throws error

# write to excel
writer = pd.ExcelWriter(f"{project_name}_{current_time}.xlsx", engine='xlsxwriter')
styles.to_excel(writer, sheet_name='Your sheet name', columns=cols, index=False)  # send df to writer
writer.save()

</code>```

Thanks

Looked up this article
How to color a value in a dataframe based on a condition and export it to a csv file?

Body:
I want to apply two styles to a dataframe with pandas and then export it as an excel file.

Style 1 (this one is accomplished):
color the entire row with according column color

Style 2 (get stuck):
if condition 2, color just one cell for a particular column

I want my excel file to look as follow.
The row color is based on values of a certain column (which stores the color code). And the cell color (purple) for 'Timestamp' column is based on whether the time difference from now exceeds 24 hrs.
enter image description here

I managed to get style 1 applied, but don't know how two roadblocks applying style 2:

df.style.apply can be used two times

don't know how to code up highlight_timeout function

# color dataframe based on column 'AlarmColor' with styler
def highlight_rows(row):
    value = row.loc['AlarmColor']
    return ['background-color: {}'.format(value) for r in row]

def highlight_timeout(dt):
    [## something here ##]
    return [## something ##]

# apply pre-defined styles
df = df.style.apply(highlight_rows, axis=1)
styles = df.style.apply(highlight_timeout, subset=['TimeStamp'])   # <- this throws error

# write to excel
writer = pd.ExcelWriter(f"{project_name}_{current_time}.xlsx", engine='xlsxwriter')
styles.to_excel(writer, sheet_name='Your sheet name', columns=cols, index=False)  # send df to writer
writer.save()

Thanks

Looked up this article
How to color a value in a dataframe based on a condition and export it to a csv file?


问:
ValueError: text input must of type `str` when running the t5 minimal start example of simpletransformers
I am trying to running this example (https://simpletransformers.ai/docs/t5-minimal-start/)

The only adaptation was the CUDA flag (use_cuda=cuda_available):

```<code>import logging, torch
import pandas as pd
from simpletransformers.t5 import T5Model, T5Args

cuda_available = torch.cuda.is_available()
logging.basicConfig(level=logging.INFO)
transformers_logger = logging.getLogger("transformers")
transformers_logger.setLevel(logging.WARNING)

train_data = [
    ["binary classification", "Anakin was Luke's father" , 1],
    ["binary classification", "Luke was a Sith Lord" , 0],
    ["generate question", "Star Wars is an American epic space-opera media franchise created by George Lucas, which began with the eponymous 1977 film and quickly became a worldwide pop-culture phenomenon", "Who created the Star Wars franchise?"],
    ["generate question", "Anakin was Luke's father" , "Who was Luke's father?"],
]
train_df = pd.DataFrame(train_data)
train_df.columns = ["prefix", "input_text", "target_text"]

eval_data = [
    ["binary classification", "Leia was Luke's sister" , 1],
    ["binary classification", "Han was a Sith Lord" , 0],
    ["generate question", "In 2020, the Star Wars franchise's total value was estimated at US$70 billion, and it is currently the fifth-highest-grossing media franchise of all time.", "What is the total value of the Star Wars franchise?"],
    ["generate question", "Leia was Luke's sister" , "Who was Luke's sister?"],
]
eval_df = pd.DataFrame(eval_data)
eval_df.columns = ["prefix", "input_text", "target_text"]

# Configure the model
model_args = T5Args()
model_args.num_train_epochs = 200
model_args.no_save = True
model_args.evaluate_generated_text = True
model_args.evaluate_during_training = True
model_args.evaluate_during_training_verbose = True

model = T5Model("t5", "t5-base", args=model_args, use_cuda=cuda_available)

# Train the model
model.train_model(train_df, eval_data=eval_df)

# Evaluate the model
result = model.eval_model(eval_df)

# Make predictions with the model
to_predict = [
    "binary classification: Luke blew up the first Death Star",
    "generate question: In 1971, George Lucas wanted to film an adaptation of the Flash Gordon serial, but could not obtain the rights, so he began developing his own space opera.",
]

preds = model.predict(to_predict)
</code>```

And I got this error:

```<code>  File "D:\Program Files\Python310\lib\site-packages\transformers\tokenization_utils_base.py", line 2578, in _call_one
    raise ValueError(
ValueError: text input must of type `str` (single example), `List[str]` (batch or single pretokenized example) or `List[List[str]]` (batch of pretokenized examples).
</code>```

Is there any incompatibility between the libs installed?
I am using python 3.10 on Windows 10
What can I do to fix it?

Body:
I am trying to running this example (https://simpletransformers.ai/docs/t5-minimal-start/)

The only adaptation was the CUDA flag (use_cuda=cuda_available):

import logging, torch
import pandas as pd
from simpletransformers.t5 import T5Model, T5Args

cuda_available = torch.cuda.is_available()
logging.basicConfig(level=logging.INFO)
transformers_logger = logging.getLogger("transformers")
transformers_logger.setLevel(logging.WARNING)

train_data = [
    ["binary classification", "Anakin was Luke's father" , 1],
    ["binary classification", "Luke was a Sith Lord" , 0],
    ["generate question", "Star Wars is an American epic space-opera media franchise created by George Lucas, which began with the eponymous 1977 film and quickly became a worldwide pop-culture phenomenon", "Who created the Star Wars franchise?"],
    ["generate question", "Anakin was Luke's father" , "Who was Luke's father?"],
]
train_df = pd.DataFrame(train_data)
train_df.columns = ["prefix", "input_text", "target_text"]

eval_data = [
    ["binary classification", "Leia was Luke's sister" , 1],
    ["binary classification", "Han was a Sith Lord" , 0],
    ["generate question", "In 2020, the Star Wars franchise's total value was estimated at US$70 billion, and it is currently the fifth-highest-grossing media franchise of all time.", "What is the total value of the Star Wars franchise?"],
    ["generate question", "Leia was Luke's sister" , "Who was Luke's sister?"],
]
eval_df = pd.DataFrame(eval_data)
eval_df.columns = ["prefix", "input_text", "target_text"]

# Configure the model
model_args = T5Args()
model_args.num_train_epochs = 200
model_args.no_save = True
model_args.evaluate_generated_text = True
model_args.evaluate_during_training = True
model_args.evaluate_during_training_verbose = True

model = T5Model("t5", "t5-base", args=model_args, use_cuda=cuda_available)

# Train the model
model.train_model(train_df, eval_data=eval_df)

# Evaluate the model
result = model.eval_model(eval_df)

# Make predictions with the model
to_predict = [
    "binary classification: Luke blew up the first Death Star",
    "generate question: In 1971, George Lucas wanted to film an adaptation of the Flash Gordon serial, but could not obtain the rights, so he began developing his own space opera.",
]

preds = model.predict(to_predict)

And I got this error:

  File "D:\Program Files\Python310\lib\site-packages\transformers\tokenization_utils_base.py", line 2578, in _call_one
    raise ValueError(
ValueError: text input must of type `str` (single example), `List[str]` (batch or single pretokenized example) or `List[List[str]]` (batch of pretokenized examples).

Is there any incompatibility between the libs installed?
I am using python 3.10 on Windows 10
What can I do to fix it?


问:
F# [System.String]' was not present in the dictionary when using FSharp.Data CSV Provider
Getting some strange behaviour

This code is part of an iteration using FSharp.Data , CSV provider iterating through the rows.

It fails on line 3 with the following error message

```<code>The given key 'Microsoft.FSharp.Core.CompilerServices.RuntimeHelpers+StructBox`1[System.String]' was not present in the dictionary
</code>```

the raw data for this field looks like this:

,0000000647203050,

What is weird is that transactionNumber and tn2 are both equal to "647203050" even though it failed on the 3rd line

```<code>let transactionNumber = row["TRXN Reference-Eway"].Replace("0000000","")
let transactionNumberInt = int transactionNumber
let tn2 = transactionNumber.ToString()
</code>```

Body:
Getting some strange behaviour

This code is part of an iteration using FSharp.Data , CSV provider iterating through the rows.

It fails on line 3 with the following error message

The given key 'Microsoft.FSharp.Core.CompilerServices.RuntimeHelpers+StructBox`1[System.String]' was not present in the dictionary

the raw data for this field looks like this:

,0000000647203050,

What is weird is that transactionNumber and tn2 are both equal to "647203050" even though it failed on the 3rd line

let transactionNumber = row["TRXN Reference-Eway"].Replace("0000000","")
let transactionNumberInt = int transactionNumber
let tn2 = transactionNumber.ToString()


问:
Selective deletion of (stop)words in Tkinter

Pre-Introduction

l am a beginner in Tkinter, l learn mostly from seeing videos(Youtube) and searching up problems according to what l need. My Python knowledge is until Object oriented but very rusty. And English isn't my mother languague
Stopwords are words which are often encountered in texts and prove little to no use so they must be deleted.
The program contains Greek characters

Introduction

My main goal for my Tkinter program is for the user, to load a corpus(a text from a file in which it later gets tokenize), load a stopwords file(preferable the output would be in a list, from txt to list). Then the program,  for each word  inside the corpus(text), checks the stopwords(list) if a stopword is contained inside the corpus. If it is, the specific stopword gets added into a listbox(let's call it "Found stopwords",A). For example, out of all 265 stopwords, a corpus might contain 65 of them, then those 65 should be inserted into the Found List Box.

The user has the choice to move words into the second ListBox(to be deleted stopwords, B) in which this ListBox will contain the stopwords that will get deleted after the user presses a menu button called "Remove stopwords". The program will check the ListBox  B for each stopword found, it will get deleted in corpus text and not just once. For example: if the ListBox B has the word "Στο" and if the corpus contains this word 7 times, then that word should be deleted 7 times and this applies to every word that is in the ListBox.

Main Problem

The main problems are the logic behind how ListBox B if it does the job right of finding the stopwords to delete in function: removeStopwords

```<code>def removeStopwords(self):
        if len (self.corpusText) == 0: # corpusText is just a String
            print("Empty")
            return

        temp=[]## Used for debugging and seeing which words get added
        for word in self.listBoxOfDelStopwords.get(0,self.listBoxOfDelStopwords.size()):
            self.updatedStopwords_Greek.append(word)
            print("Words to be added:"+word)
            #if word in self.updatedStopwords_Greek:
                #temp.append(word)
                #print(word)

        #print(temp)
        print("Total of Stopwords words:"+ str(len(self.updatedStopwords_Greek)))

        print("Before removal of stopwords from Text :"+str(len(self.corpusText)))

        for word in self.corpusText:
            if word  in self.updatedStopwords_Greek:
                temp.append(word)
                print(temp)## Debugging reasons
                print(str(len(temp)))## Number of occurences not just for one stopword
                self.corpusText.remove(word)

        print("-----")
        print("After Removal of stopwords from Text : "+str(len(self.corpusText)))
                                        #Shows number of letters

        self.textBoxTest.delete("1.0",END)
        self.textBoxTest.insert("1.0",self.corpusText)
        self.labelNumOfChars.configure(text=str(len(self.corpusText)))
        #self.textBoxTest.insert("1.0",self.corpusTest)
        #print(self.corpusTest)
</code>```

But the most critical problem is finding a way to highlight the words to be deleted in red within the Text Widget or whatever that fits best to handle this problem.  l have read up about Text Widget and its tag system but l sadly did not grasp enough. l am not sure if the tag logic can work on it.
Is it possible to make a function or just the logic of it, that highlights the words inside the Text Box widget*(*or label or whatever that fits best)?
In other words: l want each time to move an item from ListBox A to ListBox B, to update the Text Box widget by coloring the words to be deleted if the user chooses to remove them. If words "του" and "τα" are in ListBox B, then whatever occurence of these words are encountered in Text widget, should be colored with Red color. Then should be back to the original color if they get removed from ListBox B back to ListBox A.
This way, it will give the user a glimpse of what he will delete(and if the system actually works and deletes the selected words)

Last Notes

Obviously; if there are more efficient ways of dealing such a problem without using the methods l used, it would be appreciated to be mentioned and expanded on.
My code is surely a mess and l would like to be told like l am a beginneer on the methods that will be solve the problems if possible.
l sadly do not know how StackOverflow works, l doubt l can upload the Python file, onlyway l see is to copy the entire code but that would complicate the situation, right?

Body:
Pre-Introduction

l am a beginner in Tkinter, l learn mostly from seeing videos(Youtube) and searching up problems according to what l need. My Python knowledge is until Object oriented but very rusty. And English isn't my mother languague
Stopwords are words which are often encountered in texts and prove little to no use so they must be deleted.
The program contains Greek characters

Introduction

My main goal for my Tkinter program is for the user, to load a corpus(a text from a file in which it later gets tokenize), load a stopwords file(preferable the output would be in a list, from txt to list). Then the program,  for each word  inside the corpus(text), checks the stopwords(list) if a stopword is contained inside the corpus. If it is, the specific stopword gets added into a listbox(let's call it "Found stopwords",A). For example, out of all 265 stopwords, a corpus might contain 65 of them, then those 65 should be inserted into the Found List Box.

The user has the choice to move words into the second ListBox(to be deleted stopwords, B) in which this ListBox will contain the stopwords that will get deleted after the user presses a menu button called "Remove stopwords". The program will check the ListBox  B for each stopword found, it will get deleted in corpus text and not just once. For example: if the ListBox B has the word "Στο" and if the corpus contains this word 7 times, then that word should be deleted 7 times and this applies to every word that is in the ListBox.

Main Problem

The main problems are the logic behind how ListBox B if it does the job right of finding the stopwords to delete in function: removeStopwords

def removeStopwords(self):
        if len (self.corpusText) == 0: # corpusText is just a String
            print("Empty")
            return

        temp=[]## Used for debugging and seeing which words get added
        for word in self.listBoxOfDelStopwords.get(0,self.listBoxOfDelStopwords.size()):
            self.updatedStopwords_Greek.append(word)
            print("Words to be added:"+word)
            #if word in self.updatedStopwords_Greek:
                #temp.append(word)
                #print(word)

        #print(temp)
        print("Total of Stopwords words:"+ str(len(self.updatedStopwords_Greek)))

        print("Before removal of stopwords from Text :"+str(len(self.corpusText)))

        for word in self.corpusText:
            if word  in self.updatedStopwords_Greek:
                temp.append(word)
                print(temp)## Debugging reasons
                print(str(len(temp)))## Number of occurences not just for one stopword
                self.corpusText.remove(word)

        print("-----")
        print("After Removal of stopwords from Text : "+str(len(self.corpusText)))
                                        #Shows number of letters

        self.textBoxTest.delete("1.0",END)
        self.textBoxTest.insert("1.0",self.corpusText)
        self.labelNumOfChars.configure(text=str(len(self.corpusText)))
        #self.textBoxTest.insert("1.0",self.corpusTest)
        #print(self.corpusTest)

But the most critical problem is finding a way to highlight the words to be deleted in red within the Text Widget or whatever that fits best to handle this problem.  l have read up about Text Widget and its tag system but l sadly did not grasp enough. l am not sure if the tag logic can work on it.
Is it possible to make a function or just the logic of it, that highlights the words inside the Text Box widget*(*or label or whatever that fits best)?
In other words: l want each time to move an item from ListBox A to ListBox B, to update the Text Box widget by coloring the words to be deleted if the user chooses to remove them. If words "του" and "τα" are in ListBox B, then whatever occurence of these words are encountered in Text widget, should be colored with Red color. Then should be back to the original color if they get removed from ListBox B back to ListBox A.
This way, it will give the user a glimpse of what he will delete(and if the system actually works and deletes the selected words)

Last Notes

Obviously; if there are more efficient ways of dealing such a problem without using the methods l used, it would be appreciated to be mentioned and expanded on.
My code is surely a mess and l would like to be told like l am a beginneer on the methods that will be solve the problems if possible.
l sadly do not know how StackOverflow works, l doubt l can upload the Python file, onlyway l see is to copy the entire code but that would complicate the situation, right?


问:
How to return a CSV from Pandas Dataframe using StreamingResponse in FastAPI?
I'm trying to return a CSV response to a GET query (end library requirement..), and I am hoping to find a way to do this without writing the CSV to disk. A similar question has been answered here, but I have one additional bit of complexity where I'm returning data from another function.

import json
import time
from typing import Optional
import io

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from fastapi.responses import StreamingResponse

import xarray as xr
import pandas as pd
import numpy as np
import gc

async def get_intensity_csv(x,y):
    #Use select on the xarray datasource, returning a data array and then convert to a pandas dataframe
    #Index
    da = ds["intensity"].sel(longitude=y, latitude=x, method="nearest")

    df = da.to_dataframe()
    df.drop(columns=['latitude', 'longitude'], inplace=True)

    #pandas to csv ready for streaming to the client
    stream = io.StringIO()
    resp_csv = df.to_csv(stream, index = False)

    return resp_csv
```
<p>The above is being called from:</p>
<pre class="lang-py prettyprint-override"><code>#create an app.get that returns intensity as a csv stream
@app.get("/intensity_csv/{x}/{y}", tags=["intensity_csv"])
async def get_intensity_csv(x: float, y: float):
    res = await int_process(x,y)
    return StreamingResponse(io.StringIO(res), media_type="text/csv")
</code>```

The error I'm receiving is:

```<code>return StreamingResponse(io.StringIO(res), media_type="text/csv")
TypeError: initial_value must be str or None, not dict
</code>```

I believe my issue is getting data from the first sample via these couple of lines back to the def async get_intensity_csv

```<code>#pandas to csv ready for streaming to the client
    stream = io.StringIO()
    resp_csv = df.to_csv(stream, index = False)
</code>```

I'm not sure how to pass the content of the dataframe back so I can then use StreamingResponse to deliver the csv to the client.

Body:
I'm trying to return a CSV response to a GET query (end library requirement..), and I am hoping to find a way to do this without writing the CSV to disk. A similar question has been answered here, but I have one additional bit of complexity where I'm returning data from another function.

import json
import time
from typing import Optional
import io

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from fastapi.responses import StreamingResponse

import xarray as xr
import pandas as pd
import numpy as np
import gc

async def get_intensity_csv(x,y):
    #Use select on the xarray datasource, returning a data array and then convert to a pandas dataframe
    #Index
    da = ds["intensity"].sel(longitude=y, latitude=x, method="nearest")

    df = da.to_dataframe()
    df.drop(columns=['latitude', 'longitude'], inplace=True)

    #pandas to csv ready for streaming to the client
    stream = io.StringIO()
    resp_csv = df.to_csv(stream, index = False)

    return resp_csv

The above is being called from:

#create an app.get that returns intensity as a csv stream
@app.get("/intensity_csv/{x}/{y}", tags=["intensity_csv"])
async def get_intensity_csv(x: float, y: float):
    res = await int_process(x,y)
    return StreamingResponse(io.StringIO(res), media_type="text/csv")

The error I'm receiving is:

return StreamingResponse(io.StringIO(res), media_type="text/csv")
TypeError: initial_value must be str or None, not dict

I believe my issue is getting data from the first sample via these couple of lines back to the def async get_intensity_csv

#pandas to csv ready for streaming to the client
    stream = io.StringIO()
    resp_csv = df.to_csv(stream, index = False)

I'm not sure how to pass the content of the dataframe back so I can then use StreamingResponse to deliver the csv to the client.


问:
Laravel 9 / InertiaJS / Vue || Correctly Configuring Accessor to Translate Table Value to String
I am new to Laravel / Inertia / Vue but not necessarily to PHP or JS, so forgive me if this isn't the most informed question.

I've asked a similar question before, but this is a new attempt to rectify it using an Accessor on the attribute so I felt like starting a new conversation. It was suggested I use an enumerator but I think an accessor on the model might be the most fitting way to handle this. Feel free to correct me if I'm wrong.

Essentially, I have a field in a DB called StatusID (I can't change this) but it's an integer value. I want it to be translated to a string value when it's accessed by Eloquent. I don't care about it being an integer in my controller, but I just want it to enter Inertia as a string value rather than an int.

Controller

<?php

namespace App\Http\Controllers;

use Inertia\Inertia;
use Illuminate\Http\Request;
use App\Models\eRequester\Requisition;
use App\Models\eRequester\ProjectManager;

class RequisitionController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return Inertia::render('Requisition/Index',[
                'requisitions' => Requisition::with(
                    'lines:RequisitionLineID,ItemID,Description,ProjectNumber,RequisitionID',
                    'owner:UserID,UserName,FirstName,LastName')
                    ->latest()
                    ->where('StatusID','!=','2')
                    ->limit(15)
                    ->select('RequisitionID','Title','UserID','StatusID') // << This value, StatusID
                    ->get(),
                'projectmanagers' => ProjectManager::where('AttributeID','siica3')
                    ->orWhere('AttributeID','ckwca7')
                    ->orWhere('AttributeID','orica3')
                    ->get(),
                'companies' => [
                    ['CompanyID' => '3', 'CompanyName' => 'Spitzer'],
                    ['CompanyID' => '2', 'CompanyName' => 'Curtis Kelly'],
                    ['CompanyID' => '4', 'CompanyName' => 'Orizon']],
            ]);
    }

}
```
<p><strong>Model (function on the model)</strong></p>
<pre class="lang-php prettyprint-override"><code>  protected function StatusID(): Attribute
    {
        $statusDescription = [
            "0" => "Incomplete",
            "1" => "Unsubmitted",
            "2" => "Cancelled",
            "3" => "Rejected",
            "4" => "Waiting",
            "5" => "Request Info",
            "6" => "Approved",
            "7" => "Posted",
            "8" => "Partially Received",
            "9" => "Closed",
            "10" => "Require Change",
            "11" => "Resubmitted for Post Approval Routing",
            "12" => "Edited (Post Approval)",
            "13" => "Fully Received",
            "14" => "Posted - On Hold"
        ];

        return Attribute::make(
            get: fn ($value) => $statusDescription[$value],
        );

    }
</code>```

Vue

```<code>  <div class="p-4 border-2 mb-4 rounded-lg">
        <div class="text-white font-bold uppercase flex justify-between">
            <span class="">

            <a target="_BLANK" :href="'{redacted}/req/review.aspx?reqid=' + req.RequisitionID">
                <button class="bg-white hover:bg-blue-200 text-black font-bold py-0 px-2 mr-2 mb-2 rounded transition-all">
                    {{ req.RequisitionID }}
                </button></a>
                    {{ req.Title }}
            </span>
            <span>
                {{ req.StatusID }}
            </span>
</code>```

I've tried several different configurations to have it hit this accessor but I'm kind of poking around in the dark.

From what I understand, when it hits Vue it should already be translated to a string, which it isn't at the moment (image)

enter image description here

What could I be doing wrong? I have a feeling it might be something to do with the StatusID camel case resolving to something like status_id (which is incorrect) and I don't know how to manually set that value if it's protected, etc.

Also, feel free to yell at me if I should have asked this question as an addendum on my previous question. I rarely ask questions on here and I don't want to be ruffling feathers.

Thanks,
Alex

Body:
I am new to Laravel / Inertia / Vue but not necessarily to PHP or JS, so forgive me if this isn't the most informed question.

I've asked a similar question before, but this is a new attempt to rectify it using an Accessor on the attribute so I felt like starting a new conversation. It was suggested I use an enumerator but I think an accessor on the model might be the most fitting way to handle this. Feel free to correct me if I'm wrong.

Essentially, I have a field in a DB called StatusID (I can't change this) but it's an integer value. I want it to be translated to a string value when it's accessed by Eloquent. I don't care about it being an integer in my controller, but I just want it to enter Inertia as a string value rather than an int.

Controller

<?php

namespace App\Http\Controllers;

use Inertia\Inertia;
use Illuminate\Http\Request;
use App\Models\eRequester\Requisition;
use App\Models\eRequester\ProjectManager;

class RequisitionController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return Inertia::render('Requisition/Index',[
                'requisitions' => Requisition::with(
                    'lines:RequisitionLineID,ItemID,Description,ProjectNumber,RequisitionID',
                    'owner:UserID,UserName,FirstName,LastName')
                    ->latest()
                    ->where('StatusID','!=','2')
                    ->limit(15)
                    ->select('RequisitionID','Title','UserID','StatusID') // << This value, StatusID
                    ->get(),
                'projectmanagers' => ProjectManager::where('AttributeID','siica3')
                    ->orWhere('AttributeID','ckwca7')
                    ->orWhere('AttributeID','orica3')
                    ->get(),
                'companies' => [
                    ['CompanyID' => '3', 'CompanyName' => 'Spitzer'],
                    ['CompanyID' => '2', 'CompanyName' => 'Curtis Kelly'],
                    ['CompanyID' => '4', 'CompanyName' => 'Orizon']],
            ]);
    }

}

Model (function on the model)

  protected function StatusID(): Attribute
    {
        $statusDescription = [
            "0" => "Incomplete",
            "1" => "Unsubmitted",
            "2" => "Cancelled",
            "3" => "Rejected",
            "4" => "Waiting",
            "5" => "Request Info",
            "6" => "Approved",
            "7" => "Posted",
            "8" => "Partially Received",
            "9" => "Closed",
            "10" => "Require Change",
            "11" => "Resubmitted for Post Approval Routing",
            "12" => "Edited (Post Approval)",
            "13" => "Fully Received",
            "14" => "Posted - On Hold"
        ];

        return Attribute::make(
            get: fn ($value) => $statusDescription[$value],
        );

    }

Vue

                <button class="bg-white hover:bg-blue-200 text-black font-bold py-0 px-2 mr-2 mb-2 rounded transition-all">
                    {{ req.RequisitionID }}
                </button>
                    {{ req.Title }}

                {{ req.StatusID }}

I've tried several different configurations to have it hit this accessor but I'm kind of poking around in the dark.

From what I understand, when it hits Vue it should already be translated to a string, which it isn't at the moment (image)

enter image description here

What could I be doing wrong? I have a feeling it might be something to do with the StatusID camel case resolving to something like status_id (which is incorrect) and I don't know how to manually set that value if it's protected, etc.

Also, feel free to yell at me if I should have asked this question as an addendum on my previous question. I rarely ask questions on here and I don't want to be ruffling feathers.

Thanks,
Alex


问:
How to specify a data type while importing a spreadsheet from gsheets (Google Colab) - Zero missing
I am importing a data frame from google drive , and I have two columns with numbers. The problem is that when the number ends with a zero, this 'zero' does not appear in my dataframe (this column is set as a object) - For example 20.180 in the original dataset becomes 2.018.

I have already tried to change the data type after importing the files, however I guess the problem is in the type of data that it gets while being imported(object). I know that when using pd.read_excel I can choose the data type of the columns. Is there any way to specify this when uploading files directly from google sheets/google drive?

I am using the code below to import the file

```<code>planilha_reg = gc.open('base_modelo_REG')
aba_reg = planilha_reg.sheet1
df_reg = pd.DataFrame(aba_reg.get_all_records())
</code>```

Body:
I am importing a data frame from google drive , and I have two columns with numbers. The problem is that when the number ends with a zero, this 'zero' does not appear in my dataframe (this column is set as a object) - For example 20.180 in the original dataset becomes 2.018.

I have already tried to change the data type after importing the files, however I guess the problem is in the type of data that it gets while being imported(object). I know that when using pd.read_excel I can choose the data type of the columns. Is there any way to specify this when uploading files directly from google sheets/google drive?

I am using the code below to import the file

planilha_reg = gc.open('base_modelo_REG')
aba_reg = planilha_reg.sheet1
df_reg = pd.DataFrame(aba_reg.get_all_records())


问:
How to parse FieldDecl with libclang?
Using the example Clang lambda, I'm trying to parse a c++ header file. The problem is, I'm unsure how to parse a CXCursor_FieldDecl for the type and name of a member field of a class.

```<code>clang_visitChildren(cursor,
    [](CXCursor c, CXCursor parent, CXClientData client_data) {

        if (clang_getCursorKind(c) == CXCursor_FieldDecl) {
            std::cout << clang_getCursorKindSpelling(clang_getCursorKind(c))
                << " " << clang_getCursorSpelling(c) << ";\n";
        }

        return CXChildVisit_Recurse;
    }, nullptr);

</code>```

The above will print out:

```<code>FieldDecl varA;
FieldDecl varB;
FieldDecl varC;
</code>```

What I'm looking for is:

```<code>int    varA;
double varB;
string varC;
</code>```

Any thoughts on how to parse a FieldDecl for type and name of member field?

Title: How to parse FieldDecl with libclang?

Body:
Using the example Clang lambda, I'm trying to parse a c++ header file. The problem is, I'm unsure how to parse a CXCursor_FieldDecl for the type and name of a member field of a class.

clang_visitChildren(cursor,
    [](CXCursor c, CXCursor parent, CXClientData client_data) {

        if (clang_getCursorKind(c) == CXCursor_FieldDecl) {
            std::cout << clang_getCursorKindSpelling(clang_getCursorKind(c))
                << " " << clang_getCursorSpelling(c) << ";\n";
        }

        return CXChildVisit_Recurse;
    }, nullptr);

The above will print out:

FieldDecl varA;
FieldDecl varB;
FieldDecl varC;

What I'm looking for is:

int    varA;
double varB;
string varC;

Any thoughts on how to parse a FieldDecl for type and name of member field?


问:
Layout broken trying to the delete a comment
I'm having some layout issues with my Facebook comments box.

The box is 245 pixels wide, which I need to fit the rest of my layout.

The window is working fine with this size, but the delete window does not seems to resize automatically according to my main box width.

See the following image:

Is there a way I can fix this?

ContentLicense: CC BY-SA 3.0


问:
document.cookie returns empty string, even although there's one cookie with no HttpOnly attribute
In a Typescript-React SPA, I'm trying to access the document.cookie in order to retrieve a token sent together with a JWT cookie, intended to protect my Flask API against CSRF attacks, as described here.

The basic idea is that my API will send 2 cookies: one containing the JWT and flagged with the Secure & HttpOnly attributes, and another one that should be readable by JS with a token that, when sent back in the request Headersto the server should match a token encrypted in the JWT and thus verify if it's a CSRF attack or not.

To grab said token, I'm using the following function:

export default function getCSRFCookie() {
    console.log(document.cookie);
    const cookiesString = `; ${document.cookie} `;
    const CSRFCookie = cookiesString.split(`; csrf_access_token=`);

    return CSRFCookie.length === 2 ? CSRFCookie.pop()?.split(';').shift() : '';
}
```
<p>However, <code>document.cookie</code> always ends up being an empty string, even although the relevant cookie <strong>doesn't have the <code>HttpOnly</code> flag, which is the one that prevents JS from reading it in <code>document.cookie</code></strong>:</p>
```csrf_access_token=<token_value>;
Expires=Wed, 21 Dec 2022 00:33:53 GMT;
Max-Age=7200; Secure; Path=/;
SameSite=None
```
<p>The following are the relevant Flask & Flask JWT Extended configurations that set the cookies up, but personally I don't think this is a server issue, because I saw, the cookies have the correct attributes matching the settings below:</p>
<pre class="lang-py prettyprint-override"><code># Flask JWT Extended specific configurations:
JWT_COOKIE_CSRF_PROTECT = True
JWT_COOKIE_SECURE = True
JWT_COOKIE_SAMESITE = "None"

# Flask config values, which are explicitly set to override default values.
# See https://flask.palletsprojects.com/en/2.2.x/security/#security-cookie
SESSION_COOKIE_HTTPONLY = False
SESSION_COOKIE_SAMESITE = "None"
</code>```

The Flask application is already deployed in Linode, has got its own domain as well as an SSL certificate. I believe this is a front end problem.

I've tried to:

Access from http://127.0.0.1:3000 instead of localhost, as a comment in this answer suggests.

Access from both HTTPS (through HTTPS=true npm run start) and regular HTTP.

Check any default setting that might set the wrong attribute implicitly (such as Flask's SESSION_COOKIE_HTTPONLY, but as I wrote above, all those attributes appear to be correct and besides, the cookie I get doesn't have the HttpOnlyattribute.

The SameSite attribute is already set to None, as several comments and answers suggest in this question

Deleting all the cookies sent by my API before trying again after a change.

In order to continue working in other features, I've provisionally set the JWT_COOKIE_CSRF_PROTECT property to False, but that cannot remain that way since it's an obvious security risk.

Body:
In a Typescript-React SPA, I'm trying to access the document.cookie in order to retrieve a token sent together with a JWT cookie, intended to protect my Flask API against CSRF attacks, as described here.

The basic idea is that my API will send 2 cookies: one containing the JWT and flagged with the Secure & HttpOnly attributes, and another one that should be readable by JS with a token that, when sent back in the request Headersto the server should match a token encrypted in the JWT and thus verify if it's a CSRF attack or not.

To grab said token, I'm using the following function:

export default function getCSRFCookie() {
    console.log(document.cookie);
    const cookiesString = `; ${document.cookie} `;
    const CSRFCookie = cookiesString.split(`; csrf_access_token=`);

    return CSRFCookie.length === 2 ? CSRFCookie.pop()?.split(';').shift() : '';
}

However, document.cookie always ends up being an empty string, even although the relevant cookie doesn't have the HttpOnly flag, which is the one that prevents JS from reading it in document.cookie:

csrf_access_token=<token_value>;
Expires=Wed, 21 Dec 2022 00:33:53 GMT;
Max-Age=7200; Secure; Path=/;
SameSite=None

The following are the relevant Flask & Flask JWT Extended configurations that set the cookies up, but personally I don't think this is a server issue, because I saw, the cookies have the correct attributes matching the settings below:

# Flask JWT Extended specific configurations:
JWT_COOKIE_CSRF_PROTECT = True
JWT_COOKIE_SECURE = True
JWT_COOKIE_SAMESITE = "None"

# Flask config values, which are explicitly set to override default values.
# See https://flask.palletsprojects.com/en/2.2.x/security/#security-cookie
SESSION_COOKIE_HTTPONLY = False
SESSION_COOKIE_SAMESITE = "None"

The Flask application is already deployed in Linode, has got its own domain as well as an SSL certificate. I believe this is a front end problem.

I've tried to:

Access from http://127.0.0.1:3000 instead of localhost, as a comment in this answer suggests.

Access from both HTTPS (through HTTPS=true npm run start) and regular HTTP.

Check any default setting that might set the wrong attribute implicitly (such as Flask's SESSION_COOKIE_HTTPONLY, but as I wrote above, all those attributes appear to be correct and besides, the cookie I get doesn't have the HttpOnlyattribute.

The SameSite attribute is already set to None, as several comments and answers suggest in this question

Deleting all the cookies sent by my API before trying again after a change.

In order to continue working in other features, I've provisionally set the JWT_COOKIE_CSRF_PROTECT property to False, but that cannot remain that way since it's an obvious security risk.


问:
How to unit test code that calls Console.ReadKey without mocking
I know I can call Console.SetIn()  and pass in a StringReader.  When I call Console.ReadLine() it works as expected and returns the string from the StringReader but here's the question:

Is there a way to get Console.ReadKey() to behave similarly and read a single char without using Moq (or other mocking framework)?

Here's a link to an example using Console.ReadLine() as I've described in case it's not clear.

https://makolyte.com/csharp-how-to-unit-test-code-that-reads-and-writes-to-the-console/


问:
Geopandas: joining by nearest with matching id field
I have a line df and a point df.

I want to join the attributes of line features to the nearest point features, but only when the 'id' fields from both df's are matching

I can join by nearest using the sjoin_nearest geopandas function.

geopandas.sjoin_nearest(point_df, line_df, distance_col="distances")

But I am not sure how I could add the ability to only join to features that have a matching id field


问:
JSONata returns Stack Overflow error when using functions on a non-first property in a new grouped object
I am unsure if this stems from JSONata 2.0.0 but I have yet to see this from previous uses of this query language. I have a list of objects that the sub-arrays will contain the same dates:

```<code>{
property1: {
  subProperty1: [{"date": 1/1/2022, value: 10}...],
  subProperty2: [{"date": 1/1/2022, value: 50}...]
}
}
</code>```

I am trying to create a new object where all values with the same date are summed together. When I believe I got the right query, I get a Stack Overflow recursion error. After more testing, it seems that a function called on the first property will work but any property after that will not have a working function. How or why is there a recursion on any non-first property and what in my code would cause a non-terminating loop?

I have tried creating an object of only the {date, value} object without adding any other properties. I am working on a direct line of $...* to see if I could diagnose any syntax errors on my part. The [value != null] is there to weed out null values that would stop a $sum() function from happening.

After changing the playground to 1.8.6, it is clear that 2.0.0 is why there is an issue.

Body:
I am unsure if this stems from JSONata 2.0.0 but I have yet to see this from previous uses of this query language. I have a list of objects that the sub-arrays will contain the same dates:

{
property1: {
  subProperty1: [{"date": 1/1/2022, value: 10}...],
  subProperty2: [{"date": 1/1/2022, value: 50}...]
}
}

I am trying to create a new object where all values with the same date are summed together. When I believe I got the right query, I get a Stack Overflow recursion error. After more testing, it seems that a function called on the first property will work but any property after that will not have a working function. How or why is there a recursion on any non-first property and what in my code would cause a non-terminating loop?

I have tried creating an object of only the {date, value} object without adding any other properties. I am working on a direct line of $...* to see if I could diagnose any syntax errors on my part. The [value != null] is there to weed out null values that would stop a $sum() function from happening.

After changing the playground to 1.8.6, it is clear that 2.0.0 is why there is an issue.


问:
NullPointerException when importing mule project to Anypoint Studio
I am trying to import a mule project into Anypoint Studio and I get this error with a failed import

```<code>!ENTRY org.mule.tooling.core 4 0 2022-12-20 13:00:30.899
!MESSAGE The project can't be imported.
!STACK 0
java.lang.NullPointerException
    at org.mule.tooling.core.utils.CoreUtils.createDocumentationStructure(CoreUtils.java:811)
    at org.mule.tooling.core.MuleRuntime.createMuleProject(MuleRuntime.java:148)
    at org.mule.tooling.core.packageManager.importing.OpenProjectAction.lambda$0(OpenProjectAction.java:101)
    at org.mule.tooling.core.MuleRuntime.runLockingProjectsRegistry(MuleRuntime.java:317)
    at org.mule.tooling.core.packageManager.importing.OpenProjectAction.run(OpenProjectAction.java:98)
    at org.mule.tooling.core.packageManager.importing.ProjectImportAction.runAllActions(ProjectImportAction.java:16)
    at org.mule.tooling.core.packageManager.importing.ProjectImportAction.lambda$0(ProjectImportAction.java:18)
    at java.base/java.util.Optional.map(Optional.java:265)
    at org.mule.tooling.core.packageManager.importing.ProjectImportAction.runAllActions(ProjectImportAction.java:18)
    at org.mule.tooling.ui.wizards.MuleProjectImportJob.runInWorkspace(MuleProjectImportJob.java:96)
    at org.eclipse.core.internal.resources.InternalWorkspaceJob.run(InternalWorkspaceJob.java:42)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63)
</code>```

enter image description here

I am using JDK 1.8 and Maven 3.6.3. I can't find any resources online about this error. Could anyone please help?

Body:
I am trying to import a mule project into Anypoint Studio and I get this error with a failed import

!ENTRY org.mule.tooling.core 4 0 2022-12-20 13:00:30.899
!MESSAGE The project can't be imported.
!STACK 0
java.lang.NullPointerException
    at org.mule.tooling.core.utils.CoreUtils.createDocumentationStructure(CoreUtils.java:811)
    at org.mule.tooling.core.MuleRuntime.createMuleProject(MuleRuntime.java:148)
    at org.mule.tooling.core.packageManager.importing.OpenProjectAction.lambda$0(OpenProjectAction.java:101)
    at org.mule.tooling.core.MuleRuntime.runLockingProjectsRegistry(MuleRuntime.java:317)
    at org.mule.tooling.core.packageManager.importing.OpenProjectAction.run(OpenProjectAction.java:98)
    at org.mule.tooling.core.packageManager.importing.ProjectImportAction.runAllActions(ProjectImportAction.java:16)
    at org.mule.tooling.core.packageManager.importing.ProjectImportAction.lambda$0(ProjectImportAction.java:18)
    at java.base/java.util.Optional.map(Optional.java:265)
    at org.mule.tooling.core.packageManager.importing.ProjectImportAction.runAllActions(ProjectImportAction.java:18)
    at org.mule.tooling.ui.wizards.MuleProjectImportJob.runInWorkspace(MuleProjectImportJob.java:96)
    at org.eclipse.core.internal.resources.InternalWorkspaceJob.run(InternalWorkspaceJob.java:42)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63)

enter image description here

I am using JDK 1.8 and Maven 3.6.3. I can't find any resources online about this error. Could anyone please help?