问:
Warning when making mutiple api requests inside getStaticProps
I need to make three API requests inside getStaticProps, but I am getting this warning:

Warning: data for page "/" is 154 kB which exceeds the threshold of 128 kB, this amount of data can reduce performance.

code

export const getStaticProps = async () => {
  const topAnime = await api.get("/top/anime?filter=airing&limit=5");
  const currentSeasonAnimes = await api.get("/seasons/now?limit=5");
  const recomendations = await api.get("/recommendations/anime");

  return {
    props: {
      topAnime: topAnime.data.data,
      currentSeasonAnimes: currentSeasonAnimes.data.data,
      recomendations: recomendations.data.data,
    },
  };
};
```

How can I make the warning go away?

Body:
I need to make three API requests inside getStaticProps, but I am getting this warning:

Warning: data for page "/" is 154 kB which exceeds the threshold of 128 kB, this amount of data can reduce performance.

code

export const getStaticProps = async () => {
  const topAnime = await api.get("/top/anime?filter=airing&limit=5");
  const currentSeasonAnimes = await api.get("/seasons/now?limit=5");
  const recomendations = await api.get("/recommendations/anime");

  return {
    props: {
      topAnime: topAnime.data.data,
      currentSeasonAnimes: currentSeasonAnimes.data.data,
      recomendations: recomendations.data.data,
    },
  };
};

How can I make the warning go away?


来源: stackexchange

问:
"staggerChildren" from framer motion not working
i have an ul with a bunch of li as children, i wanted to add an staggerChildren to the li elements but the code isnt working at all

```<code>function Aside(props: any) {
    /*==========Categories Variants========= */
    const categorieContaiener = {
        hidden: { opacity: 0, y: "100vh" },
        show: {
            opacity: 1,
            y: 0,
            transition: {
                when: "beforeChildren",
                delay: 1,
                staggerChildren: 1,
            },
        },
    };
    const categorieItem = {
        hidden: { opacity: 0, x: "100vw" },
        show: {
            opacity: 1,
            x: 0,
            transition: {
                duration: 3,
            },
        },
    };
    return (
        <div
            className="aside bottom-0 sticky w-full h-[15%] md:w-[15%] md:h-full
        bg-gradient-to-r from-[rgba(0,0,0,1)] to-transparent md:fixed text-white "
        >
            <div className="top w-full flex justify-center mt-5">
                <div className="logo w-[130px] md:w-[160px] h-[60px]">
                    <img className="w-full h-full object-cover " src={logo} alt="" />
                </div>
            </div>
            <div className="body text-white flex flex-col justify-between">
                <motion.ul
                    className="w-full bg-blue-500"
                    variants={categorieContaiener}
                    initial="hidden"
                    animate="show"
                >
                    {props.categories.map((categorie: string, index: number) => {
                        return (
                            <motion.li
                                key={index}
                                variants={categorieItem}
                                className="bg-red-500 m-1"
                            >
                                <Categorie
                                    categorie={categorie}
                                    categorieId={index}
                                    setGifNameF={props.setGifNameF}
                                />
                            </motion.li>
                        );
                    })}
                </motion.ul>
            </div>
        </div>
    );
}
</code>```

its weird because i alredy use this effect on other page, now im using almost the exact same code but it isnt working out :/

ContentLicense: CC BY-SA 4.0

Body:
i have an ul with a bunch of li as children, i wanted to add an staggerChildren to the li elements but the code isnt working at all

function Aside(props: any) {
    /*==========Categories Variants========= */
    const categorieContaiener = {
        hidden: { opacity: 0, y: "100vh" },
        show: {
            opacity: 1,
            y: 0,
            transition: {
                when: "beforeChildren",
                delay: 1,
                staggerChildren: 1,
            },
        },
    };
    const categorieItem = {
        hidden: { opacity: 0, x: "100vw" },
        show: {
            opacity: 1,
            x: 0,
            transition: {
                duration: 3,
            },
        },
    };
    return (

                <motion.ul
                    className="w-full bg-blue-500"
                    variants={categorieContaiener}
                    initial="hidden"
                    animate="show"
                >
                    {props.categories.map((categorie: string, index: number) => {
                        return (
                            <motion.li
                                key={index}
                                variants={categorieItem}
                                className="bg-red-500 m-1"
                            >
                                <Categorie
                                    categorie={categorie}
                                    categorieId={index}
                                    setGifNameF={props.setGifNameF}
                                />
                            </motion.li>
                        );
                    })}
                </motion.ul>

    );
}

its weird because i alredy use this effect on other page, now im using almost the exact same code but it isnt working out :/


问:
gradle using plugin id(kotlin-kapt) vs kotlin(kapt)
My project uses the following sintax for kapt

```<code>plugins {
    id("com.android.application")
    id("kotlin-android")
    id("kotlin-kapt")
    ...
}
</code>```

but recently I've seen documentation using

```<code>plugins {
    id("com.android.application")
    id("kotlin-android")
    kotlin("kapt")
    ...
}
</code>```

Is it the same? is it something that requires recent versions of gradle? (from which one)

Body:
My project uses the following sintax for kapt

plugins {
    id("com.android.application")
    id("kotlin-android")
    id("kotlin-kapt")
    ...
}

but recently I've seen documentation using

plugins {
    id("com.android.application")
    id("kotlin-android")
    kotlin("kapt")
    ...
}

Is it the same? is it something that requires recent versions of gradle? (from which one)


问:
Update one parameters of many of objects - the best way
I have a situation to deliver solution for functionality of update one property of many objects. The point is that is possible to update any property. For example

```<code>class Book {
   private String name;
   private Long number;
   private LocalDate date;
   private SomeEnum name;
   private boolean someFlag;
}
</code>```

Possible is to update only one field at a time, but each field is available to update.
Of course I can create new filter class with each field and send it with given parameter I'd like to update, but I thinking about more elegant solution. More generic.

I have to List get objects by ids from database, update and save all with updated field.

What do You think this could be done. Is possible to create filter class with one generic field depend on what variable user give to update? What is the best practice to do something like that ? What is you experience ?

Body:
I have a situation to deliver solution for functionality of update one property of many objects. The point is that is possible to update any property. For example

class Book {
   private String name;
   private Long number;
   private LocalDate date;
   private SomeEnum name;
   private boolean someFlag;
}

Possible is to update only one field at a time, but each field is available to update.
Of course I can create new filter class with each field and send it with given parameter I'd like to update, but I thinking about more elegant solution. More generic.

I have to List get objects by ids from database, update and save all with updated field.

What do You think this could be done. Is possible to create filter class with one generic field depend on what variable user give to update? What is the best practice to do something like that ? What is you experience ?


问:
How should I implement CSRF tokens in form submitting POST requests, rendered in React
I'm using React to build a component which renders a form.

Once the submit button is clicked, this kicks off a POST request using fetch to the backend (Django) which will include the text in the form.

```<code>// The 'Newpost' component
class Newpost extends React.Component {
    constructor(props) {
        super(props);
        this.state = {date: new Date()};
        this.handleClick = this.handleClick.bind(this);
    }

    // Execute this when button is clicked
    handleClick() {
        const request = new Request(
        'https://apjackson20-code50-112112529-76x5j94r47x2pgxr-8000.preview.app.github.dev/',
        {headers: {'X-CSRFToken': csrftoken}}
    );
    fetch(request, {
        method: 'POST',
        mode: 'same-origin'  // Do not send CSRF token to another domain.
    }).then(function(response) {
        // ...
    });
}

    // This is the HTML to be rendered on the page
    render() {
        return (
            <React.Fragment>
                <p class="h3 m-3">All Posts</p>
                <div class="container p-3 border">
                    <p class="h4 mt-1">New Post</p>
                        <div class="input-group">
                            <form method="post" id="newpost" class="container p-0" >
                                <textarea class="form-control" aria-label="With textarea"></textarea>
                            </form>
                        </div>
                    <button type="submit" form="newpost" onClick={this.handleClick} type="button" id="newpostsubmit" class="btn btn-primary mt-2">Post</button>
                </div>
            </React.Fragment>
            );
        }
    }

