问:
Uppy/Shrine: How to retrieve presigned url for video after successful upload (using AWS S3)
I'm using Uppy for file uploads in React, with a Rails API using Shrine.

I'm trying to show a preview for an uploaded video before submitting a form. It's important to emphasize that this is specifically for a video upload, not an image. So the 'thumbnail:generated' event will not apply here.

I can't seem to find any events that uppy provides that returns a cached video preview (like thumbnail:generated does) or anything that passes back a presigned url for the uploaded file (less expected, obviously), so the only option I see is constructing the url manually. Here's what I'm currently trying for that (irrelevant code removed for brevity):

import React, { useEffect, useState } from 'react'

import AwsS3 from '@uppy/aws-s3'
import Uppy from '@uppy/core'
import axios from 'axios'
import { DragDrop } from '@uppy/react'

import { API_BASE } from '../../../api'

const constructParams = (metadata) => ([
  `?X-Amz-Algorithm=${metadata['x-amz-algorithm']}`,
  `&X-Amz-Credential=${metadata['x-amz-credential']}`,
  `&X-Amz-Date=${metadata['x-amz-date']}`,
  '&X-Amz-Expires=900',
  '&X-Amz-SignedHeaders=host',
  `&X-Amz-Signature=${metadata['x-amz-signature']}`,
].join('').replaceAll('/', '%2F'))

const MediaUploader = () => {
  const [videoSrc, setVideoSrc] = useState('')

  const uppy = new Uppy({
    meta: { type: 'content' },
    restrictions: {
      maxNumberOfFiles: 1
    },
    autoProceed: true,
  })

  const getPresigned = async (id, type) => {
    const response = await axios.get(`${API_BASE}/s3/params?filename=${id}&type=${type}`)

    const { fields, url } = response.data
    const params = constructParams(fields)
    const presignedUrl = `${url}/${fields.key}${params}`
    console.log('presignedUrl from Shrine request data: ', presignedUrl)

    setVideoSrc(presignedUrl)
  }

  useEffect(() => {
    uppy
      .use(AwsS3, {
        id: `AwsS3:${Math.random()}`,
        companionUrl: API_BASE,
      })

    uppy.on('upload-success', (file, _response) => {
      const { type, meta } = file

      // First attempt to construct presigned URL here
      const url = 'https://my-s3-bucket.s3.us-west-1.amazonaws.com'
      const params = constructParams(meta)
      const presignedUrl = `${url}/${meta.key}${params}`
      console.log('presignedUrl from upload-success data: ', presignedUrl)

      // Second attempt to construct presigned URL here
      const id = meta.key.split(`${process.env.REACT_APP_ENV}/cache/`)[1]
      getPresigned(id, type)
    })
  }, [uppy])

  return (

        <video
          src={videoSrc || ''}
          className="Uppy__preview"
          controls
        />

      {(!videoSrc || videoSrc === '') && (
        <DragDrop
          uppy={uppy}
          className="UploadForm"
          locale={{
            strings: {
              dropHereOr: 'Drop here or %{browse}',
              browse: 'browse',
            },
          }}
        />
      )}

  )
}

export default MediaUploader
```
<p>Both urls here come back with a <code>SignatureDoesNotMatch</code> error from AWS.</p>
<p>The manual construction of the url comes mainly from <code>constructParams</code>. I have two different implementations of this, the first of which takes the metadata directly from the uploaded file data in the <code>'upload-success'</code> event, and then just concatenates a string to build the url. The second one uses <code>getPresigned</code>, which makes a request to my API, which points to a generated Shrine path that should return data for a presigned URL. <code>API_BASE</code> simply points to my Rails API. More info on the generated Shrine route here.</p>
<p>It's worth noting that everything works perfectly with the upload process that passes through Shrine, and after submitting the form, I'm able to get a presigned url for the video and play it without issue on the site. So I have no reason to believe Shrine is returning incorrectly signed urls.</p>
<p>I've compared the two presigned urls I'm manually generating in the form, with the url returned from Shrine after uploading. All 3 are identical in structure, but have different signatures. Here are those three urls:</p>
```presignedUrl from upload-success data:
https://my-s3-bucket.s3.us-west-1.amazonaws.com/development/cache/41b229fb17cbf21925d2cd907a59be25.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAW63AYCMFA4374OLC%2F20221210%2Fus-west-1%2Fs3%2Faws4_request&X-Amz-Date=20221210T132613Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=97aefd1ac7f3d42abd2c48fe3ad50b542742ad0717a51528c35f1159bfb15609

presignedUrl from Shrine request data:
https://my-s3-bucket.s3.us-west-1.amazonaws.com/development/cache/023592fb14c63a45f02c1ad89a49e5fd.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAW63AYCMFA4374OLC%2F20221210%2Fus-west-1%2Fs3%2Faws4_request&X-Amz-Date=20221210T132619Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=7171ac72f7db2b8871668f76d96d275aa6c53f71b683bcb6766ac972e549c2b3

presigned url displayed on site after form submission:
https://my-s3-bucket.s3.us-west-1.amazonaws.com/development/cache/41b229fb17cbf21925d2cd907a59be25.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAW63AYCMFA4374OLC%2F20221210%2Fus-west-1%2Fs3%2Faws4_request&X-Amz-Date=20221210T132734Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=9ecc98501866f9c5bd460369a7c2ce93901f94c19afa28144e0f99137cdc2aaf
```

The first two urls come back with SignatureDoesNotMatch, while the third url properly plays the video.

I'm aware the first and third urls have the same file name, while the second url does not. I'm not sure what to make of that, though, but the relevance of this is secondary to me, since that solution was more of a last ditch effort anyway.

I'm not at all attached to the current way I'm doing things. It's just the only solution I could come up with, due to lack of options. If there's a better way of going about this, I'm very open to suggestions.

Body:
I'm using Uppy for file uploads in React, with a Rails API using Shrine.

I'm trying to show a preview for an uploaded video before submitting a form. It's important to emphasize that this is specifically for a video upload, not an image. So the 'thumbnail:generated' event will not apply here.

I can't seem to find any events that uppy provides that returns a cached video preview (like thumbnail:generated does) or anything that passes back a presigned url for the uploaded file (less expected, obviously), so the only option I see is constructing the url manually. Here's what I'm currently trying for that (irrelevant code removed for brevity):

import React, { useEffect, useState } from 'react'

import AwsS3 from '@uppy/aws-s3'
import Uppy from '@uppy/core'
import axios from 'axios'
import { DragDrop } from '@uppy/react'

import { API_BASE } from '../../../api'

const constructParams = (metadata) => ([
  `?X-Amz-Algorithm=${metadata['x-amz-algorithm']}`,
  `&X-Amz-Credential=${metadata['x-amz-credential']}`,
  `&X-Amz-Date=${metadata['x-amz-date']}`,
  '&X-Amz-Expires=900',
  '&X-Amz-SignedHeaders=host',
  `&X-Amz-Signature=${metadata['x-amz-signature']}`,
].join('').replaceAll('/', '%2F'))

const MediaUploader = () => {
  const [videoSrc, setVideoSrc] = useState('')

  const uppy = new Uppy({
    meta: { type: 'content' },
    restrictions: {
      maxNumberOfFiles: 1
    },
    autoProceed: true,
  })

  const getPresigned = async (id, type) => {
    const response = await axios.get(`${API_BASE}/s3/params?filename=${id}&type=${type}`)

    const { fields, url } = response.data
    const params = constructParams(fields)
    const presignedUrl = `${url}/${fields.key}${params}`
    console.log('presignedUrl from Shrine request data: ', presignedUrl)

    setVideoSrc(presignedUrl)
  }

  useEffect(() => {
    uppy
      .use(AwsS3, {
        id: `AwsS3:${Math.random()}`,
        companionUrl: API_BASE,
      })

    uppy.on('upload-success', (file, _response) => {
      const { type, meta } = file

      // First attempt to construct presigned URL here
      const url = 'https://my-s3-bucket.s3.us-west-1.amazonaws.com'
      const params = constructParams(meta)
      const presignedUrl = `${url}/${meta.key}${params}`
      console.log('presignedUrl from upload-success data: ', presignedUrl)

      // Second attempt to construct presigned URL here
      const id = meta.key.split(`${process.env.REACT_APP_ENV}/cache/`)[1]
      getPresigned(id, type)
    })
  }, [uppy])

  return (

        <video
          src={videoSrc || ''}
          className="Uppy__preview"
          controls
        />

      {(!videoSrc || videoSrc === '') && (
        <DragDrop
          uppy={uppy}
          className="UploadForm"
          locale={{
            strings: {
              dropHereOr: 'Drop here or %{browse}',
              browse: 'browse',
            },
          }}
        />
      )}

  )
}

export default MediaUploader

Both urls here come back with a SignatureDoesNotMatch error from AWS.

The manual construction of the url comes mainly from constructParams. I have two different implementations of this, the first of which takes the metadata directly from the uploaded file data in the 'upload-success' event, and then just concatenates a string to build the url. The second one uses getPresigned, which makes a request to my API, which points to a generated Shrine path that should return data for a presigned URL. API_BASE simply points to my Rails API. More info on the generated Shrine route here.

It's worth noting that everything works perfectly with the upload process that passes through Shrine, and after submitting the form, I'm able to get a presigned url for the video and play it without issue on the site. So I have no reason to believe Shrine is returning incorrectly signed urls.

I've compared the two presigned urls I'm manually generating in the form, with the url returned from Shrine after uploading. All 3 are identical in structure, but have different signatures. Here are those three urls:

presignedUrl from upload-success data:
https://my-s3-bucket.s3.us-west-1.amazonaws.com/development/cache/41b229fb17cbf21925d2cd907a59be25.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAW63AYCMFA4374OLC%2F20221210%2Fus-west-1%2Fs3%2Faws4_request&X-Amz-Date=20221210T132613Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=97aefd1ac7f3d42abd2c48fe3ad50b542742ad0717a51528c35f1159bfb15609

presignedUrl from Shrine request data:
https://my-s3-bucket.s3.us-west-1.amazonaws.com/development/cache/023592fb14c63a45f02c1ad89a49e5fd.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAW63AYCMFA4374OLC%2F20221210%2Fus-west-1%2Fs3%2Faws4_request&X-Amz-Date=20221210T132619Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=7171ac72f7db2b8871668f76d96d275aa6c53f71b683bcb6766ac972e549c2b3

presigned url displayed on site after form submission:
https://my-s3-bucket.s3.us-west-1.amazonaws.com/development/cache/41b229fb17cbf21925d2cd907a59be25.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAW63AYCMFA4374OLC%2F20221210%2Fus-west-1%2Fs3%2Faws4_request&X-Amz-Date=20221210T132734Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=9ecc98501866f9c5bd460369a7c2ce93901f94c19afa28144e0f99137cdc2aaf

The first two urls come back with SignatureDoesNotMatch, while the third url properly plays the video.

I'm aware the first and third urls have the same file name, while the second url does not. I'm not sure what to make of that, though, but the relevance of this is secondary to me, since that solution was more of a last ditch effort anyway.

I'm not at all attached to the current way I'm doing things. It's just the only solution I could come up with, due to lack of options. If there's a better way of going about this, I'm very open to suggestions.


来源: stackexchange

问:
Why using “Reformat Code” functionality some methods are differently formatted?
In PhpStorm 2021.1 working with Laravel 9 I periodically use “Reformat Code” functionality with all content of the file selected.

But some methods of this file looks differently formatted :

    public function setBannerId(int $value): self
    {
        $this->bannerId = $value;

        return $this;
    }

...
    public
    function setDescriptionSize(
        int $value
    ): self {
        $this->descriptionSize = $value;

        return $this;
    }
```