ReactDOM.render(<Newpost />, document.querySelector("#newpost"))
</code>```

The problem is every time the form submits, I get back the following error:

```<code>Forbidden (Origin checking failed - https://apjackson20-code50-112112529-76x5j94r47x2pgxr-8000.preview.app.github.dev does not match any trusted origins.): /
</code>```

Normally I would place the {% csrf_token %} in the form but since React is rendering the form I don't think that's an option here.

I've seen different solutions to this across the web and have tried each one of them and went with the one where you include a JavaScript function to get the CSRF Token cookie value and then plug it into the fetch request.

```<code>function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var csrftoken = getCookie('csrftoken')
</code>```

But none of them seem to work (or I might be applying them incorrectly).

Body:
I'm using React to build a component which renders a form.

Once the submit button is clicked, this kicks off a POST request using fetch to the backend (Django) which will include the text in the form.

// The 'Newpost' component
class Newpost extends React.Component {
    constructor(props) {
        super(props);
        this.state = {date: new Date()};
        this.handleClick = this.handleClick.bind(this);
    }

    // Execute this when button is clicked
    handleClick() {
        const request = new Request(
        'https://apjackson20-code50-112112529-76x5j94r47x2pgxr-8000.preview.app.github.dev/',
        {headers: {'X-CSRFToken': csrftoken}}
    );
    fetch(request, {
        method: 'POST',
        mode: 'same-origin'  // Do not send CSRF token to another domain.
    }).then(function(response) {
        // ...
    });
}

    // This is the HTML to be rendered on the page
    render() {
        return (
            <React.Fragment>

All Posts

New Post

                            <form method="post" id="newpost" class="container p-0" >
                                <textarea class="form-control" aria-label="With textarea"></textarea>
                            </form>

                    <button type="submit" form="newpost" onClick={this.handleClick} type="button" id="newpostsubmit" class="btn btn-primary mt-2">Post</button>

            </React.Fragment>
            );
        }
    }

ReactDOM.render(<Newpost />, document.querySelector("#newpost"))

The problem is every time the form submits, I get back the following error:

Forbidden (Origin checking failed - https://apjackson20-code50-112112529-76x5j94r47x2pgxr-8000.preview.app.github.dev does not match any trusted origins.): /

Normally I would place the {% csrf_token %} in the form but since React is rendering the form I don't think that's an option here.

I've seen different solutions to this across the web and have tried each one of them and went with the one where you include a JavaScript function to get the CSRF Token cookie value and then plug it into the fetch request.

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var csrftoken = getCookie('csrftoken')

But none of them seem to work (or I might be applying them incorrectly).


问:
Google Travel API requires account_id
I want to fetch hotel datas from Google so i wanted use Google Travel API.But the endpoints in the api doc requires a account_id.

There is no guide to where does this required "account_id" comes from and since i don't know how to get it i am stuck.

Google Travel API DOC

The Request i want to make

The account_id might be reffering to a business account that is owned by establishment.

Title: Google Travel API requires account_id


问:
NextJS Server-only Render to Reduce Client Bundle Size
TLDR: Is there a way to signal to NextJS to render a component only on the server (and thus only show the pre-rendered HTML on the client)?

Motivation:
The reason I want to do this is because the render function inside of the component in question runs a lot of (synchronous) Javascript. I'd like for this Javascript to not be included in the client bundle. My desired behavior is that this component is rendered once on the server and the generated HTML is simply displayed on the client; it should never render on the client.

Things that I've tried / don't work:

getServerSideProps
It appears that, even when a page has getServerSideProps, it will still send the Javascript code to the client. My assumption is that this occurs because NextJS (incorrectly) assumes that some state update could possibly occur in the component on the client and therefore the client must have access to the Javascript code to render the component in such an event. Perhaps I'm doing something wrong here?

Static rendering
The page uses dynamic from the URL (imagine something like the delivery status page of a delivery website; there are hundreds of thousands of different deliveries and so it doesn't make sense for them all to be statically rendered)

Conditional Rendering based on typeof window
I don't think this helps with my particular issue as I'd like to skip rendering entirely on the client but still show the component as it was rendered on the server

Thanks so much for any and all help!


问:
Remove mouseview.js aperture with jsPsych
I don't really have any experience with JS.

That being said, I am working on an experiment where I am using jsPsych and MouseView.js to build the experiment.

I am using MouseView.js's demo and am wondering how I'd remove the aperture that it adds at the end of the trial. Their demo does not appear to do that.

Anyone with experience with either of these tools or with JS more generally have an idea about how I'd do this?

The code that I am using is here in this demo:
https://github.com/u01ai11/MouseView.js/tree/master/examples/jspsych


问:
Under row selection column, the select all checkbox in the header shows incorrect status while using react table v8
Below, I am sharing the code that I have written so far for row selection:

import {
  ApolloError,
  LazyQueryExecFunction,
  OperationVariables,
} from '@apollo/client';
import { CategoryList, Category } from '../common/lib/generated-types';
import {
  ColumnDef,
  flexRender,
  getCoreRowModel,
  useReactTable,
} from '@tanstack/react-table';
import classNames from 'classnames';
import { HTMLProps, useEffect, useRef, useState } from 'react';

export interface CategoriesProps {
  loading: boolean;
  error?: ApolloError;
  categories?: CategoryList;
  fetchCategories: LazyQueryExecFunction<
    {
      categories: CategoryList;
    },
    OperationVariables
  >;
  storeId: string;
}

const defaultColumns: ColumnDef<Category>[] = [
  {
    id: 'select',
    header: ({ table }) => (
      <IndeterminateCheckbox
        {...{
          checked: table.getIsAllRowsSelected(),
          indeterminate: table.getIsSomeRowsSelected(),
          onChange: table.getToggleAllRowsSelectedHandler(),
        }}
      />
    ),
    cell: ({ row }) => (
      <IndeterminateCheckbox
        {...{
          checked: row.getIsSelected(),
          indeterminate: row.getIsSomeSelected(),
          onChange: row.getToggleSelectedHandler(),
        }}
      />
    ),
  },
  {
    accessorKey: 'name',
    cell: info => info.getValue(),
    header: 'Category Name',
  },
  {
    accessorKey: 'slug',
    cell: info => info.getValue(),
    header: 'Slug',
  },
  {
    accessorKey: 'assignmentMethod',
    cell: info => info.getValue(),
    header: 'Assignment',
  },
  {
    accessorKey: 'isPrivate',
    cell: info => (info.getValue() ? 'Private' : 'Public'),
    header: 'Visibility',
  },
];

function IndeterminateCheckbox({
  indeterminate,
  className = '',
  ...rest
}: { indeterminate?: boolean } & HTMLProps<HTMLInputElement>) {
  const ref = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (typeof indeterminate === 'boolean' && ref.current) {
      ref.current.indeterminate = !rest.checked && indeterminate;
    }
  }, [ref, indeterminate, rest.checked]);

  return (
    <input
      type="checkbox"
      ref={ref}
      className={className + ' cursor-pointer'}
      {...rest}
    />
  );
}

export function Categories(props: CategoriesProps) {
  const { error, loading, categories, fetchCategories, storeId } = props;
  const [pagination, setPagination] = useState({
    pageIndex: 0,
    pageSize: 10,
  });
  const [sort, setSort] = useState({ name: 'ASC' });
  const [rowSelection, setRowSelection] = useState({});
  const pageCount = Math.ceil(
    (categories?.totalItems ?? 0) / pagination.pageSize,
  );

  const categoriesTable = useReactTable({
    data: categories?.items || [],
    columns: defaultColumns,
    columnResizeMode: 'onChange',
    pageCount,
    onRowSelectionChange: setRowSelection,
    getRowId: row => row.id.toString(),
    getCoreRowModel: getCoreRowModel(),
    state: {
      pagination,
      rowSelection,
    },
    onPaginationChange: setPagination,
    manualPagination: true,
  });

  useEffect(() => {
    fetchCategories({
      variables: {
        options: {
          take: pagination.pageSize,
          skip: pagination.pageIndex * pagination.pageSize,
          filter: { storeId: { eq: storeId } },
          sort,
        },
      },
    });
  }, [
    fetchCategories,
    pagination.pageIndex,
    pagination.pageSize,
    sort,
    storeId,
  ]);

  if (error) {
    return (

Error!

    );
  }

  return (

            {categoriesTable.getHeaderGroups().map(headerGroup => (

                {headerGroup.headers.map(header => (

                    {header.isPlaceholder
                      ? null
                      : flexRender(
                          header.column.columnDef.header,
                          header.getContext(),
                        )}
                    <div
                      {...{
                        onMouseDown: header.getResizeHandler(),
                        onTouchStart: header.getResizeHandler(),
                        className: classNames(
                          'absolute right-0 top-0 w-[5px] h-full bg-gray-200 cursor-col-resize user-select-none touch-action-none opacity-0 transition-opacity duration-200 group-hover:opacity-100',
                          {
                            'bg-blue-400 opacity-100':
                              header.column.getIsResizing(),
                          },
                        ),
                      }}
                    />

                ))}

            ))}

          {loading ? (

                Loading...

          ) : (

              {categoriesTable.getRowModel().rows.map(row => (

                  {row.getVisibleCells().map(cell => (

                      {flexRender(
                        cell.column.columnDef.cell,
                        cell.getContext(),
                      )}

                  ))}

              ))}

          )}

        <button
          className="border rounded p-1"
          onClick={() => categoriesTable.setPageIndex(0)}
          disabled={!categoriesTable.getCanPreviousPage()}
        >
          {'<<'}
        </button>
        <button
          className="border rounded p-1"
          onClick={() => categoriesTable.previousPage()}
          disabled={!categoriesTable.getCanPreviousPage()}
        >
          {'<'}
        </button>
        <button
          className="border rounded p-1"
          onClick={() => categoriesTable.nextPage()}
          disabled={!categoriesTable.getCanNextPage()}
        >
          {'>'}
        </button>
        <button
          className="border rounded p-1"
          onClick={() =>
            categoriesTable.setPageIndex(categoriesTable.getPageCount() - 1)
          }
          disabled={!categoriesTable.getCanNextPage()}
        >
          {'>>'}
        </button>

Page

            {categoriesTable.getState().pagination.pageIndex + 1} of{' '}
            {categoriesTable.getPageCount()}

          | Go to page:
          <input
            type="number"
            value={categoriesTable.getState().pagination.pageIndex + 1}
            onChange={e => {
              const page = e.target.value ? Number(e.target.value) - 1 : 0;
              categoriesTable.setPageIndex(page);
            }}
            className="border p-1 rounded w-16"
          />

        <select
          value={categoriesTable.getState().pagination.pageSize}
          onChange={e => {
            categoriesTable.setPageSize(Number(e.target.value));
          }}
        >
          {[10, 20, 30, 40, 50].map(pageSize => (
            <option key={pageSize} value={pageSize}>
              Show {pageSize}
            </option>
          ))}
        </select>

{Object.keys(rowSelection).length} Rows Selected

  );
}

export default Categories;
```

What does the code do?

It fetches the paginated data from the server related to some categories - (Cat1 dataset, Cat2 dataset, Cat3 dataset)

Issue?

Row selection works well with data that resides locally.

But, let's say the paginated data is being fetched from the server, the limit is set to 10 per page and you have selected 7 rows from the 1st page. Now, go to page 2 and select 3 rows from the second page once the data is fetched. The Select All checkbox is unticked on page two whereas it should show indeterminate.

I believe this happens because row selection is only aware of 10 items per page. Although it has a memory of selected rows, it's not aware of out of how many items those rows were selected.

One of the approaches could be to save retrieved data in a state and pass it to useReactTable. But, the apollo client already handles caching for me. So, I do not have to save anything to state as clicking on next/previous provides a similar experience. Are there any other approaches where I can continue using apollo client's caching feature and still get the correct status of the Select All Checkbox?

I have created a code sandbox to reproduce the issue:

https://codesandbox.io/s/pedantic-austin-uqt9ry?file=/src/table.tsx

Body:
Below, I am sharing the code that I have written so far for row selection:

import {
  ApolloError,
  LazyQueryExecFunction,
  OperationVariables,
} from '@apollo/client';
import { CategoryList, Category } from '../common/lib/generated-types';
import {
  ColumnDef,
  flexRender,
  getCoreRowModel,
  useReactTable,
} from '@tanstack/react-table';
import classNames from 'classnames';
import { HTMLProps, useEffect, useRef, useState } from 'react';

export interface CategoriesProps {
  loading: boolean;
  error?: ApolloError;
  categories?: CategoryList;
  fetchCategories: LazyQueryExecFunction<
    {
      categories: CategoryList;
    },
    OperationVariables
  >;
  storeId: string;
}

const defaultColumns: ColumnDef<Category>[] = [
  {
    id: 'select',
    header: ({ table }) => (
      <IndeterminateCheckbox
        {...{
          checked: table.getIsAllRowsSelected(),
          indeterminate: table.getIsSomeRowsSelected(),
          onChange: table.getToggleAllRowsSelectedHandler(),
        }}
      />
    ),
    cell: ({ row }) => (
      <IndeterminateCheckbox
        {...{
          checked: row.getIsSelected(),
          indeterminate: row.getIsSomeSelected(),
          onChange: row.getToggleSelectedHandler(),
        }}
      />
    ),
  },
  {
    accessorKey: 'name',
    cell: info => info.getValue(),
    header: 'Category Name',
  },
  {
    accessorKey: 'slug',
    cell: info => info.getValue(),
    header: 'Slug',
  },
  {
    accessorKey: 'assignmentMethod',
    cell: info => info.getValue(),
    header: 'Assignment',
  },
  {
    accessorKey: 'isPrivate',
    cell: info => (info.getValue() ? 'Private' : 'Public'),
    header: 'Visibility',
  },
];

function IndeterminateCheckbox({
  indeterminate,
  className = '',
  ...rest
}: { indeterminate?: boolean } & HTMLProps<HTMLInputElement>) {
  const ref = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (typeof indeterminate === 'boolean' && ref.current) {
      ref.current.indeterminate = !rest.checked && indeterminate;
    }
  }, [ref, indeterminate, rest.checked]);

  return (
    <input
      type="checkbox"
      ref={ref}
      className={className + ' cursor-pointer'}
      {...rest}
    />
  );
}

export function Categories(props: CategoriesProps) {
  const { error, loading, categories, fetchCategories, storeId } = props;
  const [pagination, setPagination] = useState({
    pageIndex: 0,
    pageSize: 10,
  });
  const [sort, setSort] = useState({ name: 'ASC' });
  const [rowSelection, setRowSelection] = useState({});
  const pageCount = Math.ceil(
    (categories?.totalItems ?? 0) / pagination.pageSize,
  );

  const categoriesTable = useReactTable({
    data: categories?.items || [],
    columns: defaultColumns,
    columnResizeMode: 'onChange',
    pageCount,
    onRowSelectionChange: setRowSelection,
    getRowId: row => row.id.toString(),
    getCoreRowModel: getCoreRowModel(),
    state: {
      pagination,
      rowSelection,
    },
    onPaginationChange: setPagination,
    manualPagination: true,
  });

  useEffect(() => {
    fetchCategories({
      variables: {
        options: {
          take: pagination.pageSize,
          skip: pagination.pageIndex * pagination.pageSize,
          filter: { storeId: { eq: storeId } },
          sort,
        },
      },
    });
  }, [
    fetchCategories,
    pagination.pageIndex,
    pagination.pageSize,
    sort,
    storeId,
  ]);

  if (error) {
    return (

Error!

    );
  }

  return (

            {categoriesTable.getHeaderGroups().map(headerGroup => (

                {headerGroup.headers.map(header => (

                    {header.isPlaceholder
                      ? null
                      : flexRender(
                          header.column.columnDef.header,
                          header.getContext(),
                        )}
                    <div
                      {...{
                        onMouseDown: header.getResizeHandler(),
                        onTouchStart: header.getResizeHandler(),
                        className: classNames(
                          'absolute right-0 top-0 w-[5px] h-full bg-gray-200 cursor-col-resize user-select-none touch-action-none opacity-0 transition-opacity duration-200 group-hover:opacity-100',
                          {
                            'bg-blue-400 opacity-100':
                              header.column.getIsResizing(),
                          },
                        ),
                      }}
                    />

                ))}

            ))}

          {loading ? (

                Loading...

          ) : (

              {categoriesTable.getRowModel().rows.map(row => (

                  {row.getVisibleCells().map(cell => (

                      {flexRender(
                        cell.column.columnDef.cell,
                        cell.getContext(),
                      )}

                  ))}

              ))}

          )}

        <button
          className="border rounded p-1"
          onClick={() => categoriesTable.setPageIndex(0)}
          disabled={!categoriesTable.getCanPreviousPage()}
        >
          {'<<'}
        </button>
        <button
          className="border rounded p-1"
          onClick={() => categoriesTable.previousPage()}
          disabled={!categoriesTable.getCanPreviousPage()}
        >
          {'<'}
        </button>
        <button
          className="border rounded p-1"
          onClick={() => categoriesTable.nextPage()}
          disabled={!categoriesTable.getCanNextPage()}
        >
          {'>'}
        </button>
        <button
          className="border rounded p-1"
          onClick={() =>
            categoriesTable.setPageIndex(categoriesTable.getPageCount() - 1)
          }
          disabled={!categoriesTable.getCanNextPage()}
        >
          {'>>'}
        </button>

Page

            {categoriesTable.getState().pagination.pageIndex + 1} of{' '}
            {categoriesTable.getPageCount()}

          | Go to page:
          <input
            type="number"
            value={categoriesTable.getState().pagination.pageIndex + 1}
            onChange={e => {
              const page = e.target.value ? Number(e.target.value) - 1 : 0;
              categoriesTable.setPageIndex(page);
            }}
            className="border p-1 rounded w-16"
          />

        <select
          value={categoriesTable.getState().pagination.pageSize}
          onChange={e => {
            categoriesTable.setPageSize(Number(e.target.value));
          }}
        >
          {[10, 20, 30, 40, 50].map(pageSize => (
            <option key={pageSize} value={pageSize}>
              Show {pageSize}
            </option>
          ))}
        </select>

{Object.keys(rowSelection).length} Rows Selected

  );
}

export default Categories;

What does the code do?

It fetches the paginated data from the server related to some categories - (Cat1 dataset, Cat2 dataset, Cat3 dataset)

Issue?

Row selection works well with data that resides locally.

But, let's say the paginated data is being fetched from the server, the limit is set to 10 per page and you have selected 7 rows from the 1st page. Now, go to page 2 and select 3 rows from the second page once the data is fetched. The Select All checkbox is unticked on page two whereas it should show indeterminate.

I believe this happens because row selection is only aware of 10 items per page. Although it has a memory of selected rows, it's not aware of out of how many items those rows were selected.

One of the approaches could be to save retrieved data in a state and pass it to useReactTable. But, the apollo client already handles caching for me. So, I do not have to save anything to state as clicking on next/previous provides a similar experience. Are there any other approaches where I can continue using apollo client's caching feature and still get the correct status of the Select All Checkbox?

I have created a code sandbox to reproduce the issue:

https://codesandbox.io/s/pedantic-austin-uqt9ry?file=/src/table.tsx


问:
how to speed up scene._render_pygame_def_update() in python
im trying to make a 3d renderer but i can only get at most 20fps on idle.
i tried using @functools.lru_cache(maxsize=None) on project_and_rotate() and got it up to 40fps on idle.
is there any way i could make this any faster
im using a long math formula i found a few month ago but it seems to be to slow for the map in projected_des</p>
```<code>from math import *
import pygame
import numpy
from functools import lru_cache

@lru_cache(maxsize=None)
def project_and_rotate(x, y, z,rotx,roty,rotz,posx,posy,posz,cx,cy,cz,scale,render_distance):
            x,y,z=x-posx,y-posy,z-posz
            if abs(x)>render_distance or abs(z)>render_distance:return None

            px = (((x * cos(rotz) - sin(rotz) * y) * cos(roty) - z * sin(roty)) * (315 / ((((z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * cos(rotx) + (y * cos(rotz) + x * sin(rotz)) * sin(rotx)) + 5) + cz))) * scale + cx
            py = (((y * cos(rotz) + x * sin(rotz)) * cos(rotx) - (z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * sin(rotx)) * (315 / ((((z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * cos(rotx) + (y * cos(rotz) + x * sin(rotz)) * sin(rotx)) + 5) + cz))) * scale + cy

            return [round(px),round(py)]

class coordinate:
    def __init__(self,x,y,z):
        self.x=x
        self.y=y
        self.z=z

class verticies_structure:
    def __init__(self):
        self._verts=[]
    def add_vert(self,x,y,z):
        self._verts.append(coordinate(x,y,z))
    def get_coords(self,indexes):
        return self._verts[indexes[0]:indexes[1]]

class camera:
    def __init__(self,w,h,render_distance,fov=45):
        self.fov=360-fov
        self.w=w
        self.h=h
        self.x=0
        self.rx=0
        self.cx=0
        self.y=0
        self.ry=0
        self.cy=0
        self.z=0
        self.rz=0
        self.cz=0
        self.render_distance=render_distance

def false(f,value):
    if value==f:
        value=f+0.01
    return value

def inf360(value):
    if value>359:value=0
    if value<0:value=359
    return value

class mesh(object):
    def __init__(self,file_obj,cam):
        self.cam=cam
        self.verts=verticies_structure()
        self.source=file_obj
        self.read_object_file()

        self.verts=verticies_structure()

        size=100
        for x in range(size):
            for z in range(size):
                self.verts.add_vert(x-size//2,0,z-size//2)

        self.w2s_vect=numpy.vectorize(self.w2s)
        self.array_verts=numpy.array(self.verts._verts)

    def w2s(self,coord):
        cam=self.cam
        return project_and_rotate(coord.x,coord.y,coord.z,cam.ry,cam.rx,cam.rz,cam.x,cam.y,cam.z,cam.cx,cam.cy,cam.cz,10,cam.render_distance)

    def projected_des(self,cam):
        #return self.w2s_vect(self.array_verts).tolist()

        return map( lambda coord:project_and_rotate(coord.x,coord.y,coord.z,cam.ry,cam.rx,cam.rz,cam.x,cam.y,cam.z,cam.cx,cam.cy,cam.cz,10,cam.render_distance),self.verts.get_coords([0,-1]))

    def read_object_file(self):
        self.verts=verticies_structure()
        import re
        reComp = re.compile("(?<=^)(v |vn |vt |f )(.*)(?=$)", re.MULTILINE)
        with open(self.source) as f:
            data = [txt.group() for txt in reComp.finditer(f.read())]
        v_arr, vn_arr, vt_arr, f_arr = [], [], [], []
        for line in data:
            tokens = line.split(' ')
            if tokens[0] == 'v':
                v_arr.append([float(c) for c in tokens[1:]])
            elif tokens[0] == 'vn':
                vn_arr.append([float(c) for c in tokens[1:]])
            elif tokens[0] == 'vt':
                vn_arr.append([float(c) for c in tokens[1:]])
            elif tokens[0] == 'f':
                f_arr.append([[int(i) if len(i) else 0 for i in c.split('/')] for c in tokens[1:]])
        vertices, normals = [], []
        for face in f_arr:
            for tp in face:
                self.verts.add_vert(*v_arr[tp[0]-1])

        self.array_verts=numpy.array(self.verts._verts)
class draw:
    class frame:
        class pygame_uitl:
            def grid(rowx,rowy,px,color=(255,255,255)):
                display=pygame.display.get_surface()
                for r in range(rowx):
                    r+=1
                    pygame.draw.line(display,color,(0,(display.get_height()/(rowx+1))*r),(display.get_width(),(display.get_height()/(rowx+1))*r),px)
                for r in range(rowy):
                    r+=1
                    pygame.draw.line(display,color,((display.get_width()/(rowy+1))*r,0),((display.get_width()/(rowy+1))*r,display.get_height()),px)

class system:
    class pygame_util:
        def get_orientation():
            inf=pygame.display.Info()
            w,h=inf.current_w,inf.current_h
            if w>h:
                return 1
            else:
                return 0

class Drivers:
    class Pygame:
        DEFAULT="PG-default"
        SDL2="PG-sdl2"

class master:
    class scene:
        def __init__(self,wh:list,display_driver:str,render_distance:int,fps:int):
            self._model={
                "class 1":[],
                "class 2":[],
                "class 3":[],
                "class 4":[]}
            self._fps=fps
            self._window_wh=wh
            self._driver=display_driver
            self._camera=camera(*wh,render_distance)
            self._mode="mesh"
            self._super_ls=0

            if display_driver==Drivers.Pygame.DEFAULT:
                self._render_pygame_def_setup()

        def add_model(self,file):
            model=mesh(file,self._camera)
            vertexes=len(model.verts._verts)
            if vertexes>100:
                self._model["class 4"].append(model)
            elif vertexes>50:
                self._model["class 3"].append(model)
            elif vertexes>25:
                self._model["class 2"].append(model)
            else:
                self._model["class 1"].append(model)
        def regulate_camera(self):
            self._camera.rx,self._camera.ry,self._camera.rz=false(0,self._camera.rx),false(0,self._camera.ry),false(0,self._camera.rz)
            self._camera.cx,self._camera.cy,self._camera.cz=false(0,self._camera.cx),false(0,self._camera.cy),false(0,self._camera.cz)
        def correct_camera(self,orient=1):
            self._orient=orient
            if orient:
                self._camera.cx=self._window_wh[1]//2
                self._camera.cy=self._window_wh[0]
                self._camera.ry=0.4
            else:
                self._camera.cx=self._window_wh[0]//2
                self._camera.cy=self._window_wh[1]
                self._camera.ry=0.2

        def auto_render_distance(self):
            if self._driver==Drivers.Pygame.DEFAULT:
                if self._pygame_clock.get_fps()+5>self._fps:
                    self._camera.render_distance+=1
                else:
                    self._camera.render_distance-=1

        def landscape_super(self):
            self._super_ls=1
            self._lss_hdri_file_jpg_surf=pygame.Surface([self._window_wh[0],self._window_wh[1]//2.01])
            self._lss_hdri_file_jpg_surf.fill((200,220,255))

        def _render_pygame_def_setup(self):
            self._pygame_clock=pygame.time.Clock()
            self._pygame_screen=pygame.display.set_mode((self._camera.w,self._camera.h),pygame.DOUBLEBUF|pygame.HWACCEL|pygame.HWSURFACE)

        def _render_pygame_def_update(self):
                self._pygame_screen.fill((0,70,0))
                self.regulate_camera()

                for idx,vclass in self._model.items():
                    for model in vclass:
                        for point in model.projected_des(self._camera):
                            if point!=None:
                                try:self._pygame_screen.set_at(point,(255,255,255))
                                except:pass

                if self._super_ls:
                    self._pygame_screen.blit(self._lss_hdri_file_jpg_surf,(0,0))

        def _render_pygame_def_finish(self):
                pygame.display.flip()
                self._pygame_clock.tick(self._fps)

scene=master.scene([2176,1080],Drivers.Pygame.DEFAULT,render_distance=25,fps=60)

scene.add_model("cube.obj")
scene.correct_camera(0)
scene.landscape_super()

#make the sky mapped to edge of render
pygame.font.init()
while 1:
    rx,ry=pygame.mouse.get_rel()
    scene._camera.rx+=rx/200

    scene._render_pygame_def_update()

    #scene.auto_render_distance()

    scene._pygame_screen.blit(pygame.font.SysFont(None,60).render(str(scene._pygame_clock.get_fps()),None,(255,0,0)),(0,0))

    scene._render_pygame_def_finish()
</code>```