I dislike a way the second method is formatted. I want all methods to be formatted as the first method?

UPDATED :
“Reformat Code” tab https://prnt.sc/cxkkYQdcRPjd printscreen

Can it be done?

ContentLicense: CC BY-SA 4.0

Body:
In PhpStorm 2021.1 working with Laravel 9 I periodically use “Reformat Code” functionality with all content of the file selected.

But some methods of this file looks differently formatted :

    public function setBannerId(int $value): self
    {
        $this->bannerId = $value;

        return $this;
    }

...
    public
    function setDescriptionSize(
        int $value
    ): self {
        $this->descriptionSize = $value;

        return $this;
    }

I dislike a way the second method is formatted. I want all methods to be formatted as the first method?

UPDATED :
“Reformat Code” tab https://prnt.sc/cxkkYQdcRPjd printscreen

Can it be done?


问:
Where do I enter moment.js code so a DataTables column appears in my chosen format?
I want to make data like 2022/12/15 (imported from Google Sheets at the moment of page load) display as "Dec 15" in one column, and as "Thu" in another column.

I found the format codes:
moment().format("MMM d"); // "Dec 15" and
moment().format("ddd"); // "Thu".

I read https://momentjs.com/docs/ and https://momentjs.com/guides/, but could not find:
Where do I enter that code?

Can I skip entering that code, and instead just enter this?:

```<code>$(document).ready(function () {
    $('#example').DataTable({
        columnDefs: [
            {
                targets: 4,
                render: DataTable.render.datetime('MMM d'),
            },
        ],
    });
});
</code>```

Perhaps I should separate my questions into different posted questions, but I imagine it will be more helpful for future readers to find the combined challenges asked and answered in a single thread.