Body:
im trying to make a 3d renderer but i can only get at most 20fps on idle.
i tried using @functools.lru_cache(maxsize=None) on project_and_rotate() and got it up to 40fps on idle.
is there any way i could make this any faster
im using a long math formula i found a few month ago but it seems to be to slow for the map in projected_des

from math import *
import pygame
import numpy
from functools import lru_cache

@lru_cache(maxsize=None)
def project_and_rotate(x, y, z,rotx,roty,rotz,posx,posy,posz,cx,cy,cz,scale,render_distance):
            x,y,z=x-posx,y-posy,z-posz
            if abs(x)>render_distance or abs(z)>render_distance:return None

            px = (((x * cos(rotz) - sin(rotz) * y) * cos(roty) - z * sin(roty)) * (315 / ((((z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * cos(rotx) + (y * cos(rotz) + x * sin(rotz)) * sin(rotx)) + 5) + cz))) * scale + cx
            py = (((y * cos(rotz) + x * sin(rotz)) * cos(rotx) - (z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * sin(rotx)) * (315 / ((((z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * cos(rotx) + (y * cos(rotz) + x * sin(rotz)) * sin(rotx)) + 5) + cz))) * scale + cy

            return [round(px),round(py)]

class coordinate:
    def __init__(self,x,y,z):
        self.x=x
        self.y=y
        self.z=z

class verticies_structure:
    def __init__(self):
        self._verts=[]
    def add_vert(self,x,y,z):
        self._verts.append(coordinate(x,y,z))
    def get_coords(self,indexes):
        return self._verts[indexes[0]:indexes[1]]

class camera:
    def __init__(self,w,h,render_distance,fov=45):
        self.fov=360-fov
        self.w=w
        self.h=h
        self.x=0
        self.rx=0
        self.cx=0
        self.y=0
        self.ry=0
        self.cy=0
        self.z=0
        self.rz=0
        self.cz=0
        self.render_distance=render_distance

def false(f,value):
    if value==f:
        value=f+0.01
    return value

def inf360(value):
    if value>359:value=0
    if value<0:value=359
    return value

class mesh(object):
    def __init__(self,file_obj,cam):
        self.cam=cam
        self.verts=verticies_structure()
        self.source=file_obj
        self.read_object_file()

        self.verts=verticies_structure()

        size=100
        for x in range(size):
            for z in range(size):
                self.verts.add_vert(x-size//2,0,z-size//2)

        self.w2s_vect=numpy.vectorize(self.w2s)
        self.array_verts=numpy.array(self.verts._verts)

    def w2s(self,coord):
        cam=self.cam
        return project_and_rotate(coord.x,coord.y,coord.z,cam.ry,cam.rx,cam.rz,cam.x,cam.y,cam.z,cam.cx,cam.cy,cam.cz,10,cam.render_distance)

    def projected_des(self,cam):
        #return self.w2s_vect(self.array_verts).tolist()

        return map( lambda coord:project_and_rotate(coord.x,coord.y,coord.z,cam.ry,cam.rx,cam.rz,cam.x,cam.y,cam.z,cam.cx,cam.cy,cam.cz,10,cam.render_distance),self.verts.get_coords([0,-1]))

    def read_object_file(self):
        self.verts=verticies_structure()
        import re
        reComp = re.compile("(?<=^)(v |vn |vt |f )(.*)(?=$)", re.MULTILINE)
        with open(self.source) as f:
            data = [txt.group() for txt in reComp.finditer(f.read())]
        v_arr, vn_arr, vt_arr, f_arr = [], [], [], []
        for line in data:
            tokens = line.split(' ')
            if tokens[0] == 'v':
                v_arr.append([float(c) for c in tokens[1:]])
            elif tokens[0] == 'vn':
                vn_arr.append([float(c) for c in tokens[1:]])
            elif tokens[0] == 'vt':
                vn_arr.append([float(c) for c in tokens[1:]])
            elif tokens[0] == 'f':
                f_arr.append([[int(i) if len(i) else 0 for i in c.split('/')] for c in tokens[1:]])
        vertices, normals = [], []
        for face in f_arr:
            for tp in face:
                self.verts.add_vert(*v_arr[tp[0]-1])

        self.array_verts=numpy.array(self.verts._verts)
class draw:
    class frame:
        class pygame_uitl:
            def grid(rowx,rowy,px,color=(255,255,255)):
                display=pygame.display.get_surface()
                for r in range(rowx):
                    r+=1
                    pygame.draw.line(display,color,(0,(display.get_height()/(rowx+1))*r),(display.get_width(),(display.get_height()/(rowx+1))*r),px)
                for r in range(rowy):
                    r+=1
                    pygame.draw.line(display,color,((display.get_width()/(rowy+1))*r,0),((display.get_width()/(rowy+1))*r,display.get_height()),px)

class system:
    class pygame_util:
        def get_orientation():
            inf=pygame.display.Info()
            w,h=inf.current_w,inf.current_h
            if w>h:
                return 1
            else:
                return 0

class Drivers:
    class Pygame:
        DEFAULT="PG-default"
        SDL2="PG-sdl2"

class master:
    class scene:
        def __init__(self,wh:list,display_driver:str,render_distance:int,fps:int):
            self._model={
                "class 1":[],
                "class 2":[],
                "class 3":[],
                "class 4":[]}
            self._fps=fps
            self._window_wh=wh
            self._driver=display_driver
            self._camera=camera(*wh,render_distance)
            self._mode="mesh"
            self._super_ls=0

            if display_driver==Drivers.Pygame.DEFAULT:
                self._render_pygame_def_setup()

        def add_model(self,file):
            model=mesh(file,self._camera)
            vertexes=len(model.verts._verts)
            if vertexes>100:
                self._model["class 4"].append(model)
            elif vertexes>50:
                self._model["class 3"].append(model)
            elif vertexes>25:
                self._model["class 2"].append(model)
            else:
                self._model["class 1"].append(model)
        def regulate_camera(self):
            self._camera.rx,self._camera.ry,self._camera.rz=false(0,self._camera.rx),false(0,self._camera.ry),false(0,self._camera.rz)
            self._camera.cx,self._camera.cy,self._camera.cz=false(0,self._camera.cx),false(0,self._camera.cy),false(0,self._camera.cz)
        def correct_camera(self,orient=1):
            self._orient=orient
            if orient:
                self._camera.cx=self._window_wh[1]//2
                self._camera.cy=self._window_wh[0]
                self._camera.ry=0.4
            else:
                self._camera.cx=self._window_wh[0]//2
                self._camera.cy=self._window_wh[1]
                self._camera.ry=0.2

        def auto_render_distance(self):
            if self._driver==Drivers.Pygame.DEFAULT:
                if self._pygame_clock.get_fps()+5>self._fps:
                    self._camera.render_distance+=1
                else:
                    self._camera.render_distance-=1

        def landscape_super(self):
            self._super_ls=1
            self._lss_hdri_file_jpg_surf=pygame.Surface([self._window_wh[0],self._window_wh[1]//2.01])
            self._lss_hdri_file_jpg_surf.fill((200,220,255))

        def _render_pygame_def_setup(self):
            self._pygame_clock=pygame.time.Clock()
            self._pygame_screen=pygame.display.set_mode((self._camera.w,self._camera.h),pygame.DOUBLEBUF|pygame.HWACCEL|pygame.HWSURFACE)

        def _render_pygame_def_update(self):
                self._pygame_screen.fill((0,70,0))
                self.regulate_camera()

                for idx,vclass in self._model.items():
                    for model in vclass:
                        for point in model.projected_des(self._camera):
                            if point!=None:
                                try:self._pygame_screen.set_at(point,(255,255,255))
                                except:pass

                if self._super_ls:
                    self._pygame_screen.blit(self._lss_hdri_file_jpg_surf,(0,0))

        def _render_pygame_def_finish(self):
                pygame.display.flip()
                self._pygame_clock.tick(self._fps)

scene=master.scene([2176,1080],Drivers.Pygame.DEFAULT,render_distance=25,fps=60)

scene.add_model("cube.obj")
scene.correct_camera(0)
scene.landscape_super()

#make the sky mapped to edge of render
pygame.font.init()
while 1:
    rx,ry=pygame.mouse.get_rel()
    scene._camera.rx+=rx/200

    scene._render_pygame_def_update()

    #scene.auto_render_distance()

    scene._pygame_screen.blit(pygame.font.SysFont(None,60).render(str(scene._pygame_clock.get_fps()),None,(255,0,0)),(0,0))

    scene._render_pygame_def_finish()


问:
What is the good approach via api to download file
Do you know how via a web page usind the IPB APi allowinfg to doynload a file. Until now I can the see the files but it's not possible to download it. My result myfile:zip.3313213213

Thank you
Below my approach :

```<code>public function getFilesInformations(int $id)
  {
    $curl = curl_init( $this->communityUrl . 'api/downloads/files?id=' . $id . '&download&perPage=300');

    $array = [
      CURLOPT_RETURNTRANSFER    => TRUE,
      CURLOPT_HTTPAUTH  => CURLAUTH_BASIC,
      CURLOPT_USERPWD       => "{$this->apiKey}:",
      CURLOPT_USERAGENT     => "MyUserAgent/1.0"
    ];

    curl_setopt_array( $curl, $array);

    $response = curl_exec( $curl );

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

My other function to get the file info

```<code> public function insertFilesInformations(int $id): bool
  {
      $json_result = $this->getFilesInformations($id);
      $result = json_decode($json_result, true);

      $i = 1;

      if (is_array($result)) {
        foreach ($result as $value) {
          if (is_array($value)) {
            foreach ($value as $file) {
              $download = $file['files'][0]['url'];
              var_dum($download);
            }
          }
        }
      }

      return $download
  }
</code>```

the result is something like that : https://localhost/forum/uploads/monthly_2019_12/myfile_zip.a1fb44a2cb001aa6f3596ec4c6dfba16

Body:
Do you know how via a web page usind the IPB APi allowinfg to doynload a file. Until now I can the see the files but it's not possible to download it. My result myfile:zip.3313213213

Thank you
Below my approach :

public function getFilesInformations(int $id)
  {
    $curl = curl_init( $this->communityUrl . 'api/downloads/files?id=' . $id . '&download&perPage=300');

    $array = [
      CURLOPT_RETURNTRANSFER    => TRUE,
      CURLOPT_HTTPAUTH  => CURLAUTH_BASIC,
      CURLOPT_USERPWD       => "{$this->apiKey}:",
      CURLOPT_USERAGENT     => "MyUserAgent/1.0"
    ];

    curl_setopt_array( $curl, $array);

    $response = curl_exec( $curl );

    return $response;
  }

My other function to get the file info

 public function insertFilesInformations(int $id): bool
  {
      $json_result = $this->getFilesInformations($id);
      $result = json_decode($json_result, true);

      $i = 1;

      if (is_array($result)) {
        foreach ($result as $value) {
          if (is_array($value)) {
            foreach ($value as $file) {
              $download = $file['files'][0]['url'];
              var_dum($download);
            }
          }
        }
      }

      return $download
  }

the result is something like that : https://localhost/forum/uploads/monthly_2019_12/myfile_zip.a1fb44a2cb001aa6f3596ec4c6dfba16


问:
Is there a way to get LibGit2Sharp to work on AlmaLinux 8 in an application built on Windows?
I have an ASP.NET Core application (.net core 2.1) built on Windows that uses LibGit2Sharp (version 0.26.2).

It works fine when running on Windows, but I have not been able to get it to work properly when running on an AlmaLinux 8 server.

I copied the libgit2-106a5f2.so file from the linux-x64 native runtime publish output to the same folder that contains LibGit2Sharp.dll on the AlmaLinux 8 machine.

This is the error I see:

```<code>System.TypeInitializationException: The type initializer for 'LibGit2Sharp.Core.NativeMethods' threw an exception. ---> System.DllNotFoundException: Unable to load shared library 'git2-106a5f2' or one of its dependencies. In order to help diagnose loading problems, consider setting the LD_DEBUG environment variable: libgit2-106a5f2: cannot open shared object file: No such file or directory
   at LibGit2Sharp.Core.NativeMethods.git_libgit2_init()
   at LibGit2Sharp.Core.NativeMethods.InitializeNativeLibrary()
   at LibGit2Sharp.Core.NativeMethods..cctor()
   --- End of inner exception stack trace ---
   at LibGit2Sharp.Core.NativeMethods.git_repository_open_ext(git_repository*& repository, FilePath path, RepositoryOpenFlags flags, FilePath ceilingDirs)
   at LibGit2Sharp.Core.Proxy.git_repository_open_ext(String path, RepositoryOpenFlags flags, String ceilingDirs)
   at LibGit2Sharp.Repository.IsValid(String path)
...
</code>```

Edit:

I set the LD_DEBUG and LD_LIBRARY_PATH variables, and got this output when it tried to load the libgit2 library:

```<code>   1413948:     file=libgit2-106a5f2 [0];  dynamically loaded by /usr/share/dotnet/shared/Microsoft.NETCore.App/2.1.30/libcoreclr.so [0]
   1413948:     find library=libgit2-106a5f2 [0]; searching
   1413948:      search path=/path/to/application/runtimes/linux-x64/native                (LD_LIBRARY_PATH)
   1413948:       trying file=/path/to/application/runtimes/linux-x64/native/libgit2-106a5f2
   1413948:      search cache=/etc/ld.so.cache
   1413948:      search path=/lib64/tls:/lib64:/usr/lib64/tls:/usr/lib64                (system search path)
   1413948:       trying file=/lib64/tls/libgit2-106a5f2
   1413948:       trying file=/lib64/libgit2-106a5f2
   1413948:       trying file=/usr/lib64/tls/libgit2-106a5f2
   1413948:       trying file=/usr/lib64/libgit2-106a5f2
</code>```

This file exists:

/path/to/application/runtimes/linux-x64/native/libgit2-106a5f2.so

But it appears that it is looking for the file without the ".so" extension?

Body:
I have an ASP.NET Core application (.net core 2.1) built on Windows that uses LibGit2Sharp (version 0.26.2).

It works fine when running on Windows, but I have not been able to get it to work properly when running on an AlmaLinux 8 server.

I copied the libgit2-106a5f2.so file from the linux-x64 native runtime publish output to the same folder that contains LibGit2Sharp.dll on the AlmaLinux 8 machine.

This is the error I see:

System.TypeInitializationException: The type initializer for 'LibGit2Sharp.Core.NativeMethods' threw an exception. ---> System.DllNotFoundException: Unable to load shared library 'git2-106a5f2' or one of its dependencies. In order to help diagnose loading problems, consider setting the LD_DEBUG environment variable: libgit2-106a5f2: cannot open shared object file: No such file or directory
   at LibGit2Sharp.Core.NativeMethods.git_libgit2_init()
   at LibGit2Sharp.Core.NativeMethods.InitializeNativeLibrary()
   at LibGit2Sharp.Core.NativeMethods..cctor()
   --- End of inner exception stack trace ---
   at LibGit2Sharp.Core.NativeMethods.git_repository_open_ext(git_repository*& repository, FilePath path, RepositoryOpenFlags flags, FilePath ceilingDirs)
   at LibGit2Sharp.Core.Proxy.git_repository_open_ext(String path, RepositoryOpenFlags flags, String ceilingDirs)
   at LibGit2Sharp.Repository.IsValid(String path)
...

Edit:

I set the LD_DEBUG and LD_LIBRARY_PATH variables, and got this output when it tried to load the libgit2 library:

   1413948:     file=libgit2-106a5f2 [0];  dynamically loaded by /usr/share/dotnet/shared/Microsoft.NETCore.App/2.1.30/libcoreclr.so [0]
   1413948:     find library=libgit2-106a5f2 [0]; searching
   1413948:      search path=/path/to/application/runtimes/linux-x64/native                (LD_LIBRARY_PATH)
   1413948:       trying file=/path/to/application/runtimes/linux-x64/native/libgit2-106a5f2
   1413948:      search cache=/etc/ld.so.cache
   1413948:      search path=/lib64/tls:/lib64:/usr/lib64/tls:/usr/lib64                (system search path)
   1413948:       trying file=/lib64/tls/libgit2-106a5f2
   1413948:       trying file=/lib64/libgit2-106a5f2
   1413948:       trying file=/usr/lib64/tls/libgit2-106a5f2
   1413948:       trying file=/usr/lib64/libgit2-106a5f2

This file exists:

/path/to/application/runtimes/linux-x64/native/libgit2-106a5f2.so

But it appears that it is looking for the file without the ".so" extension?


问:
PyFlink - get "rowtime" after groupby agg using Table API
I converted a datastream using table api and have a time, key and value field

```<code>t = t_env.from_data_stream(
    ds,
    Schema.new_builder()
    .column_by_expression("ts","TO_TIMESTAMP(FROM_UNIXTIME(f0))")
    .column("f1", DataTypes.STRING())
    .column("f2", DataTypes.INT())
    .watermark("ts", "ts - INTERVAL '1' SECONDS")
    .build()
).alias("time","key","value")
</code>```

The row time for "ts" works fine for t, when I do

```<code>t.order_by(col("time").asc)
</code>```

I then tried to agg the value field for each key and also keep the last time field:

```<code>t1 = t.group_by(col("key")).select(col("key"), col("time").max.alias("time"), col("value").sum.alias("value")
</code>```

and do

```<code>t1.order_by(col("time").asc)
</code>```

It always print TableException: org.apache.flink.table.api.TableException: Sort on a non-time-attribute field is not supported.

Thanks a lot!

I checked the type of the "time" field of t1 after group by and it has the same type as the "time" field in t, which is TIMESTAMP(3) ROWTIME, looks like the SQL_TIMESTAMP type.

Body:
I converted a datastream using table api and have a time, key and value field

t = t_env.from_data_stream(
    ds,
    Schema.new_builder()
    .column_by_expression("ts","TO_TIMESTAMP(FROM_UNIXTIME(f0))")
    .column("f1", DataTypes.STRING())
    .column("f2", DataTypes.INT())
    .watermark("ts", "ts - INTERVAL '1' SECONDS")
    .build()
).alias("time","key","value")

The row time for "ts" works fine for t, when I do

t.order_by(col("time").asc)

I then tried to agg the value field for each key and also keep the last time field:

t1 = t.group_by(col("key")).select(col("key"), col("time").max.alias("time"), col("value").sum.alias("value")

and do

t1.order_by(col("time").asc)

It always print TableException: org.apache.flink.table.api.TableException: Sort on a non-time-attribute field is not supported.

Thanks a lot!

I checked the type of the "time" field of t1 after group by and it has the same type as the "time" field in t, which is TIMESTAMP(3) ROWTIME, looks like the SQL_TIMESTAMP type.


问:
Angular Library Import Errors With Multiple Entry Points
I am using Angular Workspaces and creating an additional entry point for AG-Grid inside of the Angular library to reduce the initial main bundle size as the grid isn't needed right away.

My app structure is:

```<code>projects
    my-library
        ag-grid
           grid
           ng-package.json
           public-api.ts
        src
           constants
           services
           lib
             other smaller components (button, input, etc)
           ng-package.json
           public-api.ts
     app1
        src
           features (trying to import my-library/ag-grid here)
tsconfig.json

</code>```

Inside my tsconfig.json file at the project root, I have paths set to the following:

```<code>{
   "paths": {
       "my-library/*": ["dist/my-library/*"],
       "my-library:: [dist/my-library"]
   }
}

</code>```

When I try building the library and the project I keep getting an import error. Here is my build command:

```<code>npm run build:my-library && ng serve app1 --port-4200 --open
</code>```

And my errors inside of app1 component modules/models are basically just a ton of:

```<code>Module not found: Error: Can't resolve 'my-library/ag-grid"
</code>```

I have been referencing this article: https://blog.ag-grid.com/reducing-angular-library-contributions-to-the-main-bundle/

Any thoughts as to why that module isn't found is appreciated.

Body:
I am using Angular Workspaces and creating an additional entry point for AG-Grid inside of the Angular library to reduce the initial main bundle size as the grid isn't needed right away.

My app structure is:

projects
    my-library
        ag-grid
           grid
           ng-package.json
           public-api.ts
        src
           constants
           services
           lib
             other smaller components (button, input, etc)
           ng-package.json
           public-api.ts
     app1
        src
           features (trying to import my-library/ag-grid here)
tsconfig.json

Inside my tsconfig.json file at the project root, I have paths set to the following:

{
   "paths": {
       "my-library/*": ["dist/my-library/*"],
       "my-library:: [dist/my-library"]
   }
}

When I try building the library and the project I keep getting an import error. Here is my build command:

npm run build:my-library && ng serve app1 --port-4200 --open

And my errors inside of app1 component modules/models are basically just a ton of:

Module not found: Error: Can't resolve 'my-library/ag-grid"

I have been referencing this article: https://blog.ag-grid.com/reducing-angular-library-contributions-to-the-main-bundle/

Any thoughts as to why that module isn't found is appreciated.


问:
Adding A Call Back Function To Javascript Classes
I am trying to make a javascript class that will take an html button, and will execute function from the class when the button is clicked, but I am having a hard time figuring out how to do that.

Here is my code.

class BtnThatDoesStuff {
  constructor(selector) {
    this.selector = selector;
    this.addEventListenerToBtn();
  }

  yell() {
    console.log("Clicked");
  }

  addEventListenerToBtn() {
    let btn = document.querySelector(this.selector);
    btn.addEventListener("click", function() {
      yell();
    })
  }

}

new BtnThatDoesStuff(`[rel='button-that-does-stuff']`);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="" rel="button-that-does-stuff">
        <span class="">Click Me</span>
</button></code>```

I was expecting to get log hello world but instead I get yell is not defined.

Body:
I am trying to make a javascript class that will take an html button, and will execute function from the class when the button is clicked, but I am having a hard time figuring out how to do that.

Here is my code.

class BtnThatDoesStuff {
  constructor(selector) {
    this.selector = selector;
    this.addEventListenerToBtn();
  }

  yell() {
    console.log("Clicked");
  }

  addEventListenerToBtn() {
    let btn = document.querySelector(this.selector);
    btn.addEventListener("click", function() {
      yell();
    })
  }

}

new BtnThatDoesStuff(`[rel='button-that-does-stuff']`);

<button class="" rel="button-that-does-stuff">
        Click Me
</button>

I was expecting to get log hello world but instead I get yell is not defined.


问:
Unable to move elements using cursor in IntelliJ's Scene Builder - any fix?
Essentially my issue is the same as the one found at this link, however, this was multiple years ago and no solution was presented: How to relocate or resize items using mouse in Intellij Idea scene builder?

I am using a Windows machine, with fresh installs of IntelliJ, the JavaSDK, and JavaFX.

However, I am unable to move or resize elements using the cursor within the Scene Builder; doing so just results in the cursor turning into a cross, much like in the above question.

I was wondering if anyone had found any solutions since the original question was asked?

Thanks so much for any help.


问:
Changing reocurring events in Goolge Calendar using javascript console
I would like to change if an event is reocurring or not using the javascript console. How can i find the variable or function that needs to change and then change it? Noob here trying to learn.</p>


问:
Live Reload Cordova IONIC
I have the following response when I run:

```<code>$ ionic cordova run android -l
</code>```

Res:

```<code>[INFO] Hardware device(s) found for android. Using --device.
> ng.cmd run app:ionic-cordova-serve --host=localhost --port=8102 --platform=android
[ng] This version of CLI is only compatible with Angular versions ^14.0.0,
[ng] but Angular version 15.0.4 was found instead.
[ng]
[ng] Please visit the link below to find instructions on how to update Angular.
[ng] https://update.angular.io/
[ng]

[ERROR] ng has unexpectedly closed (exit code 3).
</code>```

I would like to be able to run the program I am creating on my android mobile device. Being able to change the design and certain things in real time.

Title: Live Reload Cordova IONIC

Body:
I have the following response when I run:

$ ionic cordova run android -l

Res:

[INFO] Hardware device(s) found for android. Using --device.
> ng.cmd run app:ionic-cordova-serve --host=localhost --port=8102 --platform=android
[ng] This version of CLI is only compatible with Angular versions ^14.0.0,
[ng] but Angular version 15.0.4 was found instead.
[ng]
[ng] Please visit the link below to find instructions on how to update Angular.
[ng] https://update.angular.io/
[ng]

[ERROR] ng has unexpectedly closed (exit code 3).

I would like to be able to run the program I am creating on my android mobile device. Being able to change the design and certain things in real time.


问:
Javascript Pass a variable into a replace method
I am trying to delete all the vowels from a string within a function.

deleteVowels = myString.replace(/[aeiou]/i, "");

Deletes a,e,i,o,u from the string, however instead of (/[aeiou]/i), I want to pass in a value instead which is:

let vowels = "aeiou";

I have tried things such as:

deleteVowels = myString.replace(/[vowels]/i, ""); // and many other variatons.

I have searched SO and found similar, however, not being able to pass in a string keeping the letters separate. Would appreciate some support as I may be barking up the wrong tree here. Thanks


问:
Passing constructor parameter throught multiple objects while resolving in AutoFac
i have difficulties getting my registration in AutoFac done.

Let`s say i have the following classes

```<code>class Foo : IFoo
{
public Foo(string test, IBar bar) {}
}

class Bar : IBar
{
public Bar(bool someFlag) {}
}

</code>```

The issue I'm having now is that i don't know how to set this boolean 'someFlag' while resolving.
I am only able to create these objects and fill in the flag while resolving, not while registering the classes.
Note: This is just an easy example to show the problem. In my case there are half a dozen classes in between Foo and Bar.

Can anyone please help me?

I know how to fill a parameter directly like the string 'test'. But I don`t understand how i pass the boolean through Foo to Bar.

Body:
i have difficulties getting my registration in AutoFac done.

Let`s say i have the following classes

class Foo : IFoo
{
public Foo(string test, IBar bar) {}
}

class Bar : IBar
{
public Bar(bool someFlag) {}
}

The issue I'm having now is that i don't know how to set this boolean 'someFlag' while resolving.
I am only able to create these objects and fill in the flag while resolving, not while registering the classes.
Note: This is just an easy example to show the problem. In my case there are half a dozen classes in between Foo and Bar.

Can anyone please help me?

I know how to fill a parameter directly like the string 'test'. But I don`t understand how i pass the boolean through Foo to Bar.


问:
Unable to delete AWS Batch Compute Environment
I'm running into the following vague error messages while attempting to delete an AWS Batch Compute Environment.

In the output from terraform destroy:

Error: error waiting for Batch Compute Environment (xyzabc) delete: timeout while waiting for resource to be gone (last state: 'DELETING', timeout: 20m0s)

Under the AWS console's "Status reason":

INTERNAL_ERROR - Failed compute environment workflow

The resource's status goes from "DELETING" to "INVALID" after some amount of time.

How can I force the deletion of this resource?


问:
Assign site name based on matching strings (without separating the address)
I am trying to assigna SiteName based on some matching criteria. I have completed the task using the below steps, hwoever was wondering if I could achieve the same result without the  "separate" and "pivot_longer" functions

Code:

```<code>
df <- tibble::tribble(
  ~Author,                       ~"Author Address",
     "BA",        "METRO NORTH; DALLAS",
     "OA",       "RBWH; TPCH; TOPEND",
     "OB", "CABOOLTURE HOSPITAL; CALIFORNIA UNI",
    "AOS",           "CABOOLTURE HOSPITAL; RBWH",
       "KB",                     "WOMENS HOSPITAL"
  )

df

df %>%
  separate (`Author Address`, into = c("Site1", "Site2", "Site3"), sep = ";", remove = F ) %>%
  rename (Address = `Author Address` ) %>%
  pivot_longer (cols = - c(Author, Address), names_to = "Site", values_to = "Author Address" ) %>%
  mutate (`Author Address`  = str_to_upper(`Author Address`),
          Site = case_when (grepl ("METRO NORTH", `Author Address` ) ~ "Metro North Health",
                            grepl ("CABOOLTURE HOSPITAL", `Author Address` ) ~ "Caboolture Hospital",
                            grepl ("TPCH", `Author Address` ) ~ "Prince charles hospital",
                            grepl ("RBWH", `Author Address` ) ~ "RBWH")) %>%
  #filter (!is.na (Site)) %>%
  select (Author, Address, Site ) %>%
  distinct () %>%
  group_by (Author, Address) %>%
  summarise (Site = paste0(Site, collapse = ", "  )) %>%
  ungroup () %>%
  mutate (Site = str_trim (str_remove_all (Site, pattern = ", NA$"  ), "right"  ) )
</code>```

Output:

I have compelete the task but wish to do without the "separate" and "pivot_longer" functions and possibly a short code

Body:
I am trying to assigna SiteName based on some matching criteria. I have completed the task using the below steps, hwoever was wondering if I could achieve the same result without the  "separate" and "pivot_longer" functions

Code:

df <- tibble::tribble(
  ~Author,                       ~"Author Address",
     "BA",        "METRO NORTH; DALLAS",
     "OA",       "RBWH; TPCH; TOPEND",
     "OB", "CABOOLTURE HOSPITAL; CALIFORNIA UNI",
    "AOS",           "CABOOLTURE HOSPITAL; RBWH",
       "KB",                     "WOMENS HOSPITAL"
  )

df

df %>%
  separate (`Author Address`, into = c("Site1", "Site2", "Site3"), sep = ";", remove = F ) %>%
  rename (Address = `Author Address` ) %>%
  pivot_longer (cols = - c(Author, Address), names_to = "Site", values_to = "Author Address" ) %>%
  mutate (`Author Address`  = str_to_upper(`Author Address`),
          Site = case_when (grepl ("METRO NORTH", `Author Address` ) ~ "Metro North Health",
                            grepl ("CABOOLTURE HOSPITAL", `Author Address` ) ~ "Caboolture Hospital",
                            grepl ("TPCH", `Author Address` ) ~ "Prince charles hospital",
                            grepl ("RBWH", `Author Address` ) ~ "RBWH")) %>%
  #filter (!is.na (Site)) %>%
  select (Author, Address, Site ) %>%
  distinct () %>%
  group_by (Author, Address) %>%
  summarise (Site = paste0(Site, collapse = ", "  )) %>%
  ungroup () %>%
  mutate (Site = str_trim (str_remove_all (Site, pattern = ", NA$"  ), "right"  ) )

Output:

I have compelete the task but wish to do without the "separate" and "pivot_longer" functions and possibly a short code


问:
Using HostFXR to host a C# runtime that hotloads user made C# assemblies
I'm trying to write a C++ application that hosts a C# runtime using the HostFXR API. I want to get this C# runtime to load user-made C# assemblies dynamically.

So what I have right now is three .dll files called Host.dll, FunctionLibrary.dll and UserLibrary.dll.

The Host.dll file is what HostFXR hosts in C++.

This is what Host.dll's code looks like

```<code>using System.Reflection;
using System.Runtime.InteropServices;

namespace Host;

public unsafe class Program
{
    private static byte[] ToMemoryStream( Stream input )
    {
        MemoryStream ms = new MemoryStream();
        input.CopyTo( ms );
        return ms.ToArray();
    }

    private static Assembly LoadAssembly( string path )
    {
        return Assembly.Load( ToMemoryStream( File.OpenRead( path ) ) );
    }

    [UnmanagedCallersOnly]
    public static void Main()
    {
        try
        {
            FunctionLibrary.Module.Test = true;

            Assembly userLibrary = LoadAssembly( @"W:\\Visual Studio 2022\\UserLibrary\\bin\\Debug\\net7.0\\UserLibrary.dll" );
            Type? userModule = userLibrary.GetType( "MyLibrary.MyModule" );
            MethodInfo entryPoint = userModule?.GetMethod( "OnStartup", BindingFlags.Static | BindingFlags.Public );
            entryPoint.Invoke( null, null ); // Print out the value of FunctionLibrary.Module.Test, expected to == true
        }
        catch ( Exception ex )
        {
            Console.WriteLine( ex );
        }
    }
}
</code>```

This is FunctionLibrary.dll's code:

```<code>namespace FunctionLibrary;

public static class Module
{
    public static bool Test = false;
}
</code>```

And finally, this is UserLibrary.dll's code:

```<code>using FunctionLibrary;

namespace MyLibrary;

public class MyModule
{
    public static void OnStartup()
    {
        Console.WriteLine( FunctionLibrary.Module.Test );
    }
}
</code>```

What I want to happen is for the console to print out the value of FunctionLibrary.Module.Test, which I set to true in the Host.dll's code;

But when I run my C++ application, the console prints out this error message:

```<code>System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> System.IO.FileNotFoundException: Could not load file or assembly 'FunctionLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
File name: 'FunctionLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'
   at MyLibrary.MyModule.OnStartup()
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
   at System.Reflection.MethodInvoker.Invoke(Object obj, IntPtr* args, BindingFlags invokeAttr)
   --- End of inner exception stack trace ---
   at System.Reflection.MethodInvoker.Invoke(Object obj, IntPtr* args, BindingFlags invokeAttr)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
   at Host.Program.Main() in W:\Visual Studio 2022\Host\Program.cs:line 30
</code>```

I'm really stuck right now, mainly because I just don't know what other avenues I can try to get this working the way I want. I appreciate any help I can get to understand what exactly I'm doing wrong.

Body:
I'm trying to write a C++ application that hosts a C# runtime using the HostFXR API. I want to get this C# runtime to load user-made C# assemblies dynamically.

So what I have right now is three .dll files called Host.dll, FunctionLibrary.dll and UserLibrary.dll.

The Host.dll file is what HostFXR hosts in C++.

This is what Host.dll's code looks like

using System.Reflection;
using System.Runtime.InteropServices;

namespace Host;

public unsafe class Program
{
    private static byte[] ToMemoryStream( Stream input )
    {
        MemoryStream ms = new MemoryStream();
        input.CopyTo( ms );
        return ms.ToArray();
    }

    private static Assembly LoadAssembly( string path )
    {
        return Assembly.Load( ToMemoryStream( File.OpenRead( path ) ) );
    }

    [UnmanagedCallersOnly]
    public static void Main()
    {
        try
        {
            FunctionLibrary.Module.Test = true;

            Assembly userLibrary = LoadAssembly( @"W:\\Visual Studio 2022\\UserLibrary\\bin\\Debug\\net7.0\\UserLibrary.dll" );
            Type? userModule = userLibrary.GetType( "MyLibrary.MyModule" );
            MethodInfo entryPoint = userModule?.GetMethod( "OnStartup", BindingFlags.Static | BindingFlags.Public );
            entryPoint.Invoke( null, null ); // Print out the value of FunctionLibrary.Module.Test, expected to == true
        }
        catch ( Exception ex )
        {
            Console.WriteLine( ex );
        }
    }
}

This is FunctionLibrary.dll's code:

namespace FunctionLibrary;

public static class Module
{
    public static bool Test = false;
}

And finally, this is UserLibrary.dll's code:

using FunctionLibrary;

namespace MyLibrary;

public class MyModule
{
    public static void OnStartup()
    {
        Console.WriteLine( FunctionLibrary.Module.Test );
    }
}

What I want to happen is for the console to print out the value of FunctionLibrary.Module.Test, which I set to true in the Host.dll's code;

But when I run my C++ application, the console prints out this error message:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> System.IO.FileNotFoundException: Could not load file or assembly 'FunctionLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
File name: 'FunctionLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'
   at MyLibrary.MyModule.OnStartup()
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
   at System.Reflection.MethodInvoker.Invoke(Object obj, IntPtr* args, BindingFlags invokeAttr)
   --- End of inner exception stack trace ---
   at System.Reflection.MethodInvoker.Invoke(Object obj, IntPtr* args, BindingFlags invokeAttr)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
   at Host.Program.Main() in W:\Visual Studio 2022\Host\Program.cs:line 30

I'm really stuck right now, mainly because I just don't know what other avenues I can try to get this working the way I want. I appreciate any help I can get to understand what exactly I'm doing wrong.


问:
How to Import Library like Cheerio into Chrome Extension Project?
I am trying to build a simple Chrome extension that utilizes a few JS libraries. The directory structure is as follows:

```<code>cheerio(folder downloaded with npm)
axios.min.js
jquery.min.js
popup.html
test.js
</code>```

As you can see, two of the three libraries I was able to locate a .min file for. However, Cheerio does not appear to have one, so I am trying to figure out how to get it to load in my extension.

I have tried to configure my popup.html as such, which does not work:

```<code><html>
    <script src="jquery.min.js"></script>
    <script type="module" src="cheerio"></script>
    <script src="axios.min.js"></script>
    <body>
        <h1>Header</h1>
    </body>
    <script src="test.js" type="module"></script>
</html>
</code>```

And when I try to import cheerio from 'cheerio', I get a type error.

I am not using a content or background script in my manifest.json, just the action.default_popup.

Can I use web pack as a solution? Is there another way?

Body:
I am trying to build a simple Chrome extension that utilizes a few JS libraries. The directory structure is as follows:

cheerio(folder downloaded with npm)
axios.min.js
jquery.min.js
popup.html
test.js

As you can see, two of the three libraries I was able to locate a .min file for. However, Cheerio does not appear to have one, so I am trying to figure out how to get it to load in my extension.

I have tried to configure my popup.html as such, which does not work:

Header

And when I try to import cheerio from 'cheerio', I get a type error.

I am not using a content or background script in my manifest.json, just the action.default_popup.

Can I use web pack as a solution? Is there another way?


问:
Not understanding type error when using trait objects in Rust
I have the following struct defined in my project:

```<code>pub struct HitableList <'a> {
    pub list : Vec<Box<dyn Hitable + 'a>>
}

impl <'a> HitableList <'a> {
    pub fn new (l : &Vec<Box<dyn Hitable + 'a>>) -> HitableList<'a> {
        HitableList {list : *l}
    }
}
</code>```

where Hitable is a trait that is implemented by HitableList

Then later on I want to create a HitableList like so

```<code>let list = vec![Box::new(Sphere::new(Vec3::new(0f32, 0f32, -1f32), 0.5f32)), Box::new(Sphere::new(Vec3::new(0f32, -100.5f32, -1f32), 100f32))];
let world = &HitableList::new(&list);
</code>```

Spheres in my code also implement the Hitable trait

When I run that last code however I get the following compilation error:

```<code>error[E0308]: mismatched types
--> src/image_gen/many_spheres.rs:39:35
   |     let world = &HitableList::new(&list);
   |                  ---------------- ^^^^^ expected trait object `dyn Hitable`, found struct `Sphere`
   |                  |
   |                  arguments to this function are incorrect
   |
   = note: expected reference `&Vec<Box<dyn Hitable>>`
              found reference `&Vec<Box<Sphere>>`
</code>```

I'm using boxes to contemplate the Vector having different objects that implement the Hitable trait. However, I have no clue why a Box is not a Box

What am I doing wrong and how do I fix this? Thanks in advance

Body:
I have the following struct defined in my project:

pub struct HitableList <'a> {
    pub list : Vec<Box<dyn Hitable + 'a>>
}

impl <'a> HitableList <'a> {
    pub fn new (l : &Vec<Box<dyn Hitable + 'a>>) -> HitableList<'a> {
        HitableList {list : *l}
    }
}

where Hitable is a trait that is implemented by HitableList

Then later on I want to create a HitableList like so

let list = vec![Box::new(Sphere::new(Vec3::new(0f32, 0f32, -1f32), 0.5f32)), Box::new(Sphere::new(Vec3::new(0f32, -100.5f32, -1f32), 100f32))];
let world = &HitableList::new(&list);

Spheres in my code also implement the Hitable trait

When I run that last code however I get the following compilation error:

error[E0308]: mismatched types
--> src/image_gen/many_spheres.rs:39:35
   |     let world = &HitableList::new(&list);
   |                  ---------------- ^^^^^ expected trait object `dyn Hitable`, found struct `Sphere`
   |                  |
   |                  arguments to this function are incorrect
   |
   = note: expected reference `&Vec<Box<dyn Hitable>>`
              found reference `&Vec<Box<Sphere>>`

I'm using boxes to contemplate the Vector having different objects that implement the Hitable trait. However, I have no clue why a Box is not a Box

What am I doing wrong and how do I fix this? Thanks in advance


问:
Is it possible to connect the BTCpay server api to my app
Is It possible for me to use the BTCpay server api within my MERN app to allow users to connect there wallets and create invoices and if say is there any tutorials or pages that I could read up on</p>


问:
Cannot get my python generated chart to display on my live page
I've got some python code creating a chart from a csv file and then saving that interactive chart as an html file. I've tested the file just as a page and it works perfectly with no errors. Yet when I use PHP to display that html page in a block on my wordpress site using Elementor PHP snippets plugin, it displays fine on the editor page, but it does not display at all on the live page.

As I said, I tested the raw html code and the page displayed perfectly in my browser with no errors. I also inserted the raw HTML code into an HTML snippet and it displayed perfectly with no error on the editor page, but it also failed to display on the live page. I am using Python 3.9, PHP 7.4, XYZ PHP snippets plugin and Elementor Pro. Really stuck was hoping to find a code fix or advice on how to find a workaround. Thanks!


问:
create new columns with mean of specific other columns
I'm trying to create 5 new columns in my data frame by calculating the mean of specific already existing columns.

i so far tried the following code:

```<code>`data_new2 <- data1 %>%
  data1$chronisch <-apply(data1[,c(22,28,31,25)],1,mean) %>%
  data1$Sozial <-apply(data1[,33],1,mean) %>%
  data1$überforderung <-apply(data1[,c(30,24,27)],1,mean) %>%
  data1$Anerkennung <-apply(data1[,c(26,29)],1,mean) %>%
  data1$Arbeit <-apply(data1[,c(23,32)],1,mean)`
</code>```

by it give the error message: Fehler in apply(data1[, c(26, 29)], 1, mean) %>% data1$Arbeit <- apply(data1[,  :  konnte Funktion "%>%<-" nicht finden

But I cannot figure out what the problem is. And yes, deplore is installed and loaded.

Would appreciate ny help!

Body:
I'm trying to create 5 new columns in my data frame by calculating the mean of specific already existing columns.

i so far tried the following code:

`data_new2 <- data1 %>%
  data1$chronisch <-apply(data1[,c(22,28,31,25)],1,mean) %>%
  data1$Sozial <-apply(data1[,33],1,mean) %>%
  data1$überforderung <-apply(data1[,c(30,24,27)],1,mean) %>%
  data1$Anerkennung <-apply(data1[,c(26,29)],1,mean) %>%
  data1$Arbeit <-apply(data1[,c(23,32)],1,mean)`

by it give the error message: Fehler in apply(data1[, c(26, 29)], 1, mean) %>% data1$Arbeit <- apply(data1[,  :  konnte Funktion "%>%<-" nicht finden

But I cannot figure out what the problem is. And yes, deplore is installed and loaded.

Would appreciate ny help!


问:
What is considered the most modern and robust way to do a browser (engine) based redirect?
e.g. for installing a browser extension if you wanted to have a single page that sends users to either the Chrome App store or Firefox add-ons page based on just the name of the browser but but underlying extension compatibility (e.g. Chromium based browsers, incl.Edge ,Opera, Brave to Chrome store, Firefox and Tor browsers, Palemoon etc. to Firefox add-on store, and Safari to an error page.

I know you can name them by user agent individually, but is there a more robust way that's more future-proof and relies on the underlying browser engine for the redirect logic?


问:
Reprojection from North Polar Stereo to Lat/Lon using Rioxarray causes dataset to become corrupted
I am attempting to reproject a CMC Snow Depth Map (in GeoTIFF format) from North Polar Stereo to Lat/Lon. The PROJ string of the file is: '+proj=stere +lat_0=90 +lat_ts=60 +lon_0=10 +x_0=0 +y_0=0 +R=6371200 +units=m +no_defs=True'. The data is stored here: https://drive.google.com/file/d/1EhzWiOMF2YEYpDOPpmfH58tJMQOxNdIM/view?usp=share_link

Here is a reproduction of my code block:

```<code>import rasterio
from rasterio.warp import calculate_default_transform, reproject, Resampling
from rasterio.crs import CRS
from rioxarray.crs import crs_from_user_input
import rioxarray as rxr
#### Open CMC Data ####
yrs = np.arange(1980,2020,1)

CMC_dir = '/mnt/data/obs/CMC_snow_depth/'

CMC_fil = ''.join([CMC_dir+'cmc_sdepth_dly_1998_v01.2.tif'])

dates = pd.date_range(start='08-01-1998', end='12-31-1998', freq='D')

### Create XArray Dataset ###
CMC_dataset = rxr.open_rasterio(CMC_fil,decode_coords="all")
print(CMC_dataset)

#writing the crs, using proj4
crs_CMC = CRS.from_string('+proj=stere +lat_0=90 +lat_ts=60 +lon_0=10 +x_0=0 +y_0=0 +R=6371200 +units=m +no_defs=True')
CMC_dataset = CMC_dataset.rio.write_crs(crs_CMC)

### Reproject to Lat/Lon from Polar Stereographic ###
CMC_dataset_latlon = CMC_dataset.rio.reproject("EPSG:4326") #EPSG:4326 is the lat/lon projection
print(CMC_dataset_latlon)
</code>```

The input data has the following structure:

```<code><xarray.DataArray (band: 153, y: 706, x: 706)>
[76260708 values with dtype=float64]
Coordinates:
  * band         (band) int64 1 2 3 4 5 6 7 8 ... 147 148 149 150 151 152 153
  * x            (x) float64 -8.394e+06 -8.37e+06 ... 8.37e+06 8.394e+06
  * y            (y) float64 8.394e+06 8.37e+06 ... -8.37e+06 -8.394e+06
    spatial_ref  int64 0
Attributes:
    AREA_OR_POINT:  Area
    _FillValue:     -1.7e+308
    scale_factor:   1.0
    add_offset:     0.0
</code>```

However, when I go to reproject the file to Lat/Lon, the dataset becomes corrupted, and the lat/lon become strange:

```<code><xarray.DataArray (band: 153, y: 54, x: 997)>
array([[[ 0.0e+000,  0.0e+000,  0.0e+000, ...,  0.0e+000,  0.0e+000,
          0.0e+000],
        [ 0.0e+000,  0.0e+000,  0.0e+000, ...,  0.0e+000,  0.0e+000,
          0.0e+000],
        [-1.7e+308, -1.7e+308, -1.7e+308, ...,  0.0e+000,  0.0e+000,
         -1.7e+308],
        ...,
        [-1.7e+308, -1.7e+308, -1.7e+308, ..., -1.7e+308, -1.7e+308,
         -1.7e+308],
        [-1.7e+308, -1.7e+308, -1.7e+308, ..., -1.7e+308, -1.7e+308,
         -1.7e+308],
        [-1.7e+308, -1.7e+308, -1.7e+308, ..., -1.7e+308, -1.7e+308,
         -1.7e+308]],

       [[ 0.0e+000,  0.0e+000,  0.0e+000, ...,  0.0e+000,  0.0e+000,
          0.0e+000],
        [ 0.0e+000,  0.0e+000,  0.0e+000, ...,  0.0e+000,  0.0e+000,
          0.0e+000],
        [-1.7e+308, -1.7e+308, -1.7e+308, ...,  0.0e+000,  0.0e+000,
         -1.7e+308],
...
        [-1.7e+308, -1.7e+308, -1.7e+308, ..., -1.7e+308, -1.7e+308,
         -1.7e+308],
        [-1.7e+308, -1.7e+308, -1.7e+308, ..., -1.7e+308, -1.7e+308,
         -1.7e+308],
        [-1.7e+308, -1.7e+308, -1.7e+308, ..., -1.7e+308, -1.7e+308,
         -1.7e+308]],

       [[ 0.0e+000,  0.0e+000,  0.0e+000, ...,  0.0e+000,  0.0e+000,
          0.0e+000],
        [ 0.0e+000,  0.0e+000,  0.0e+000, ...,  0.0e+000,  0.0e+000,
          0.0e+000],
        [-1.7e+308, -1.7e+308, -1.7e+308, ...,  0.0e+000,  0.0e+000,
         -1.7e+308],
        ...,
        [-1.7e+308, -1.7e+308, -1.7e+308, ..., -1.7e+308, -1.7e+308,
         -1.7e+308],
        [-1.7e+308, -1.7e+308, -1.7e+308, ..., -1.7e+308, -1.7e+308,
         -1.7e+308],
        [-1.7e+308, -1.7e+308, -1.7e+308, ..., -1.7e+308, -1.7e+308,
         -1.7e+308]]])
Coordinates:
  * x            (x) float64 -179.8 -179.5 -179.1 -178.7 ... 179.1 179.4 179.8
  * y            (y) float64 19.3 18.94 18.57 18.21 ... 0.8805 0.5194 0.1583
  * band         (band) int64 1 2 3 4 5 6 7 8 ... 147 148 149 150 151 152 153
    spatial_ref  int64 0
Attributes:
    AREA_OR_POINT:  Area
    scale_factor:   1.0
    add_offset:     0.0
    _FillValue:     -1.7e+308
</code>```

Any idea what is happening here?

Body:
I am attempting to reproject a CMC Snow Depth Map (in GeoTIFF format) from North Polar Stereo to Lat/Lon. The PROJ string of the file is: '+proj=stere +lat_0=90 +lat_ts=60 +lon_0=10 +x_0=0 +y_0=0 +R=6371200 +units=m +no_defs=True'. The data is stored here: https://drive.google.com/file/d/1EhzWiOMF2YEYpDOPpmfH58tJMQOxNdIM/view?usp=share_link

Here is a reproduction of my code block:

import rasterio
from rasterio.warp import calculate_default_transform, reproject, Resampling
from rasterio.crs import CRS
from rioxarray.crs import crs_from_user_input
import rioxarray as rxr
#### Open CMC Data ####
yrs = np.arange(1980,2020,1)

CMC_dir = '/mnt/data/obs/CMC_snow_depth/'

CMC_fil = ''.join([CMC_dir+'cmc_sdepth_dly_1998_v01.2.tif'])

dates = pd.date_range(start='08-01-1998', end='12-31-1998', freq='D')

### Create XArray Dataset ###
CMC_dataset = rxr.open_rasterio(CMC_fil,decode_coords="all")
print(CMC_dataset)

#writing the crs, using proj4
crs_CMC = CRS.from_string('+proj=stere +lat_0=90 +lat_ts=60 +lon_0=10 +x_0=0 +y_0=0 +R=6371200 +units=m +no_defs=True')
CMC_dataset = CMC_dataset.rio.write_crs(crs_CMC)

### Reproject to Lat/Lon from Polar Stereographic ###
CMC_dataset_latlon = CMC_dataset.rio.reproject("EPSG:4326") #EPSG:4326 is the lat/lon projection
print(CMC_dataset_latlon)

The input data has the following structure:

<xarray.DataArray (band: 153, y: 706, x: 706)>
[76260708 values with dtype=float64]
Coordinates:
  * band         (band) int64 1 2 3 4 5 6 7 8 ... 147 148 149 150 151 152 153
  * x            (x) float64 -8.394e+06 -8.37e+06 ... 8.37e+06 8.394e+06
  * y            (y) float64 8.394e+06 8.37e+06 ... -8.37e+06 -8.394e+06
    spatial_ref  int64 0
Attributes:
    AREA_OR_POINT:  Area
    _FillValue:     -1.7e+308
    scale_factor:   1.0
    add_offset:     0.0

However, when I go to reproject the file to Lat/Lon, the dataset becomes corrupted, and the lat/lon become strange:

<xarray.DataArray (band: 153, y: 54, x: 997)>
array([[[ 0.0e+000,  0.0e+000,  0.0e+000, ...,  0.0e+000,  0.0e+000,
          0.0e+000],
        [ 0.0e+000,  0.0e+000,  0.0e+000, ...,  0.0e+000,  0.0e+000,
          0.0e+000],
        [-1.7e+308, -1.7e+308, -1.7e+308, ...,  0.0e+000,  0.0e+000,
         -1.7e+308],
        ...,
        [-1.7e+308, -1.7e+308, -1.7e+308, ..., -1.7e+308, -1.7e+308,
         -1.7e+308],
        [-1.7e+308, -1.7e+308, -1.7e+308, ..., -1.7e+308, -1.7e+308,
         -1.7e+308],
        [-1.7e+308, -1.7e+308, -1.7e+308, ..., -1.7e+308, -1.7e+308,
         -1.7e+308]],

       [[ 0.0e+000,  0.0e+000,  0.0e+000, ...,  0.0e+000,  0.0e+000,
          0.0e+000],
        [ 0.0e+000,  0.0e+000,  0.0e+000, ...,  0.0e+000,  0.0e+000,
          0.0e+000],
        [-1.7e+308, -1.7e+308, -1.7e+308, ...,  0.0e+000,  0.0e+000,
         -1.7e+308],
...
        [-1.7e+308, -1.7e+308, -1.7e+308, ..., -1.7e+308, -1.7e+308,
         -1.7e+308],
        [-1.7e+308, -1.7e+308, -1.7e+308, ..., -1.7e+308, -1.7e+308,
         -1.7e+308],
        [-1.7e+308, -1.7e+308, -1.7e+308, ..., -1.7e+308, -1.7e+308,
         -1.7e+308]],

       [[ 0.0e+000,  0.0e+000,  0.0e+000, ...,  0.0e+000,  0.0e+000,
          0.0e+000],
        [ 0.0e+000,  0.0e+000,  0.0e+000, ...,  0.0e+000,  0.0e+000,
          0.0e+000],
        [-1.7e+308, -1.7e+308, -1.7e+308, ...,  0.0e+000,  0.0e+000,
         -1.7e+308],
        ...,
        [-1.7e+308, -1.7e+308, -1.7e+308, ..., -1.7e+308, -1.7e+308,
         -1.7e+308],
        [-1.7e+308, -1.7e+308, -1.7e+308, ..., -1.7e+308, -1.7e+308,
         -1.7e+308],
        [-1.7e+308, -1.7e+308, -1.7e+308, ..., -1.7e+308, -1.7e+308,
         -1.7e+308]]])
Coordinates:
  * x            (x) float64 -179.8 -179.5 -179.1 -178.7 ... 179.1 179.4 179.8
  * y            (y) float64 19.3 18.94 18.57 18.21 ... 0.8805 0.5194 0.1583
  * band         (band) int64 1 2 3 4 5 6 7 8 ... 147 148 149 150 151 152 153
    spatial_ref  int64 0
Attributes:
    AREA_OR_POINT:  Area
    scale_factor:   1.0
    add_offset:     0.0
    _FillValue:     -1.7e+308

Any idea what is happening here?