I'm using the WordPress plugin "Inline Google Spreadsheet Viewer", which is built on DataTables.
[Edit: I realized I should not paste that code into inline_gdocs_viewer.php, and intended to paste it into igsv-datatables.js.  I could not however figure out where to paste within that file. What should I look for to know where to insert it?   (The author of that plugin publicly announced that no more support will be given.) Should I post the contents of the js file somewhere so you can see it?]
[Edit 2: Would entering that code make column 5 always displayed in MMM d format, even if I want column 5 to be displayed in a different format?  Shouldn't specifying what format to apply to which column happen when I create a page / post and use the shortcode to embed the spreadsheet?]
(I read the plugin's documentation and I read DataTables documentation.)

If my table doesn't have a name, what do I use instead of #example?  Do I need to name my table?  If so, how?  (I tried to find the answer at, for example, https://www.w3schools.com/html/html_tables.asp.)

The source for the longer code came from a live example where the dates were in column 5, but the code says "targets:4".  To apply the code to column 3 (for example), should I enter targets:2? I read https://datatables.net/reference/option/columns.render, but bizarrely that didn't address this basic question.

If you're wondering if I upgraded DataTables from the old version that comes with Inline Google Spreadsheet Viewer, yes I did.

If you're wondering if I got the script array to call moment.js, I might have.  Into the scripts array I added

```<code>,
'moment' => array(
'src' => plugins_url('moment.min.js', __FIL__),
'deps' => array( 'moment' )
)
</code>```

I'm not sure about the "deps" part. Does it mean dependencies? Was I right to use "moment" twice in that code?

If you only know a possible answer to one of these questions, that's better than nothing, so please do share what you can.

I know the Moment team recommends you choose a different library than Moment for new projects, but DataTables to this day recommends Moment for sorting by Day of the week or sorting by Date.

Thanks

Using moment.js 2.29.2 and DataTables 1.13.1.

What I tried, and what I expected:
I read the documentation for all the programs, and I read forum discussions for all the programs, and I studied examples, expecting to find where to enter the code, but nowhere could I find what to do with it.  It was always assumed that that part was already known.

Body:
I want to make data like 2022/12/15 (imported from Google Sheets at the moment of page load) display as "Dec 15" in one column, and as "Thu" in another column.

I found the format codes:
moment().format("MMM d"); // "Dec 15" and
moment().format("ddd"); // "Thu".

I read https://momentjs.com/docs/ and https://momentjs.com/guides/, but could not find:
Where do I enter that code?

Can I skip entering that code, and instead just enter this?:

$(document).ready(function () {
    $('#example').DataTable({
        columnDefs: [
            {
                targets: 4,
                render: DataTable.render.datetime('MMM d'),
            },
        ],
    });
});

Perhaps I should separate my questions into different posted questions, but I imagine it will be more helpful for future readers to find the combined challenges asked and answered in a single thread.

I'm using the WordPress plugin "Inline Google Spreadsheet Viewer", which is built on DataTables.
[Edit: I realized I should not paste that code into inline_gdocs_viewer.php, and intended to paste it into igsv-datatables.js.  I could not however figure out where to paste within that file. What should I look for to know where to insert it?   (The author of that plugin publicly announced that no more support will be given.) Should I post the contents of the js file somewhere so you can see it?]
[Edit 2: Would entering that code make column 5 always displayed in MMM d format, even if I want column 5 to be displayed in a different format?  Shouldn't specifying what format to apply to which column happen when I create a page / post and use the shortcode to embed the spreadsheet?]
(I read the plugin's documentation and I read DataTables documentation.)

If my table doesn't have a name, what do I use instead of #example?  Do I need to name my table?  If so, how?  (I tried to find the answer at, for example, https://www.w3schools.com/html/html_tables.asp.)

The source for the longer code came from a live example where the dates were in column 5, but the code says "targets:4".  To apply the code to column 3 (for example), should I enter targets:2? I read https://datatables.net/reference/option/columns.render, but bizarrely that didn't address this basic question.

If you're wondering if I upgraded DataTables from the old version that comes with Inline Google Spreadsheet Viewer, yes I did.

If you're wondering if I got the script array to call moment.js, I might have.  Into the scripts array I added

,
'moment' => array(
'src' => plugins_url('moment.min.js', __FIL__),
'deps' => array( 'moment' )
)

I'm not sure about the "deps" part. Does it mean dependencies? Was I right to use "moment" twice in that code?

If you only know a possible answer to one of these questions, that's better than nothing, so please do share what you can.

I know the Moment team recommends you choose a different library than Moment for new projects, but DataTables to this day recommends Moment for sorting by Day of the week or sorting by Date.

Thanks

Using moment.js 2.29.2 and DataTables 1.13.1.

What I tried, and what I expected:
I read the documentation for all the programs, and I read forum discussions for all the programs, and I studied examples, expecting to find where to enter the code, but nowhere could I find what to do with it.  It was always assumed that that part was already known.


问:
My Deployed Mern App 404 issue with api call but fine on Local Computer
Hello Every one I have just deployed my mern app on cyclic and i am wonder that i am getting an issue that my client side is working fine but my api call get me an issue while database is working fine and working fine on my local computer

404 error Ss

This us how i call an api route login on client

```<code> fetch("/login",{
       method:"Post",
       headers:{
       "Content-Type":"application/json"
   }, etc....

2) Server Route

app.use("/users",userRouter)

[Comparision of my deployed one and on local computer](https://i.stack.imgur.com/rhCQT.jpg)

Github Link of my repository
https://github.com/MohsinRahman8017/Mern_Portfolio/blob/main/server.js

Please Try to help and figure me out where is the porblem i have given my repository link please figure me out the issue
</code>```

Body:
Hello Every one I have just deployed my mern app on cyclic and i am wonder that i am getting an issue that my client side is working fine but my api call get me an issue while database is working fine and working fine on my local computer

404 error Ss

This us how i call an api route login on client

 fetch("/login",{
       method:"Post",
       headers:{
       "Content-Type":"application/json"
   }, etc....

2) Server Route

app.use("/users",userRouter)

[Comparision of my deployed one and on local computer](https://i.stack.imgur.com/rhCQT.jpg)

Github Link of my repository
https://github.com/MohsinRahman8017/Mern_Portfolio/blob/main/server.js

Please Try to help and figure me out where is the porblem i have given my repository link please figure me out the issue


问:
what does folders inside .cache/pip/http do or for what?
My computer suffers from not enough storage. So I am looking for the folders that I can delete without any issue that can break my system. I came accross with .cache/pip/http folder.There are many folders that every one of them at least 2 Gib. I couldn't find an explanation for the following questions in my mind.

What is the purpose of these folders?

What would be the result if I delete them?


问:
Check HTML element type and compare it
So I have a button that activates a function onClick, then I want to check all classes of my page with the id of this button. Then it should get the element Type and compare it to e.g. "icon". So if the element is an icon it should get a different style than a div.
I already have an approach but I am stuck:

HTML:

```<code><div class="question-tile-container">
                 <button id="01" class="01 button" onClick="test(this)">
                            <p>How do I create an account?</p>
                            <i class="01 fa-regular fa-arrow-down-wide-short"></i>
                        </button>
                        <div class="01 answer">
                            Lorem ipsum dolor sit amet.
                        </div>
                    </div>
</code>```

JS:

```<code>function test(ele) {
    var id = ele.id
    console.log(id)

    elements = document.getElementsByClassName(id)
    console.log(elements)

    for(i=0;i<elements.length+1;i++){
        if(elements.tagName == 'icon') {
            // style icon
        } else {
            // style div
        }
    }
}
</code>```

It should check all elements with the id, then compare the element type to a string. If it matches a specific string it should style in a different way, than it would if it matches to another string.

Title: Check HTML element type and compare it

Body:
So I have a button that activates a function onClick, then I want to check all classes of my page with the id of this button. Then it should get the element Type and compare it to e.g. "icon". So if the element is an icon it should get a different style than a div.
I already have an approach but I am stuck:

HTML:

                 <button id="01" class="01 button" onClick="test(this)">

How do I create an account?

                        </button>

                            Lorem ipsum dolor sit amet.

JS:

function test(ele) {
    var id = ele.id
    console.log(id)

    elements = document.getElementsByClassName(id)
    console.log(elements)

    for(i=0;i<elements.length+1;i++){
        if(elements.tagName == 'icon') {
            // style icon
        } else {
            // style div
        }
    }
}

It should check all elements with the id, then compare the element type to a string. If it matches a specific string it should style in a different way, than it would if it matches to another string.


问:
Why my NextJs does not work with Graphql Apollo Subscription?
I am making a chat application in NextJS using a Graphql subscription.

I tried to find some examples but all I found were either expressjs with reactjs or expressjs with nextjs.

I used graphql-yoga in nextjs serverless and graphql apollo in frontend.

The following error is what I see now in the terminal.

```<code>error - TypeError [ERR_INVALID_ARG_TYPE]: The "string" argument must be of type string or an instance of Buffer or ArrayBuffer. Received type function ([Function (anonymous)])
</code>```

I am not sure what is causing this issue.

Here is the backend for my nextjs

import { createServer, createPubSub } from "@graphql-yoga/node";

const pubsub = createPubSub();

const NEW_MESSAGE = "NEW_MESSAGE";
const NEW_MESSAGES = "NEW_MESSAGES";
const messages = [];

const resolvers = {
  Query: {
    messages: (_, { name }, context) => messages,
  },
  Mutation: {
    createMessage(parent, { user, body }, { pubsub }) {
      const id = Math.floor(Math.random() * 10000000);
      messages.push({ id, user, body });

      pubsub.publish(NEW_MESSAGE, {
        newMessage: { id, user, body },
      });
      pubsub.publish(NEW_MESSAGES);

      return true;
    },
  },
  Subscription: {
    newMessage: {
      subscribe: (_, __, { pubsub }) => {
        return pubsub.subscribe(NEW_MESSAGE);
      },
      resolve: (payload) => {
        const { message } = payload;
        const { id, user, body } = message;
        return { id, user, body };
      },
    },
    newMessages: {
      subscribe: (_, __, { pubsub }) => {
        return pubsub.subscribe(NEW_MESSAGES);
      },
      resolve: () => messages,
    },
  },
};

const typeDefs = `
  type Message {
    id: ID!
    user: String!
    body: String!
  }

  type MessageInput {
    user: String!
    body: String!
  }

  type SubscriptionPayload {
    id: ID
    user: String
    body: String
  }

  type Query {
    messages: [Message!]
  }

  type Mutation {
    createMessage(user: String!, body: String!): Boolean!
  }

  type Subscription {
    newMessage: Message
    newMessages: [Message]
  }
`;

const server = createServer({
  context: async ({ req }) => {
    return {
      user: { name: "jogn Doe", id: 0 },
      pubsub,
    };
  },
  schema: {
    typeDefs,
    resolvers,
  },
});

export default server;

```
<p>my backend seems to be working fine in the <code>graphql yoga playground</code></p>
<p>but my frontend does not as soon as I integrate with my backend.</p>
<pre class="lang-js prettyprint-override"><code>// _app.js
import "../styles/globals.css";
import { ApolloProvider } from "@apollo/client";
import { client } from "./apollo";

function MyApp({ Component, pageProps }) {
  return (
    <ApolloProvider client={client}>
      <Component {...pageProps} />
    </ApolloProvider>
  );
}

export default MyApp;
</code>```

// apollo.js
import { ApolloClient, HttpLink, InMemoryCache } from "@apollo/client";
import { GraphQLWsLink } from "@apollo/client/link/subscriptions";
import { createClient } from "graphql-ws";

const uri = 'localhost:3000/api/graphql';

const httpLink = new HttpLink({
  uri: `http://${uri}`
});

const wsLink = () => {
  return new GraphQLWsLink(createClient({
    url: `ws://${uri}`
  }));
}

export const client = new ApolloClient({
  link: typeof window === 'undefined' ? httpLink : wsLink(),
  cache: new InMemoryCache(),
});
```
<pre class="lang-js prettyprint-override"><code>// index.js
import Head from "next/head";
import styles from "../styles/Home.module.css";

import { gql, useSubscription } from "@apollo/client";
export default function Home() {

  const SUBSCRIPTION = gql`
    subscription newMessages {
      newMessages {
        id
        user
        body
      }
    }
  `;

  const { loading, error, data } = useSubscription(SUBSCRIPTION);
  console.log({ data, loading, error });
  console.log(error); // {Error: undefined} is printed

  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main>
        <div>Hello Nextjs Graphql</div>
      </main>
    </div>
  );
}
</code>```

Why is it not working?
I cannot find a valid solution.
I found people also having other problems with this integration.
Is NextJS backend not good for this use case as nextjs backend is serverless?
If so, I do not understand why..
In that case, does using some sort of in-memory database would help such as Redis?

Thank you for reading and for your time.

Body:
I am making a chat application in NextJS using a Graphql subscription.

I tried to find some examples but all I found were either expressjs with reactjs or expressjs with nextjs.

I used graphql-yoga in nextjs serverless and graphql apollo in frontend.

The following error is what I see now in the terminal.

error - TypeError [ERR_INVALID_ARG_TYPE]: The "string" argument must be of type string or an instance of Buffer or ArrayBuffer. Received type function ([Function (anonymous)])

I am not sure what is causing this issue.

Here is the backend for my nextjs

import { createServer, createPubSub } from "@graphql-yoga/node";

const pubsub = createPubSub();

const NEW_MESSAGE = "NEW_MESSAGE";
const NEW_MESSAGES = "NEW_MESSAGES";
const messages = [];

const resolvers = {
  Query: {
    messages: (_, { name }, context) => messages,
  },
  Mutation: {
    createMessage(parent, { user, body }, { pubsub }) {
      const id = Math.floor(Math.random() * 10000000);
      messages.push({ id, user, body });

      pubsub.publish(NEW_MESSAGE, {
        newMessage: { id, user, body },
      });
      pubsub.publish(NEW_MESSAGES);

      return true;
    },
  },
  Subscription: {
    newMessage: {
      subscribe: (_, __, { pubsub }) => {
        return pubsub.subscribe(NEW_MESSAGE);
      },
      resolve: (payload) => {
        const { message } = payload;
        const { id, user, body } = message;
        return { id, user, body };
      },
    },
    newMessages: {
      subscribe: (_, __, { pubsub }) => {
        return pubsub.subscribe(NEW_MESSAGES);
      },
      resolve: () => messages,
    },
  },
};

const typeDefs = `
  type Message {
    id: ID!
    user: String!
    body: String!
  }

  type MessageInput {
    user: String!
    body: String!
  }

  type SubscriptionPayload {
    id: ID
    user: String
    body: String
  }

  type Query {
    messages: [Message!]
  }

  type Mutation {
    createMessage(user: String!, body: String!): Boolean!
  }

  type Subscription {
    newMessage: Message
    newMessages: [Message]
  }
`;

const server = createServer({
  context: async ({ req }) => {
    return {
      user: { name: "jogn Doe", id: 0 },
      pubsub,
    };
  },
  schema: {
    typeDefs,
    resolvers,
  },
});

export default server;

my backend seems to be working fine in the graphql yoga playground

but my frontend does not as soon as I integrate with my backend.

// _app.js
import "../styles/globals.css";
import { ApolloProvider } from "@apollo/client";
import { client } from "./apollo";

function MyApp({ Component, pageProps }) {
  return (
    <ApolloProvider client={client}>
      <Component {...pageProps} />
    </ApolloProvider>
  );
}

export default MyApp;

// apollo.js
import { ApolloClient, HttpLink, InMemoryCache } from "@apollo/client";
import { GraphQLWsLink } from "@apollo/client/link/subscriptions";
import { createClient } from "graphql-ws";

const uri = 'localhost:3000/api/graphql';

const httpLink = new HttpLink({
  uri: `http://${uri}`
});

const wsLink = () => {
  return new GraphQLWsLink(createClient({
    url: `ws://${uri}`
  }));
}

export const client = new ApolloClient({
  link: typeof window === 'undefined' ? httpLink : wsLink(),
  cache: new InMemoryCache(),
});

// index.js
import Head from "next/head";
import styles from "../styles/Home.module.css";

import { gql, useSubscription } from "@apollo/client";
export default function Home() {

  const SUBSCRIPTION = gql`
    subscription newMessages {
      newMessages {
        id
        user
        body
      }
    }
  `;

  const { loading, error, data } = useSubscription(SUBSCRIPTION);
  console.log({ data, loading, error });
  console.log(error); // {Error: undefined} is printed

  return (

        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />

Hello Nextjs Graphql

  );
}

Why is it not working?
I cannot find a valid solution.
I found people also having other problems with this integration.
Is NextJS backend not good for this use case as nextjs backend is serverless?
If so, I do not understand why..
In that case, does using some sort of in-memory database would help such as Redis?

Thank you for reading and for your time.


问:
Custom Font not Loaded in Mobile Device
I have website that using Gilroy. It's work well in desktop version.
But when I check it in mobile, or click link from social media application like Instagram, it's not work.

What can I do

Here is the way I add custom font, is it wrong?

```<code>@font-face {
  font-family: "Gilroy";
  src: url("../fonts/Gilroy-Regular.eot");
  src: local("☞../fonts/Gilroy-Regular"), local("../fonts/Gilroy-Regular"), url("../fonts/Gilroy-Regular.eot?#iefix") format("embedded-opentype"), url("../fonts/Gilroy-Regular.woff2") format("woff2"), url("../fonts/Gilroy-Regular.woff") format("woff"), url("../fonts/Gilroy-Regular.ttf") format("truetype");
  font-weight: normal;
  font-style: normal;
  font-display: swap;
}
</code>```

Title: Custom Font not Loaded in Mobile Device

Body:
I have website that using Gilroy. It's work well in desktop version.
But when I check it in mobile, or click link from social media application like Instagram, it's not work.

What can I do

Here is the way I add custom font, is it wrong?

@font-face {
  font-family: "Gilroy";
  src: url("../fonts/Gilroy-Regular.eot");
  src: local("☞../fonts/Gilroy-Regular"), local("../fonts/Gilroy-Regular"), url("../fonts/Gilroy-Regular.eot?#iefix") format("embedded-opentype"), url("../fonts/Gilroy-Regular.woff2") format("woff2"), url("../fonts/Gilroy-Regular.woff") format("woff"), url("../fonts/Gilroy-Regular.ttf") format("truetype");
  font-weight: normal;
  font-style: normal;
  font-display: swap;
}


问:
ByteBuddy loaded class is slower than expected
I'm using ByteBuddy to implement hasComponent(KClass): Boolean and <T> findComponentOrNull(KClass): T? for child classes of an Entity interface.

I've got it working, but it's around half the speed compared to a manual implementation.
Here's some simple benchmark results (codegen benchmark doesn't include the time it takes to generate the bytecode)

```<code>Benchmark                                                     Mode  Cnt          Score        Error  Units
CodegenBranchEntityBenchmark.findComponentOrNullBenchmark    thrpt    5   93353925.859 ± 626597.466  ops/s
ManualBranchEntityBenchmark.findComponentOrNullBenchmark     thrpt    5  213006529.660 ± 638025.482  ops/s
MapLookupEntityBenchmark.findComponentOrNullBenchmark        thrpt    5  168355957.091 ± 633810.959  ops/s
</code>```

I've compared the bytecode of the generated implementation and the manual implementation and they're almost identical. I'm guessing the generated class isn't being processed by the JIT at all for some reason?

javap -c output of manual implementation

javap -c output of generated implementation

The only significant difference from what I can tell is that the Kotlin compiler creates a PropertyReference1Impl which shouldn't affect performance this much?

EDIT:
I changed findComponentOrNull to take in a regular Java Class (can skip invoking JvmClassMappingKt#getJavaClass) and it's now running at the same speed. Seems like the JIT doesn't optimize KClass on dynamically loaded types? I have no clue why, but works as expected now.

Body:
I'm using ByteBuddy to implement hasComponent(KClass): Boolean and <T> findComponentOrNull(KClass): T? for child classes of an Entity interface.

I've got it working, but it's around half the speed compared to a manual implementation.
Here's some simple benchmark results (codegen benchmark doesn't include the time it takes to generate the bytecode)

Benchmark                                                     Mode  Cnt          Score        Error  Units
CodegenBranchEntityBenchmark.findComponentOrNullBenchmark    thrpt    5   93353925.859 ± 626597.466  ops/s
ManualBranchEntityBenchmark.findComponentOrNullBenchmark     thrpt    5  213006529.660 ± 638025.482  ops/s
MapLookupEntityBenchmark.findComponentOrNullBenchmark        thrpt    5  168355957.091 ± 633810.959  ops/s

I've compared the bytecode of the generated implementation and the manual implementation and they're almost identical. I'm guessing the generated class isn't being processed by the JIT at all for some reason?

javap -c output of manual implementation

javap -c output of generated implementation

The only significant difference from what I can tell is that the Kotlin compiler creates a PropertyReference1Impl which shouldn't affect performance this much?

EDIT:
I changed findComponentOrNull to take in a regular Java Class (can skip invoking JvmClassMappingKt#getJavaClass) and it's now running at the same speed. Seems like the JIT doesn't optimize KClass on dynamically loaded types? I have no clue why, but works as expected now.


问:
Matching query doesn't exist error when logging in as different user on different tabs on a browser
I am currently work on small project on djnago and it's almost finished. But from the beginning I have been facing a problem that, when I run the webpage on multiple tabs and logs in, only the last logged in user's full data is seen, when I go to the previously logged in user's tab it throws "MATCHING QUERY DOESN'T EXIST!". This makes me to log in with that particular user's data to be seen simultaneously the last logged in user's tab throws the previously mentioned error.

My requirement is "It should be able to login different users on different tabs on same browsers and without any error on djnago framework". Please let me know if there is any way.

Thanks
in advance


问:
How do I extract feature importances from a Sklearn pipeline
I'm wondering how I can extract feature importances from Logistic regression, GBM and XGBoost in scikit-learn with the feature names when using the classifier in a pipeline with preprocessing. I want to know how do I extract feature importances from a Sklearn pipeline?

From the brief research I've done, I am not sure if this is possible with scikit-learn.

I also found a package called ELI5 (https://eli5.readthedocs.io/en/latest/overview.html) that is supposed to fix that issue with sci-kit-learn but I would like to compare it with feature importance results.

Please see the code below:-

```<code># Defining regressand(Y) and regressors(X)
X = df3.drop(['Prediction_SAP_Burst','Unnamed: 0'], axis=1)
y = df3['Prediction_SAP_Burst']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.30, random_state=1,stratify=y)
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)

numerical_features = list(set(X.columns.to_list()))

numerical_transformer = Pipeline(steps=[
    ('scaler', MinMaxScaler())])

#Link all the transformers together in a ColumnTransformer

from sklearn.compose import ColumnTransformer

preprocessor = ColumnTransformer(
    transformers=[
        ('num', numerical_transformer, numerical_features)
            ])

from xgboost import XGBClassifier

# create a pipeline for each classifier.

lr_clf = Pipeline(steps=[('preprocessor', preprocessor),
                      ('lr', LogisticRegression(class_weight={0:0.52,1:16.14},random_state=1))])

xgb_clf = Pipeline(steps=[('preprocessor', preprocessor),
                      ('classifier', XGBClassifier(scale_pos_weight=8, random_state=1))])

gbc_clf = Pipeline(steps=[('preprocessor', preprocessor),
                      ('classifier', GradientBoostingClassifier(random_state=1, learning_rate=0.2, max_features=0.5,
                      n_estimators=250, subsample=0.8))])

lr_clf.fit(X_train, y_train)
xgb_clf.fit(X_train, y_train)
gbc_clf.fit(X_train, y_train)

#compute classification report and confusion matrix

def results(name: str, model: BaseEstimator) -> None:
    preds = model.predict(X_test)

    model_cv = cross_validate(model, X_train, y_train, cv=StratifiedKFold(n_splits=5), n_jobs=-1, scoring='f1')
    print(f"Kfold precision score: {model_cv['test_score']}")
    print(f"Average score of Kfold: {model_cv['test_score'].mean():.3f} +/- {model_cv['test_score'].std():.3f}")

    print(name + " score: %.3f" % model.score(X_test, y_test))
    print(classification_report(y_test, preds))
    labels = ['Good', 'Bad']

    conf_matrix = confusion_matrix(y_test, preds, normalize='true')

    font = {'family' : 'normal',
            'size'   : 14}

    plt.rc('font', **font)
    plt.figure(figsize= (10,6))
    sns.heatmap(conf_matrix, xticklabels=labels, yticklabels=labels, annot=True, cmap='Blues')
    plt.title("Confusion Matrix for " + name)
    plt.ylabel('True Class')
    plt.xlabel('Predicted Class')

results("Logistic Regression" , lr_clf)
results("X Gradient Boost" , xgb_clf)
results("Gradient boost Classifier" , gbc_clf)

</code>```

Body:
I'm wondering how I can extract feature importances from Logistic regression, GBM and XGBoost in scikit-learn with the feature names when using the classifier in a pipeline with preprocessing. I want to know how do I extract feature importances from a Sklearn pipeline?

From the brief research I've done, I am not sure if this is possible with scikit-learn.

I also found a package called ELI5 (https://eli5.readthedocs.io/en/latest/overview.html) that is supposed to fix that issue with sci-kit-learn but I would like to compare it with feature importance results.

Please see the code below:-

# Defining regressand(Y) and regressors(X)
X = df3.drop(['Prediction_SAP_Burst','Unnamed: 0'], axis=1)
y = df3['Prediction_SAP_Burst']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.30, random_state=1,stratify=y)
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)

numerical_features = list(set(X.columns.to_list()))

numerical_transformer = Pipeline(steps=[
    ('scaler', MinMaxScaler())])

#Link all the transformers together in a ColumnTransformer

from sklearn.compose import ColumnTransformer

preprocessor = ColumnTransformer(
    transformers=[
        ('num', numerical_transformer, numerical_features)
            ])

from xgboost import XGBClassifier

# create a pipeline for each classifier.

lr_clf = Pipeline(steps=[('preprocessor', preprocessor),
                      ('lr', LogisticRegression(class_weight={0:0.52,1:16.14},random_state=1))])

xgb_clf = Pipeline(steps=[('preprocessor', preprocessor),
                      ('classifier', XGBClassifier(scale_pos_weight=8, random_state=1))])

gbc_clf = Pipeline(steps=[('preprocessor', preprocessor),
                      ('classifier', GradientBoostingClassifier(random_state=1, learning_rate=0.2, max_features=0.5,
                      n_estimators=250, subsample=0.8))])

lr_clf.fit(X_train, y_train)
xgb_clf.fit(X_train, y_train)
gbc_clf.fit(X_train, y_train)

#compute classification report and confusion matrix

def results(name: str, model: BaseEstimator) -> None:
    preds = model.predict(X_test)

    model_cv = cross_validate(model, X_train, y_train, cv=StratifiedKFold(n_splits=5), n_jobs=-1, scoring='f1')
    print(f"Kfold precision score: {model_cv['test_score']}")
    print(f"Average score of Kfold: {model_cv['test_score'].mean():.3f} +/- {model_cv['test_score'].std():.3f}")

    print(name + " score: %.3f" % model.score(X_test, y_test))
    print(classification_report(y_test, preds))
    labels = ['Good', 'Bad']

    conf_matrix = confusion_matrix(y_test, preds, normalize='true')

    font = {'family' : 'normal',
            'size'   : 14}

    plt.rc('font', **font)
    plt.figure(figsize= (10,6))
    sns.heatmap(conf_matrix, xticklabels=labels, yticklabels=labels, annot=True, cmap='Blues')
    plt.title("Confusion Matrix for " + name)
    plt.ylabel('True Class')
    plt.xlabel('Predicted Class')

results("Logistic Regression" , lr_clf)
results("X Gradient Boost" , xgb_clf)
results("Gradient boost Classifier" , gbc_clf)


问:
Nuxt deployment

if (process.env.NODE_ENV === 'production'){
    app.use(express.static(__dirname + '/public/'))
    //handle SPA
    app.get(/.*/, (req,res) => res.sendFile(__dirname + '/public/views/app.template.html')) //refers to any route
}
```

what page / file do I serve app.get(/.*/, (req,res) => res.sendFile(__dirname + '/public/views/app.template.html')) here that will mean that when I localy / when I deploy my app it will run my nuxt app?

The app uses nuxt3 express node and axios, I have got it running perfectly on a dev server but deployment is causing a lot of problems since I can't find many solutions that I can understand. I was planning on deploying on vercel since its free but I was also considering heroku.

the screen shot is the public files

github link to the repo: https://github.com/Duckjpeg/dsad

Title: Nuxt deployment

Body:
if (process.env.NODE_ENV === 'production'){
    app.use(express.static(__dirname + '/public/'))
    //handle SPA
    app.get(/.*/, (req,res) => res.sendFile(__dirname + '/public/views/app.template.html')) //refers to any route
}

what page / file do I serve app.get(/.*/, (req,res) => res.sendFile(__dirname + '/public/views/app.template.html')) here that will mean that when I localy / when I deploy my app it will run my nuxt app?

The app uses nuxt3 express node and axios, I have got it running perfectly on a dev server but deployment is causing a lot of problems since I can't find many solutions that I can understand. I was planning on deploying on vercel since its free but I was also considering heroku.

the screen shot is the public files

github link to the repo: https://github.com/Duckjpeg/dsad


问:
App Stability Google play Console Eligibility issue
I can't publish my game, google just won't let me. Every time they send my this reason:

App stability
During testing we experienced stability issues with your app and were unable to successfully evaluate it for policy compliance. Please make sure your app behaves predictably at runtime and does not crash, hang, or display error messages.

Firebase show me that there are no errors, same does the internal testing report.
What's weird is that my old pre-release version was submitted as conditionally passed but the new ones stuck

I've tried tweaking minimum sdk lvl, updating unity engine to other versions, rebuilding and trying again but nothing helps


问:
Why output of laravel/telescope does not show any transaction commands?
Looking in laravel 9.19 app at output of laravel/telescope 4.9 I wondoer why it does not show any transaction commands ?
I checked file config/telescope.php and did not find any relative options...

Can it be configured ?

Thanks!


问:
Using Contentful to Steam Audio?
I am generating a card that Im getting data from Contentful.

The data contains 3 things, a title, description and an audiofile.

I want to play the audiofile on the react site.

I cannot seem to get this to work.

What I am getting back in my api call is this.

The URL being generated shows
//url:"//assets.ctfassets.net/rsocu0hl5psn/wq621YZ8fnnpEdkoAjgwf/09359abe52283b87a991da5a92575730/lesson_1_test.m4a"

I cannot seem to even target this URL.

I built this hook to get the data from contenful

```<code>const getCards = async () => {
    try {
      const entries = await client.getEntries({
        content_type: 'lessonCard',
        select: 'fields',
        order: 'fields.lessonNumber',
      })
      const sanitizeEntries = entries.items.map((item) => {
        return {
          ...item.fields,
        }
      })
      return sanitizeEntries
    } catch (error) {
      console.log(`Error getting Lesson Card: ${error}`)
    }
  }

  return { getCards }
}
</code>```

Title: Using Contentful to Steam Audio?

Body:
I am generating a card that Im getting data from Contentful.

The data contains 3 things, a title, description and an audiofile.

I want to play the audiofile on the react site.

I cannot seem to get this to work.

What I am getting back in my api call is this.

The URL being generated shows
//url:"//assets.ctfassets.net/rsocu0hl5psn/wq621YZ8fnnpEdkoAjgwf/09359abe52283b87a991da5a92575730/lesson_1_test.m4a"

I cannot seem to even target this URL.

I built this hook to get the data from contenful

const getCards = async () => {
    try {
      const entries = await client.getEntries({
        content_type: 'lessonCard',
        select: 'fields',
        order: 'fields.lessonNumber',
      })
      const sanitizeEntries = entries.items.map((item) => {
        return {
          ...item.fields,
        }
      })
      return sanitizeEntries
    } catch (error) {
      console.log(`Error getting Lesson Card: ${error}`)
    }
  }

  return { getCards }
}


问:
How pass a large array from js to c++ using emscripten?
I want to pass a large array from js to c++ using emscripten. But am only able to pass a small array of sizes 3 or 4. I keep getting this error for large arrays Uncaught (in promise) RuntimeError: memory access out of bounds
How would I pass an array of length 160000?

.js

Import function from Emscripten generated file.

Create example data to test float_multiply_array.

Get data byte size, allocate memory on Emscripten heap, and get
pointer.

Copy data to Emscripten heap (directly accessed from Module.HEAPU8)

Call function and get result.

Free memory.

```<code>function __CPPModule__(size,iterations) {
  const myModule = Module();
  return myModule.then((Module) => {
    // Import function from Emscripten generated file
    var cppf= Module.cwrap('testFunction', 'number', ['number', 'number', 'number']);

    // Create example data to test float_multiply_array
    var data = new Float32Array(size*size);

    // Get data byte size, allocate memory on Emscripten heap, and get pointer
    var nDataBytes = data.length * data.BYTES_PER_ELEMENT;
    var dataPtr = Module._malloc(nDataBytes);

    // Copy data to Emscripten heap (directly accessed from Module.HEAPU8)
    var dataHeap = new Uint8Array(Module.HEAPU8.buffer, dataPtr, nDataBytes);
    dataHeap.set(new Uint8Array(data.buffer));

    // Call function and get result
    cppf(dataHeap.byteOffset, size, iterations);
    var result = new Float32Array(dataHeap.buffer, dataHeap.byteOffset, data.length, iterations);
    // Free memory
    Module._free(dataHeap.byteOffset);
    return result
  })
}
async function jsTocpp(size,iterations){
  let f = await __CPPModule__(size,iterations)
  return f
}

var size = 400
var iterations = 0
console.log(jsTocpp(size,iterations));

</code>```

.cpp

loop the array from world.map and add it to arr

```<code>
class World{
public:
  //Constructor
  World(int size) {
   ...
  }

   double map[400][400] ={0.0};

};

extern "C" {
    EMSCRIPTEN_KEEPALIVE int testFunction(float *arr, int size, int iter) {
        World world(size);

        int row = size;
        int col = size;

        for(int i = 0; i < row; ++i)
        for(int j = 0; j < col; ++j)
              arr[i * col + j] = (float)world.map[i][j]; //copy the data from 2D array to 1D array
      return 0;
    }
}
</code>```

Body:
I want to pass a large array from js to c++ using emscripten. But am only able to pass a small array of sizes 3 or 4. I keep getting this error for large arrays Uncaught (in promise) RuntimeError: memory access out of bounds
How would I pass an array of length 160000?

.js

Import function from Emscripten generated file.

Create example data to test float_multiply_array.

Get data byte size, allocate memory on Emscripten heap, and get
pointer.

Copy data to Emscripten heap (directly accessed from Module.HEAPU8)

Call function and get result.

Free memory.

function __CPPModule__(size,iterations) {
  const myModule = Module();
  return myModule.then((Module) => {
    // Import function from Emscripten generated file
    var cppf= Module.cwrap('testFunction', 'number', ['number', 'number', 'number']);

    // Create example data to test float_multiply_array
    var data = new Float32Array(size*size);

    // Get data byte size, allocate memory on Emscripten heap, and get pointer
    var nDataBytes = data.length * data.BYTES_PER_ELEMENT;
    var dataPtr = Module._malloc(nDataBytes);

    // Copy data to Emscripten heap (directly accessed from Module.HEAPU8)
    var dataHeap = new Uint8Array(Module.HEAPU8.buffer, dataPtr, nDataBytes);
    dataHeap.set(new Uint8Array(data.buffer));

    // Call function and get result
    cppf(dataHeap.byteOffset, size, iterations);
    var result = new Float32Array(dataHeap.buffer, dataHeap.byteOffset, data.length, iterations);
    // Free memory
    Module._free(dataHeap.byteOffset);
    return result
  })
}
async function jsTocpp(size,iterations){
  let f = await __CPPModule__(size,iterations)
  return f
}

var size = 400
var iterations = 0
console.log(jsTocpp(size,iterations));

.cpp

loop the array from world.map and add it to arr

class World{
public:
  //Constructor
  World(int size) {
   ...
  }

   double map[400][400] ={0.0};

};

extern "C" {
    EMSCRIPTEN_KEEPALIVE int testFunction(float *arr, int size, int iter) {
        World world(size);

        int row = size;
        int col = size;

        for(int i = 0; i < row; ++i)
        for(int j = 0; j < col; ++j)
              arr[i * col + j] = (float)world.map[i][j]; //copy the data from 2D array to 1D array
      return 0;
    }
}


问:
Ajax - On success, await for function
I have an AJAX function that on success redirects me to another page, and once on that page, it should run another JS function that does some CSS stuff with some elements of that page. But for some reason, the second function does not wait for the page to redirect before running. I've tried .then and async/await. Please let me know if I'm doing something wrong.

Here is what I've tried:

JS Functions

```<code>async function redirectEvent(event_id) {
  window.location.href = "/event/" + event_id;
}

function delay(time) {
  return new Promise(resolve => setTimeout(resolve, time));
}
</code>```

AJAX Functions I've tried

```<code>function inviteEventAttendee(event_id, user_id) {
      $.ajax({
          method: "POST",
          headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
          url: "{{ route('inviteEventAttendee') }}",
          data: { event_id: event_id, user_id: user_id },
          success: async function (response) {
              await redirectEvent(event_id);
              delay(5000).then(() => console.log("Responseeeeeeeeeeeeeeeeee"));
          }
      });
}

function inviteEventAttendee(event_id, user_id) {
      $.ajax({
          method: "POST",
          headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
          url: "{{ route('inviteEventAttendee') }}",
          data: { event_id: event_id, user_id: user_id },
          success: function (response) {
              redirectEvent(event_id).then(() => console.log("Responseeeeeeeeeeeeeeeeee"));
          }
      });
}
</code>```

The problem I'm having is that when I run the code, I instantly see the console log and then it redirects that page, so it's not waiting for the page to load.

Title: Ajax - On success, await for function

Body:
I have an AJAX function that on success redirects me to another page, and once on that page, it should run another JS function that does some CSS stuff with some elements of that page. But for some reason, the second function does not wait for the page to redirect before running. I've tried .then and async/await. Please let me know if I'm doing something wrong.

Here is what I've tried:

JS Functions

async function redirectEvent(event_id) {
  window.location.href = "/event/" + event_id;
}

function delay(time) {
  return new Promise(resolve => setTimeout(resolve, time));
}

AJAX Functions I've tried

function inviteEventAttendee(event_id, user_id) {
      $.ajax({
          method: "POST",
          headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
          url: "{{ route('inviteEventAttendee') }}",
          data: { event_id: event_id, user_id: user_id },
          success: async function (response) {
              await redirectEvent(event_id);
              delay(5000).then(() => console.log("Responseeeeeeeeeeeeeeeeee"));
          }
      });
}

function inviteEventAttendee(event_id, user_id) {
      $.ajax({
          method: "POST",
          headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
          url: "{{ route('inviteEventAttendee') }}",
          data: { event_id: event_id, user_id: user_id },
          success: function (response) {
              redirectEvent(event_id).then(() => console.log("Responseeeeeeeeeeeeeeeeee"));
          }
      });
}

The problem I'm having is that when I run the code, I instantly see the console log and then it redirects that page, so it's not waiting for the page to load.


问:
sftpAdapter past different filename
I have a ResourceFileDownloader for sftpAdapter in Spring and i want to past different filename to get different file.

```<code>@Configuration
@EnableIntegration
public class ResourceFileDownloader
{
   private final String host;
   private final int port;
   private final String username;
   private final String password;
   private final String fileDirectory;

   public ResourceFileDownloader(@Value("${resourceprovider.host}") String host,
                                 @Value("${resourceprovider.port}") String port,
                                 @Value("${resourceprovider.user}") String username,
                                 @Value("${resourceprovider.password}") String password,
                                 @Value("${resourceprovider.directory}") String fileDirectory)
   {
      this.host = host;
      this.port = Integer.parseInt(port);
      this.username = username;
      this.password = password;
      this.fileDirectory = fileDirectory;
   }

   @Bean
   public SessionFactory<ChannelSftp.LsEntry> sftpSessionFactory()
   {
      DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true);
      factory.setHost(this.host);
      factory.setPort(this.port);
      factory.setUser(this.username);
      factory.setPassword(this.password);
      factory.setAllowUnknownKeys(true);
      return new CachingSessionFactory<>(factory);
   }

   @Bean
   public SftpRemoteFileTemplate template()
   {
      return new SftpRemoteFileTemplate(sftpSessionFactory());
   }

   @Bean
   @InboundChannelAdapter(channel = "sftpChannel", poller = @Poller(fixedDelay = "30000"))
   public MessageSource<InputStream> sftpMessageSource()
   {
      SftpStreamingMessageSource source = new SftpStreamingMessageSource(template());
      source.setRemoteDirectory(this.fileDirectory);
      source.setFilter(new SftpSimplePatternFileListFilter("/FileName_%s.csv"));
      source.setMaxFetchSize(1);
      return source;
   }

   @Bean(name = "sftpChannel")
   public MessageChannel fromSftpChannel()
   {
      return new PublishSubscribeChannel();
   }
</code>```

How to configure sftpAdapter to past different fileName into source.setFilter(new SftpSimplePatternFileListFilter("/FileName_%s.csv"));

i use: implementation "org.springframework.integration:spring-integration-sftp:5.5.15"

Title: sftpAdapter past different filename

Body:
I have a ResourceFileDownloader for sftpAdapter in Spring and i want to past different filename to get different file.

@Configuration
@EnableIntegration
public class ResourceFileDownloader
{
   private final String host;
   private final int port;
   private final String username;
   private final String password;
   private final String fileDirectory;

   public ResourceFileDownloader(@Value("${resourceprovider.host}") String host,
                                 @Value("${resourceprovider.port}") String port,
                                 @Value("${resourceprovider.user}") String username,
                                 @Value("${resourceprovider.password}") String password,
                                 @Value("${resourceprovider.directory}") String fileDirectory)
   {
      this.host = host;
      this.port = Integer.parseInt(port);
      this.username = username;
      this.password = password;
      this.fileDirectory = fileDirectory;
   }

   @Bean
   public SessionFactory<ChannelSftp.LsEntry> sftpSessionFactory()
   {
      DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true);
      factory.setHost(this.host);
      factory.setPort(this.port);
      factory.setUser(this.username);
      factory.setPassword(this.password);
      factory.setAllowUnknownKeys(true);
      return new CachingSessionFactory<>(factory);
   }

   @Bean
   public SftpRemoteFileTemplate template()
   {
      return new SftpRemoteFileTemplate(sftpSessionFactory());
   }

   @Bean
   @InboundChannelAdapter(channel = "sftpChannel", poller = @Poller(fixedDelay = "30000"))
   public MessageSource<InputStream> sftpMessageSource()
   {
      SftpStreamingMessageSource source = new SftpStreamingMessageSource(template());
      source.setRemoteDirectory(this.fileDirectory);
      source.setFilter(new SftpSimplePatternFileListFilter("/FileName_%s.csv"));
      source.setMaxFetchSize(1);
      return source;
   }

   @Bean(name = "sftpChannel")
   public MessageChannel fromSftpChannel()
   {
      return new PublishSubscribeChannel();
   }

How to configure sftpAdapter to past different fileName into source.setFilter(new SftpSimplePatternFileListFilter("/FileName_%s.csv"));

i use: implementation "org.springframework.integration:spring-integration-sftp:5.5.15"


问:
Multi selection didn't get all records , all records didn't load before select
```<code>[ExtensionOf(formControlStr(BankReconciliation ,ClearALL))]
 final class ClearAll_Extension
{

    void clicked()
    {

        next clicked();

        FormRun formrunn = this.FormRun();

        FormCheckBoxControl BankAccountTrans_Included = formrunn.design().controlName("BankAccountTrans_Included");

        FormDataSource BankAccountTran = formrunn.dataSource("BankAccountTrans");

        BankAccountTrans Bankacc  ;

        int  recordsCount ;

        recordsCount= BankAccountTran.recordsMarked().lastIndex();  // Total no of marked records.

        if (BankAccountTran.cursor().RecId != BankAccountTran.getFirst().RecId)
        {
            BankAccountTran.cursor(BankAccountTran.first());
        }

        for (Bankacc = BankAccountTran.getFirst(true) ? BankAccountTran.getFirst(true) : BankAccountTran.cursor(); Bankacc; Bankacc = BankAccountTran.getNext())
        {
            PurchTable_ds.findRecord(Bankacc);

        }

            if (Bankacc.Included == NoYes::No)
            {
                BankAccountTran.object(fieldNum(BankAccountTrans,Included)).setValue(NoYes::Yes) ;
                BankAccountTran.write();

            }
            recordsCount-- ;
            if (recordsCount == 0 || BankAccountTran.next() == 0)
            {
                BankAccountTran.research();
                BankAccountTran.reread();
                BankAccountTran.refresh();
                break;
            }
        }
    }

}
</code>```

this code run successfully on small data but in a large data it is not running well because when we open the form and clicked select all not all data be loaded method run in some of records that loaded in first time but the other the method didn't run on it because it can't see all reocords , how to make multiselect get all records and run methods on all of them ? , or how to make all records load first and then select ?

Body:
[ExtensionOf(formControlStr(BankReconciliation ,ClearALL))]
 final class ClearAll_Extension
{

    void clicked()
    {

        next clicked();

        FormRun formrunn = this.FormRun();

        FormCheckBoxControl BankAccountTrans_Included = formrunn.design().controlName("BankAccountTrans_Included");

        FormDataSource BankAccountTran = formrunn.dataSource("BankAccountTrans");

        BankAccountTrans Bankacc  ;

        int  recordsCount ;

        recordsCount= BankAccountTran.recordsMarked().lastIndex();  // Total no of marked records.

        if (BankAccountTran.cursor().RecId != BankAccountTran.getFirst().RecId)
        {
            BankAccountTran.cursor(BankAccountTran.first());
        }

        for (Bankacc = BankAccountTran.getFirst(true) ? BankAccountTran.getFirst(true) : BankAccountTran.cursor(); Bankacc; Bankacc = BankAccountTran.getNext())
        {
            PurchTable_ds.findRecord(Bankacc);

        }

            if (Bankacc.Included == NoYes::No)
            {
                BankAccountTran.object(fieldNum(BankAccountTrans,Included)).setValue(NoYes::Yes) ;
                BankAccountTran.write();

            }
            recordsCount-- ;
            if (recordsCount == 0 || BankAccountTran.next() == 0)
            {
                BankAccountTran.research();
                BankAccountTran.reread();
                BankAccountTran.refresh();
                break;
            }
        }
    }

}

this code run successfully on small data but in a large data it is not running well because when we open the form and clicked select all not all data be loaded method run in some of records that loaded in first time but the other the method didn't run on it because it can't see all reocords , how to make multiselect get all records and run methods on all of them ? , or how to make all records load first and then select ?


问:
Map function throwing Type 'Element[]' is missing the following properties error
I keep getting the error TS2739: Type 'Element[]' is missing the following properties from type 'ReactElement  >': type, props, key, what would be the best way to fix it?

```<code>export interface IHome {
  heading: string;
  title: string;
  description: string;
  features: { description: string; title: string }[];
  imgUrl: string;
  testimonial: { role: string; quote: string; name: string; company: string; imgSrc: string };
  bgColor?: string;
}

export const home: IHome[] = [
  {
    heading: 'test',
    title: 'test',
    description: 'test',
    features: [
      {
        title: 'test',
        description: 'test',
      },
      {
        title: 'test',
        description: 'test',
      },
      {
        title: 'test',
        description: 'test',
      },
    ],
    imgUrl: 'test.png',
    testimonial: {
      name: 'test',
      role: 'test',
      company: 'test',
      quote: 'test',
      imgSrc: 'images/test.jpg',
    },
    bgColor: 'bg-gray-50',
  },
];

const Home: NextPage = () => {
  return (
    <>
      <Layout>
        <Navbar />
        <Hero />
        <LogoCloud />
        {home.map((item, index) => (
          <Features
            key={index}
            heading={item.heading}
            title={item.title}
            description={item.description}
            features={item.features}
            imgUrl={item.imgUrl}
            bgColor={item.bgColor}>
            <Testimonial
              key={index}
              name={item.testimonial.name}
              role={item.testimonial.role}
              company={item.testimonial.company}
              imgSrc={item.testimonial.imgSrc}
              quote={item.testimonial.quote}/>
          </Features>
        ))}
        <FeaturesSummary />
        <FooterCta />
        <Footer />
      </Layout>
    </>
  );
};
</code>```

Features component

```<code>import * as React from 'react';
import { JSXElementConstructor, ReactElement } from 'react';

export default function Features({
  heading,
  title,
  description,
  features,
  imgUrl,
  children,
  bgColor,
}: {
  heading: string;
  title: string;
  description: string;
  features: { title: string; description: string }[];
  imgUrl: string;
  children?: ReactElement<React.ReactNode, string | JSXElementConstructor<unknown>>;
  bgColor?: string;
}) {
  const bgStyle = `relative ${bgColor} py-16 sm:pt-24 lg:py-16`;
  return (
    <section id="analytics">
      <div className={bgStyle}>
        <div className="mx-auto max-w-md px-4 text-center sm:max-w-3xl sm:px-6 lg:max-w-7xl lg:px-8">
          <div>
            <h2 className="text-lg font-medium lg:font-semibold text-sky-500">{heading}</h2>
            <p className="mt-2 text-3xl font-medium lg:font-bold tracking-tight text-gray-900 sm:text-4xl">{title}</p>
            <p className="mx-auto mt-5 max-w-prose text-xl text-gray-500">{description}</p>
          </div>
        </div>
        <div className="relative overflow-hidden">
          <div aria-hidden="true" className="absolute inset-x-0 top-0 h-48" />
          <div className="relative">
            <div className="lg:mx-auto lg:grid lg:max-w-7xl lg:grid-flow-col-dense lg:grid-cols-2 lg:gap-24 lg:px-8">
              <div className="mx-auto max-w-xl px-4 sm:px-6 lg:mx-0 lg:max-w-none lg:py-16 lg:px-0">
                {features.map((feature, key) => (
                  <div className="py-6" key={key}>
                    <h2 className="text-2xl font-bold tracking-tight text-gray-900">{feature.title}</h2>
                    <p className="mt-4 text-lg text-gray-500">{feature.description}</p>
                  </div>
                ))}
                <div className="mt-6">
                  <a
                    href="#"
                    className="inline-flex rounded-md border border-transparent bg-sky-300 px-6 py-3 text-xl
                      font-medium text-black shadow-sm xl:font-bold hover:bg-sky-200 focus:outline-none"
                  >
                    Get started
                  </a>
                </div>
              </div>
              <div className="mt-12 sm:mt-16 lg:mt-0 flex items-center">
                <div className="pl-4 md:-mr-48 sm:pl-6 mr-4 md:-mr-16 lg:px-0 lg:m-0">
                  <img className="w-full rounded-xl" src={imgUrl} alt={description} />
                </div>
              </div>
            </div>
          </div>
        </div>
        <div>{children}</div>
      </div>
    </section>
  );
}
</code>```

Testimonial component

```<code>export default function Testimonial({
  name,
  role,
  company,
  imgSrc,
  quote,
}: {
  name: string;
  role: string;
  company: string;
  imgSrc: string;
  quote: string;
}) {
  return (
    <section className="overflow-hidden">
      <div className="relative mx-auto max-w-7xl px-4 pt-20 pb-12 sm:px-6 lg:px-8 lg:py-20">
        <div className="relative lg:flex lg:items-center">
          <div className="hidden lg:block lg:flex-shrink-0">
            <img className="h-64 w-64 rounded-full" src={imgSrc} alt={`${name}, ${company}`} />
          </div>

          <div className="relative lg:ml-10">
            <svg
              className="absolute top-0 left-0 h-36 w-36 -translate-x-8 -translate-y-24 transform text-gray-200 opacity-50"
              stroke="currentColor"
              fill="none"
              viewBox="0 0 144 144"
              aria-hidden="true"
            >
              <path
                strokeWidth={2}
                d="M41.485 15C17.753 31.753 1 59.208 1 89.455c0 24.664 14.891 39.09 32.109 39.09 16.287 0 28.386-13.03 28.386-28.387 0-15.356-10.703-26.524-24.663-26.524-2.792 0-6.515.465-7.446.93 2.327-15.821 17.218-34.435 32.11-43.742L41.485 15zm80.04 0c-23.268 16.753-40.02 44.208-40.02 74.455 0 24.664 14.891 39.09 32.109 39.09 15.822 0 28.386-13.03 28.386-28.387 0-15.356-11.168-26.524-25.129-26.524-2.792 0-6.049.465-6.98.93 2.327-15.821 16.753-34.435 31.644-43.742L121.525 15z"
              />
            </svg>
            <blockquote className="relative">
              <div className="text-xl font-medium leading-8 text-gray-900">
                <p>{quote}</p>
              </div>
              <footer className="mt-8">
                <div className="flex">
                  <div className="flex-shrink-0 lg:hidden">
                    <img className="h-12 w-12 rounded-full" src={imgSrc} alt={`${name}, ${company}`} />
                  </div>
                  <div className="ml-4 lg:ml-0">
                    <div className="text-base font-medium text-gray-900">{name}</div>
                    <div className="text-base font-medium text-gray-500">
                      {role}, {company}
                    </div>
                  </div>
                </div>
              </footer>
            </blockquote>
          </div>
        </div>
      </div>
    </section>
  );
}
</code>```

Body:
I keep getting the error TS2739: Type 'Element[]' is missing the following properties from type 'ReactElement  >': type, props, key, what would be the best way to fix it?

export interface IHome {
  heading: string;
  title: string;
  description: string;
  features: { description: string; title: string }[];
  imgUrl: string;
  testimonial: { role: string; quote: string; name: string; company: string; imgSrc: string };
  bgColor?: string;
}

export const home: IHome[] = [
  {
    heading: 'test',
    title: 'test',
    description: 'test',
    features: [
      {
        title: 'test',
        description: 'test',
      },
      {
        title: 'test',
        description: 'test',
      },
      {
        title: 'test',
        description: 'test',
      },
    ],
    imgUrl: 'test.png',
    testimonial: {
      name: 'test',
      role: 'test',
      company: 'test',
      quote: 'test',
      imgSrc: 'images/test.jpg',
    },
    bgColor: 'bg-gray-50',
  },
];

const Home: NextPage = () => {
  return (
    <>
      <Layout>
        <Navbar />
        <Hero />
        <LogoCloud />
        {home.map((item, index) => (
          <Features
            key={index}
            heading={item.heading}
            title={item.title}
            description={item.description}
            features={item.features}
            imgUrl={item.imgUrl}
            bgColor={item.bgColor}>
            <Testimonial
              key={index}
              name={item.testimonial.name}
              role={item.testimonial.role}
              company={item.testimonial.company}
              imgSrc={item.testimonial.imgSrc}
              quote={item.testimonial.quote}/>
          </Features>
        ))}
        <FeaturesSummary />
        <FooterCta />

      </Layout>
    </>
  );
};

Features component

import * as React from 'react';
import { JSXElementConstructor, ReactElement } from 'react';

export default function Features({
  heading,
  title,
  description,
  features,
  imgUrl,
  children,
  bgColor,
}: {
  heading: string;
  title: string;
  description: string;
  features: { title: string; description: string }[];
  imgUrl: string;
  children?: ReactElement<React.ReactNode, string | JSXElementConstructor<unknown>>;
  bgColor?: string;
}) {
  const bgStyle = `relative ${bgColor} py-16 sm:pt-24 lg:py-16`;
  return (

{heading}

{title}

{description}

                {features.map((feature, key) => (

{feature.title}

{feature.description}

                ))}

                    Get started

{children}

  );
}

Testimonial component

export default function Testimonial({
  name,
  role,
  company,
  imgSrc,
  quote,
}: {
  name: string;
  role: string;
  company: string;
  imgSrc: string;
  quote: string;
}) {
  return (

            <img className="h-64 w-64 rounded-full" src={imgSrc} alt={`${name}, ${company}`} />

            <svg
              className="absolute top-0 left-0 h-36 w-36 -translate-x-8 -translate-y-24 transform text-gray-200 opacity-50"
              stroke="currentColor"
              fill="none"
              viewBox="0 0 144 144"
              aria-hidden="true"
            >
              <path
                strokeWidth={2}
                d="M41.485 15C17.753 31.753 1 59.208 1 89.455c0 24.664 14.891 39.09 32.109 39.09 16.287 0 28.386-13.03 28.386-28.387 0-15.356-10.703-26.524-24.663-26.524-2.792 0-6.515.465-7.446.93 2.327-15.821 17.218-34.435 32.11-43.742L41.485 15zm80.04 0c-23.268 16.753-40.02 44.208-40.02 74.455 0 24.664 14.891 39.09 32.109 39.09 15.822 0 28.386-13.03 28.386-28.387 0-15.356-11.168-26.524-25.129-26.524-2.792 0-6.049.465-6.98.93 2.327-15.821 16.753-34.435 31.644-43.742L121.525 15z"
              />
            </svg>

{quote}

                    <img className="h-12 w-12 rounded-full" src={imgSrc} alt={`${name}, ${company}`} />

{name}

                      {role}, {company}

  );
}


问:
best way to serve local file via express.js server
Our server serves single json file which has 1GB size. When request incomes, server reads that file and if certain element is included(matched) then we server that file, but if not, just throws an error.

There are two tackling points,

every time request is comming, read same file every time. we just want to read certain line

serve the file to thousands of users "concurrently".

How to design, non-blocking, asynchronous, efficient way of serving file?

// pseudo code
(req, res) => {
  fs.readFile('/path/to/file.json', (result) => {
    if (!someValidationLogic(result, req.body.someParameter)) {
      throw new Error();
    }
    return res.send(result);
  });
};
```

this is bad because, it does not utilize 'stream' functionality of node.js

Body:
Our server serves single json file which has 1GB size. When request incomes, server reads that file and if certain element is included(matched) then we server that file, but if not, just throws an error.

There are two tackling points,

every time request is comming, read same file every time. we just want to read certain line

serve the file to thousands of users "concurrently".

How to design, non-blocking, asynchronous, efficient way of serving file?

// pseudo code
(req, res) => {
  fs.readFile('/path/to/file.json', (result) => {
    if (!someValidationLogic(result, req.body.someParameter)) {
      throw new Error();
    }
    return res.send(result);
  });
};

this is bad because, it does not utilize 'stream' functionality of node.js


问:
Writing data to google sheets using Google Sheets API with R
I try to write a data frame to google sheets using R. I've successfully added data frame example from google for developers API reference method selector but got Error 404 when tried to do so from my R script.

I've successfully got API credentials by token <- gargle::token_fetch() with spreadsheet and drive scopes. I've inserted some blank lines in the beginning of my table:

```<code>sheet_ins_range <- jsonlite::fromJSON('{
  "requests": [
    {
      "insertRange": {
        "range": {
          "startRowIndex": 2,
          "endRowIndex": 2,
          "sheetId": XXXXX
        },
        "shiftDimension": "ROWS"
      }
    }
  ]
}')

sheet_ins_range$requests$insertRange$range$endRowIndex <- 10

body <- jsonlite::toJSON(sheet_ins_range)

response <- POST("https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}:batchUpdate",
            body = body, encode = "json",  config(token = token))

# response: Status: 200
</code>```

But when I try to write some data into this region I get Error Status: 404.

```<code>google_BU <- jsonlite::fromJSON('{
  "data": [
    {
      "range": "Sheet1!A1:D4",
      "values": [
        ["Item", "Cost", "Stocked", "Ship Date"],
        ["Wheel", "$20.50", "4", "3/1/2016"],
        ["Door", "$15", "2", "3/15/2016"],
        ["Engine", "$100", "1", "3/20/2016"]],
      "majorDimension": "ROWS"
    }
  ],
  "valueInputOption": "USER_ENTERED"
}')

body <- jsonlite::toJSON(google_BU)

response <- POST("https://docs.google.com/spreadsheets/d/{spreadsheetId}/values:batchUpdate",
            body = body, encode = "json",  config(token = token))

# response: Status: 404
</code>```

I suppose I do something wrong with HTTP request, because there is nothing wrong with this request body when I use googles "Try this method" page.

Body:
I try to write a data frame to google sheets using R. I've successfully added data frame example from google for developers API reference method selector but got Error 404 when tried to do so from my R script.

I've successfully got API credentials by token <- gargle::token_fetch() with spreadsheet and drive scopes. I've inserted some blank lines in the beginning of my table:

sheet_ins_range <- jsonlite::fromJSON('{
  "requests": [
    {
      "insertRange": {
        "range": {
          "startRowIndex": 2,
          "endRowIndex": 2,
          "sheetId": XXXXX
        },
        "shiftDimension": "ROWS"
      }
    }
  ]
}')

sheet_ins_range$requests$insertRange$range$endRowIndex <- 10

body <- jsonlite::toJSON(sheet_ins_range)

response <- POST("https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}:batchUpdate",
            body = body, encode = "json",  config(token = token))

# response: Status: 200

But when I try to write some data into this region I get Error Status: 404.

google_BU <- jsonlite::fromJSON('{
  "data": [
    {
      "range": "Sheet1!A1:D4",
      "values": [
        ["Item", "Cost", "Stocked", "Ship Date"],
        ["Wheel", "$20.50", "4", "3/1/2016"],
        ["Door", "$15", "2", "3/15/2016"],
        ["Engine", "$100", "1", "3/20/2016"]],
      "majorDimension": "ROWS"
    }
  ],
  "valueInputOption": "USER_ENTERED"
}')

body <- jsonlite::toJSON(google_BU)

response <- POST("https://docs.google.com/spreadsheets/d/{spreadsheetId}/values:batchUpdate",
            body = body, encode = "json",  config(token = token))

# response: Status: 404

I suppose I do something wrong with HTTP request, because there is nothing wrong with this request body when I use googles "Try this method" page.


问:
How does a child(ren) indicate that their finished loading for React.Suspense?
I'm going through the Suspense guide, but I am having trouble understanding what is the indicator to say it's completed.

There's a note that indicates this

Only Suspense-enabled data sources will activate the Suspense component. They include:

Data fetching with Suspense-enabled frameworks like Relay and Next.js

Lazy-loading component code with lazy

It also notes:

Suspense does not detect when data is fetched inside an Effect or event handler.

The first example sounds like there is a way of signaling that something is completed, but I can't find the information.

So is there any way of doing this or is Suspense not feasible in a react native context?


问:
how to fetch data from single product to livewire component?
ERROR :

Unable to resolve dependency [Parameter #0 [  $id ]] in class App\Http\Livewire\Counter

web.php :

```<code>Route::middleware('auth')->group(function () {

    Route::get('product-details/{id}/', 'SiteController@productDetails')->name('product.details');
});
</code>```

app/http/livewire/Counter.php :

```<code>class Counter extends Component
{

    public $product;

    public function mount($id)
    {
       $this->product = product::find($id);
    }

    public function render()
    {
       return view('livewire.product', [
          'product' => $this->product,
       ]);
    }

}

</code>```

how to fetch data from single product to livewire component?
i want to get product single id in blade file

Body:
ERROR :

Unable to resolve dependency [Parameter #0 [  $id ]] in class App\Http\Livewire\Counter

web.php :

Route::middleware('auth')->group(function () {

    Route::get('product-details/{id}/', 'SiteController@productDetails')->name('product.details');
});

app/http/livewire/Counter.php :

class Counter extends Component
{

    public $product;

    public function mount($id)
    {
       $this->product = product::find($id);
    }

    public function render()
    {
       return view('livewire.product', [
          'product' => $this->product,
       ]);
    }

}

how to fetch data from single product to livewire component?
i want to get product single id in blade file


问:
Ktor interceptor response.bodyAsText consumes the response body
I'm using ktor for my new app, and I'm running into an issure where I want to log the response body, but in doing so throws an error because the response JSON is no longer available for deserializing.

Here is my client (notice that I already have logging installed, but for some reason that doesn't work, so I resorted to logging in an interceptor -- Fix this too, KTOR...)

```<code>val client = HttpClient {
        install(ContentNegotiation) {
            json(json)
        }
        install(Logging) {
            logger = Logger.DEFAULT
            level = LogLevel.ALL
        }
        defaultRequest {
            url(BuildConfig.HOST_NAME)
            contentType(ContentType.Application.Json)
            accept(ContentType.Application.Json)
        }
    }.apply {
        plugin(HttpSend).intercept { req ->
            val call = execute(req)
            val response = call.response
            println("responseBody=${response.bodyAsText()}")
            call
        }
    }
</code>```

And the error I get

```<code>io.ktor.serialization.JsonConvertException: Illegal input
Caused by: kotlinx.serialization.json.internal.JsonDecodingException: Expected start of the object '{', but had 'EOF' instead at path: $

</code>```

The JSON serializer is basically receving an EOF -- lol.

If I REMOVE the println("responseBody=${response.bodyAsText()}"), the app works fine.

If I try this

```<code>println("responseBody=${response.body<Any>()}")
</code>```

the printed output is this

```<code>body=HttpResponse[http://localhost:3000/myApp/request, 200 OK]
</code>```

Which is obviously unusable

Body:
I'm using ktor for my new app, and I'm running into an issure where I want to log the response body, but in doing so throws an error because the response JSON is no longer available for deserializing.

Here is my client (notice that I already have logging installed, but for some reason that doesn't work, so I resorted to logging in an interceptor -- Fix this too, KTOR...)

val client = HttpClient {
        install(ContentNegotiation) {
            json(json)
        }
        install(Logging) {
            logger = Logger.DEFAULT
            level = LogLevel.ALL
        }
        defaultRequest {
            url(BuildConfig.HOST_NAME)
            contentType(ContentType.Application.Json)
            accept(ContentType.Application.Json)
        }
    }.apply {
        plugin(HttpSend).intercept { req ->
            val call = execute(req)
            val response = call.response
            println("responseBody=${response.bodyAsText()}")
            call
        }
    }

And the error I get

io.ktor.serialization.JsonConvertException: Illegal input
Caused by: kotlinx.serialization.json.internal.JsonDecodingException: Expected start of the object '{', but had 'EOF' instead at path: $

The JSON serializer is basically receving an EOF -- lol.

If I REMOVE the println("responseBody=${response.bodyAsText()}"), the app works fine.

If I try this

println("responseBody=${response.body<Any>()}")

the printed output is this

body=HttpResponse[http://localhost:3000/myApp/request, 200 OK]

Which is obviously unusable


问:
UseEffect not re-rendering on use state object property change
I have a component that fetches data from an API and displays it in a select box. When the select box is changed, it updates a property inside the state. When this is done, I want to run a different useEffect which fetches more values from the API based on the selected item.

```<code>// State for dropdown options
const [categories, setCategories] = useState<DropdownItemProps[]>([]);

// State for form
const [category] = useState<CategoryInstance>({
    id: "",
    number: 1,
    sponsor: "",
    logo: "",
    permit: "",
    bumpSpot: 128,
    raceEventId: "670d34d5-134b-4408-91bd-691f8c4b62d2",
    categoryId: "",
    configurationId: "",
    category: null,
    configuration: null,
    raceEvent: null,
    ladder: null,
    entryList: [],
    rounds: [],
});

// UseEffect 1, fetch dropdown items on load
useEffect(() => {
    console.log("Use effect 1");
    let c: DropdownItemProps[] = [];
    categoryStore.loadCategories().then(() => {
        categoryStore.categories.forEach((x) =>
            c.push({
                key: x.id,
                value: x.id,
                text: x.name,
            })
        );
        setCategories(c);
    });
}, [categoryStore]);

// UseEffect 2, fetch more items
useEffect(() => {
    console.log("Use effect 2");
    console.log(`ID: ${category.categoryId}`);
}, [category.categoryId]);
</code>```

From my understanding, when the category.categoryId changes value, it should cause the UseEffect to print out the information. But this isn't happening.

```<code><SelectInput
name='categoryId'
placeholder='Category'
label='Category'
options={categories}
search
/>
</code>```

Select Input

```<code>import { useField } from "formik";
import { DropdownItemProps, Form, Label, Select } from "semantic-ui-react";

interface Props {
    placeholder: string;
    name: string;
    type?: string;
    label?: string;
    options: DropdownItemProps[];
    search: boolean;
}

export default function SelectInput(props: Props) {
    const [field, meta, helpers] = useField(props.name);
    return (
        <Form.Field error={meta.touched && !!meta.error}>
            <label>{props.label}</label>
            <Select
                clearable
                options={props.options}
                value={field.value || null}
                onChange={(event, data) => helpers.setValue(data.value)}
                onBlur={() => helpers.setTouched(true)}
                placeholder={props.placeholder}
                search={props.search}
            />
            {meta.touched && meta.error ? (
                <Label basic color='red'>
                    {meta.error}
                </Label>
            ) : null}
        </Form.Field>
    );
}
</code>```

Any help would great,
Thanks.

Body:
I have a component that fetches data from an API and displays it in a select box. When the select box is changed, it updates a property inside the state. When this is done, I want to run a different useEffect which fetches more values from the API based on the selected item.

// State for dropdown options
const [categories, setCategories] = useState<DropdownItemProps[]>([]);

// State for form
const [category] = useState<CategoryInstance>({
    id: "",
    number: 1,
    sponsor: "",
    logo: "",
    permit: "",
    bumpSpot: 128,
    raceEventId: "670d34d5-134b-4408-91bd-691f8c4b62d2",
    categoryId: "",
    configurationId: "",
    category: null,
    configuration: null,
    raceEvent: null,
    ladder: null,
    entryList: [],
    rounds: [],
});

// UseEffect 1, fetch dropdown items on load
useEffect(() => {
    console.log("Use effect 1");
    let c: DropdownItemProps[] = [];
    categoryStore.loadCategories().then(() => {
        categoryStore.categories.forEach((x) =>
            c.push({
                key: x.id,
                value: x.id,
                text: x.name,
            })
        );
        setCategories(c);
    });
}, [categoryStore]);

// UseEffect 2, fetch more items
useEffect(() => {
    console.log("Use effect 2");
    console.log(`ID: ${category.categoryId}`);
}, [category.categoryId]);

From my understanding, when the category.categoryId changes value, it should cause the UseEffect to print out the information. But this isn't happening.

<SelectInput
name='categoryId'
placeholder='Category'
label='Category'
options={categories}
search
/>

Select Input

import { useField } from "formik";
import { DropdownItemProps, Form, Label, Select } from "semantic-ui-react";

interface Props {
    placeholder: string;
    name: string;
    type?: string;
    label?: string;
    options: DropdownItemProps[];
    search: boolean;
}

export default function SelectInput(props: Props) {
    const [field, meta, helpers] = useField(props.name);
    return (
        <Form.Field error={meta.touched && !!meta.error}>
            {props.label}
            <Select
                clearable
                options={props.options}
                value={field.value || null}
                onChange={(event, data) => helpers.setValue(data.value)}
                onBlur={() => helpers.setTouched(true)}
                placeholder={props.placeholder}
                search={props.search}
            />
            {meta.touched && meta.error ? (

                    {meta.error}

            ) : null}
        </Form.Field>
    );
}

Any help would great,
Thanks.


问:
How can i write an Python sqlalchemy ORM query for the following scenario where a column has comma seperated values?I have tried the below method
i have two tables movies and masters

movies :--

id
cast

1
3,4

2
4,5,6

masters :--

master_id
name

3
Allu arjun

4
Ram charan

5
Jr ntr

6
Rajamouli

my query is :---

```<code>db.session.query(Movie.id, Master.name).filter(Movie.cast==Master.id).all()

</code>```

The result I am getting is :--

movie.id
master.name

1
Allu arjun

2
Ram charan

But the output I am trying to get is :--

movie.id
master.name

1
Allu arjun, Ram charan

2
Ram charan, Jr ntr, Rajamouli

Body:
i have two tables movies and masters

movies :--

id
cast

1
3,4

2
4,5,6

masters :--

master_id
name

3
Allu arjun

4
Ram charan

5
Jr ntr

6
Rajamouli

my query is :---

db.session.query(Movie.id, Master.name).filter(Movie.cast==Master.id).all()

The result I am getting is :--

movie.id
master.name

1
Allu arjun

2
Ram charan

But the output I am trying to get is :--

movie.id
master.name

1
Allu arjun, Ram charan

2
Ram charan, Jr ntr, Rajamouli


问:
Exposing a property setter/getter to dataclass repr/init
With the introduction of python dataclasses you can declare your fields on the class and they will show up on the __init__ by default and you can customize it with field().

Is there a clean way to add a property setter to the list of things that will show up in __init__? And the getter to the list of things that show up in __repr__?

```<code>@dataclass
class Foo:
    _a: int = field(init=False, repr=False)

    @property
    def a(self):
        return self._a

    @a.setter
    def a(self, value):
        self._a = value
</code>```

Body:
With the introduction of python dataclasses you can declare your fields on the class and they will show up on the __init__ by default and you can customize it with field().

Is there a clean way to add a property setter to the list of things that will show up in __init__? And the getter to the list of things that show up in __repr__?

@dataclass
class Foo:
    _a: int = field(init=False, repr=False)

    @property
    def a(self):
        return self._a

    @a.setter
    def a(self, value):
        self._a = value


问:
Django: LoginView redirects me to accounts/profile instead of the previous page
My page has a navigation bar that is visible on all pages. There is a "Sign In/Sign Up" button. After signing in I would like to redirect the user to the previous page.

Example:

I'm currently looking to buy vinyl at http://127.0.0.1:8000/vinyls/. I press "Sign In" and I type my credentials. After clicking the Submit button, I would like to get back to /vinyls/. The same goes for /record_labels/, /events/ etc.

I tried using <input type="hidden" name="next" value="{{ next }}"> in my sign-in template but I get redirected to /accounts/profile. Then I tried using Sign Up/Sign In but I'm redirected to /accounts/profile.

This is my SignInView:

class SignInView(auth_views.LoginView):
    template_name = 'sign-in.html'
```
<p>This is my sign-in.html:</p>
<pre class="lang-html prettyprint-override"><code><h1>Sign in</h1>
<form method="post" action="{% url 'sign in' %}">
    {{ form.as_p }}
    <input type="hidden" name="next" value="{{ next }}">
    <p>
        <button type="submit">Sign in</button>
        {% csrf_token %}
    </p>
    <p>Not a member? Sign up now</p>
</form>
</code>```

Body:
My page has a navigation bar that is visible on all pages. There is a "Sign In/Sign Up" button. After signing in I would like to redirect the user to the previous page.

Example:

I'm currently looking to buy vinyl at http://127.0.0.1:8000/vinyls/. I press "Sign In" and I type my credentials. After clicking the Submit button, I would like to get back to /vinyls/. The same goes for /record_labels/, /events/ etc.

I tried using <input type="hidden" name="next" value="{{ next }}"> in my sign-in template but I get redirected to /accounts/profile. Then I tried using Sign Up/Sign In but I'm redirected to /accounts/profile.

This is my SignInView:

class SignInView(auth_views.LoginView):
    template_name = 'sign-in.html'

This is my sign-in.html:

Sign in

<form method="post" action="{% url 'sign in' %}">
    {{ form.as_p }}
    <input type="hidden" name="next" value="{{ next }}">

        <button type="submit">Sign in</button>
        {% csrf_token %}

Not a member? Sign up now

</form>


问:
Assembly Unrecognised Emulation Mode 32
I tried to compile Assembly code:

```<code>; [Assembly Tests].exe
;
; Tests
; Author: Simpfey

global _start

section .text:

_start:
    mov eax, 0x4
    mov ebx, 1
    mov ecx, message
    mov edx, message_length
    int 0x80

    mov eax, 0x1
    mov ebx, 0
    int 0x80

section .data:
    message: db "Hello World!", 0xA
    message_length equ $-message
</code>```

using nasm and ld
command
ld -m32 -o ./build/Assembly.exe ./build/Assembly.o

gives me an error saying:
unrecognised emulation mode: 32

To specify more about my Os:
Windows 10 x64 Proffesional

Title: Assembly Unrecognised Emulation Mode 32

Body:
I tried to compile Assembly code:

; [Assembly Tests].exe
;
; Tests
; Author: Simpfey

global _start

section .text:

_start:
    mov eax, 0x4
    mov ebx, 1
    mov ecx, message
    mov edx, message_length
    int 0x80

    mov eax, 0x1
    mov ebx, 0
    int 0x80

section .data:
    message: db "Hello World!", 0xA
    message_length equ $-message

using nasm and ld
command
ld -m32 -o ./build/Assembly.exe ./build/Assembly.o

gives me an error saying:
unrecognised emulation mode: 32

To specify more about my Os:
Windows 10 x64 Proffesional