问:
Filtering react data table through mui modal
I am trying to create a react data table and filter the data in the table through mui textfield in a mui Modal.
Here is the image
The filters in every column must open in the mui modal .Like this example Like this example They must have the functionality to search.
Kindly suggest me the code to filter every column separately through  mui text fields in the same Modal

```<code>import React, { useState } from 'react'
import styled from 'styled-components'
import { useTable, usePagination, useFilters, useGlobalFilter, useSortBy, useAsyncDebounce } from 'react-table'
import makeData from './makeData'
import MDBTypography from 'components/MDBTypography'
import { Divider, Grid, InputAdornment, Modal, Tooltip } from '@mui/material'
import ArrowDropUpOutlinedIcon from '@mui/icons-material/ArrowDropUpOutlined';
import ArrowDropDownOutlinedIcon from '@mui/icons-material/ArrowDropDownOutlined';
import SearchIcon from "assets/images/icons/svg/medium/SearchIcon.svg";
import { matchSorter } from 'match-sorter'
import MDBInput from 'components/MDBInput'
import MDBButton from 'components/MDBButton'
import FilterListOutlinedIcon from '@mui/icons-material/FilterListOutlined';
import MDBCard from 'components/MDBCard'
const Styles = styled.div`
    padding: 1rem;
    table {
      border-spacing: 0;
      border: 1px solid #44474A;
      tr {
        :last-child {
          td {
            border-bottom: 0;
          }
        }

      }
      th{
        background:#1C1F21;
      }
      th,
      td {
        margin: 0;
        padding: 0.5rem;
        border-bottom: 1px solid #44474A;
        border-right: 1px solid #44474A;
        :last-child {
          border-right: 0;
        }
      }
    }
    .pagination {
      padding: 0.5rem;
    }
  `

// Define a default UI for filtering
function GlobalFilter({
  preGlobalFilteredRows,
  globalFilter,
  setGlobalFilter,
}) {
  const count = preGlobalFilteredRows.length
  const [value, setValue] = useState(globalFilter)
  const onChange = useAsyncDebounce(value => {
    setGlobalFilter(value || undefined)
  }, 200)
  // Set Filter popover
  const [mediaKits, setMediaKits] = useState([]);
  const handleClose = () => {
    setAnchorEl(null);
  }
  const [anchorEl, setAnchorEl] = React.useState(null);
  const open = Boolean(anchorEl);
  const id = open ? 'simple-popover' : undefined;
  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };
  return (
    <>
      <MDBInput
        search={true}
        value={value || ""}
        fullWidth
        InputProps={{
          endAdornment: (
            <InputAdornment position="end">
              <MDBTypography component="img" src={SearchIcon} />
            </InputAdornment>
          ),
        }}
        onChange={e => {
          setValue(e.target.value);
          onChange(e.target.value);
        }}
        placeholder={`Search ${count} records...`}
        variant="standard"
        width="400px"
      />

      <MDBButton
        size="medium"
        variant="contained"
        color="white"
        bgColor="smoke_light"
        fontWeight="medium"
        fontSize="md"
        borderSize="md"
        lineHeight="2xxl"
        aria-describedby={id}
        onClick={handleClick}
      >
        <FilterListOutlinedIcon
          color="white"
        />
      </MDBButton>
      <Modal
        id={id}
        open={open}
        onClose={handleClose}
      >
        <>

          <MDBCard bgcolor="black"  >
            {/* //sx={{ px: 0, pt:0, pb: 1.5, width:"min-content"}} */}
            <Grid sx={{ px: 2.5, py: 2 }}>
              <MDBTypography sx={{ pb: 1 }}>
                Filters
              </MDBTypography>
            </Grid>
            <Divider />
            <Tooltip title={`Search ${count} records...`}>
              <MDBInput
                sx={{ pr: 4, input: { cursor: 'pointer' } }}
                placeholder="Filter First Name..."
              />
            </Tooltip>
            <Divider />
            <Tooltip title={`Search ${count} records...`}>
              <MDBInput
                sx={{ pr: 4, input: { cursor: 'pointer' } }}
                placeholder="Filter Last Name..."
              />
            </Tooltip>
            <Divider />
            <Tooltip title={`Search ${count} records...`}>
              <filterGreaterThan />
            </Tooltip>
          </MDBCard>
        </>
      </Modal>
    </>
  )
}
// Define a default UI for filtering
function DefaultColumnFilter({
  column: { filterValue, preFilteredRows, setFilter },
}) {
  const count = preFilteredRows.length

  return (
    <input
      value={filterValue || ''}
      onChange={e => {
        setFilter(e.target.value || undefined) // Set undefined to remove the filter entirely
      }}
      placeholder={`Search ${count} records...`}
    />
  )
}

// This is a custom filter UI for selecting
// a unique option from a list
function SelectColumnFilter({
  column: { filterValue, setFilter, preFilteredRows, id },
}) {
  // Calculate the options for filtering
  // using the preFilteredRows
  const options = React.useMemo(() => {
    const options = new Set()
    preFilteredRows.forEach(row => {
      options.add(row.values[id])
    })
    return [...options.values()]
  }, [id, preFilteredRows])

  // Render a multi-select box
  return (
    <select
      value={filterValue}
      onChange={e => {
        setFilter(e.target.value || undefined)
      }}
    >
      <option value="">All</option>
      {options.map((option, i) => (
        <option key={i} value={option}>
          {option}
        </option>
      ))}
    </select>
  )
}

// This is a custom filter UI that uses a
// slider to set the filter value between a column's
// min and max values
function SliderColumnFilter({
  column: { filterValue, setFilter, preFilteredRows, id },
}) {
  // Calculate the min and max
  // using the preFilteredRows

  const [min, max] = React.useMemo(() => {
    let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
    let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
    preFilteredRows.forEach(row => {
      min = Math.min(row.values[id], min)
      max = Math.max(row.values[id], max)
    })
    return [min, max]
  }, [id, preFilteredRows])

  return (
    <>
      <input
        type="range"
        min={min}
        max={max}
        value={filterValue || min}
        onChange={e => {
          setFilter(parseInt(e.target.value, 10))
        }}
      />
      <button onClick={() => setFilter(undefined)}>Off</button>
    </>
  )
}

// This is a custom UI for our 'between' or number range
// filter. It uses two number boxes and filters rows to
// ones that have values between the two
function NumberRangeColumnFilter({
  column: { filterValue = [], preFilteredRows, setFilter, id },
}) {
  const [min, max] = React.useMemo(() => {
    let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
    let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
    preFilteredRows.forEach(row => {
      min = Math.min(row.values[id], min)
      max = Math.max(row.values[id], max)
    })
    return [min, max]
  }, [id, preFilteredRows])

  return (
    <div
      style={{
        display: 'flex',
      }}
    >
      <input
        value={filterValue[0] || ''}
        type="number"
        onChange={e => {
          const val = e.target.value
          setFilter((old = []) => [val ? parseInt(val, 10) : undefined, old[1]])
        }}
        placeholder={`Min (${min})`}
        style={{
          width: '70px',
          marginRight: '0.5rem',
        }}
      />
      to
      <input
        value={filterValue[1] || ''}
        type="number"
        onChange={e => {
          const val = e.target.value
          setFilter((old = []) => [old[0], val ? parseInt(val, 10) : undefined])
        }}
        placeholder={`Max (${max})`}
        style={{
          width: '70px',
          marginLeft: '0.5rem',
        }}
      />
    </div>
  )
}

function fuzzyTextFilterFn(rows, id, filterValue) {
  return matchSorter(rows, filterValue, { keys: [row => row.values[id]] })
}

// Let the table remove the filter if the string is empty
fuzzyTextFilterFn.autoRemove = val => !val

function Table({ columns, data }) {
  const filterTypes = React.useMemo(
    () => ({
      // Add a new fuzzyTextFilterFn filter type.
      fuzzyText: fuzzyTextFilterFn,
      // Or, override the default text filter to use
      // "startWith"
      text: (rows, id, filterValue) => {
        return rows.filter(row => {
          const rowValue = row.values[id]
          return rowValue !== undefined
            ? String(rowValue)
              .toLowerCase()
              .startsWith(String(filterValue).toLowerCase())
            : true
        })
      },
    }),
    []
  )

  const defaultColumn = React.useMemo(
    () => ({
      // Let's set up our default Filter UI
      Filter: DefaultColumnFilter,
    }),
    []
  )
  // Use the state and functions returned from useTable to build your UI
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
    state,
    visibleColumns,
    preGlobalFilteredRows,
    setGlobalFilter,
    page, // Instead of using 'rows', we'll use page,
    // which has only the rows for the active page
    // The rest of these things are super handy, too ;)
    canPreviousPage,
    canNextPage,
    pageOptions,
    pageCount,
    gotoPage,
    nextPage,
    previousPage,
    setPageSize,
    state: { pageIndex, pageSize },
  } = useTable(
    {
      columns,

      data,
      defaultColumn, // Be sure to pass the defaultColumn option
      filterTypes,
      initialState: { pageIndex: 0 },
    },
    useFilters, // useFilters!
    useGlobalFilter,
    useSortBy,
    usePagination,
  )

  // Render the UI for your table
  const firstPageRows = rows.slice(0, 20)
  return (
    <>
      {/* ```

            {JSON.stringify(
              {
                pageIndex,
                pageSize,
                pageCount,
                canNextPage,
                canPreviousPage,
              },
              null,
              2
            )}

        ``` */}
      <GlobalFilter
        preGlobalFilteredRows={preGlobalFilteredRows}
        globalFilter={state.globalFilter}
        setGlobalFilter={setGlobalFilter}
      />
      <table {...getTableProps()}>
        <thead>
          {headerGroups.map(headerGroup => (
            <tr {...headerGroup.getHeaderGroupProps()} >
              {headerGroup.headers.map(column => (
                <th {...column.getHeaderProps(column.getSortByToggleProps())}>
                  {column.render('Header')}
                  {/* Add a sort direction indicator */}
                  <Grid
                    container
                    direction="row"
                    justifyContent='flex-end'
                    alignItems='flex-end'
                  >
                    <Grid
                      container
                      direction='row'
                      justifyContent="flex-end"
                      alignItems="flex-end"
                      sx={{ mt: -4.9, ml: 4 }}
                    >
                      {
                        column.isSorted ?
                          column.isSortedDesc
                            ? <ArrowDropUpOutlinedIcon color='white' sx={{ mb: 1 }} />
                            : <ArrowDropDownOutlinedIcon color='white' />
                          : ''
                      }
                    </Grid>
                  </Grid>
                  <div>{column.canFilter ? column.render('Filter') : null}</div>
                </th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody {...getTableBodyProps()}>
          {page.map((row, i) => {
            prepareRow(row)
            return (
              <tr {...row.getRowProps()}>
                {row.cells.map(cell => {
                  return (<td {...cell.getCellProps()}>{cell.render('Cell')}</td>)
                })}
              </tr>
            )
          })}
        </tbody>
      </table>
      {/*
          Pagination can be built however you'd like.
          This is just a very basic UI implementation:
        */}
      <Grid
        container
        className="pagination"
        sx={{ ml: 42 }}
      >
        <Grid>
          <MDBTypography fontWeight="regular" fontSize="xxs" lineHeight='md' sx={{ mt: 1 }}>
            Page{' '}
            {/* <strong> */}
            {pageIndex + 1} of {pageOptions.length} |
            {/* </strong>{' '} */}
          </MDBTypography>
        </Grid>
        <Grid sx={{ ml: 1, mt: -0.4 }}>
          <button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>
            {'<<'}
          </button>{' '}
          <button onClick={() => previousPage()} disabled={!canPreviousPage}>
            {'<'}
          </button>{' '}
          <button onClick={() => nextPage()} disabled={!canNextPage}>
            {'>'}
          </button>{' '}
          <button onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage}>
            {'>>'}
          </button>{' '}
        </Grid>
        {/* <span>
            | Go to page:{' '}
            <input
              type="number"
              defaultValue={pageIndex + 1}
              onChange={e => {
                const page = e.target.value ? Number(e.target.value) - 1 : 0
                gotoPage(page)
              }}
              style={{ width: '100px' }}
            />
          </span>{' '}
          <select
            value={pageSize}
            onChange={e => {
              setPageSize(Number(e.target.value))
            }}
          >
            {[10, 20, 30, 40, 50].map(pageSize => (
              <option key={pageSize} value={pageSize}>
                Show {pageSize}
              </option>
            ))}
          </select> */}
      </Grid>
    </>
  )
}
function filterGreaterThan(rows, id, filterValue) {
  return rows.filter(row => {
    const rowValue = row.values[id]
    return rowValue >= filterValue
  })
}

function App() {
  const [isOpen, setIsOpen] = useState(false);
  const handleOpen = () => {
    console.log('This is a test')
    setIsOpen(true);
  }
  const handleClose = () => setIsOpen(false);

  const columns = React.useMemo(
    () => [
      {
        Header: <MDBTypography sx={{ mr: 2 }}>First Name</MDBTypography>,
        accessor: 'firstName',
      },
      {
        Header: <MDBTypography sx={{ mr: 2 }}>Last Name</MDBTypography>,
        accessor: 'lastName',
        filter: 'fuzzyText'
      },
      {
        Header: <MDBTypography sx={{ mr: 2 }}>Age</MDBTypography>,
        accessor: 'age',
        Filter: SliderColumnFilter,
        filter: 'equals'
      },
      {
        Header: <MDBTypography sx={{ mr: 2 }}>Visits</MDBTypography>,
        accessor: 'visits',
        filter: filterGreaterThan,
        Filter: NumberRangeColumnFilter,
        filter: 'between',
      },
      {
        Header: <MDBTypography sx={{ mr: 2 }}>Status</MDBTypography>,
        accessor: 'status',
        Filter: SelectColumnFilter,
        filter: 'includes',
      },
      {
        Header: <MDBTypography sx={{ mr: 2 }}>Profile Progress</MDBTypography>,
        accessor: 'progress',
        Filter: SliderColumnFilter,
        filter: filterGreaterThan,
      },
      {
        Header: <MDBTypography sx={{ mr: 2 }}>Edit</MDBTypography>,
        accessor: 'edit',

        Cell: ({ value }) => (
          <Grid
            container
            justifyContent="space-between">
            <MDBButton variant="outlined" onClick={() => handleEdit(value)}>Edit</MDBButton>
            <MDBButton variant="outlined" sx={{ backgroundColor: "red" }} onClick={handleOpen}>Delrte</MDBButton>
            <Modal
              // open={isOpen}
              // onClose={handleClose}
              aria-labelledby="modal-modal-title"
              aria-describedby="modal-modal-description"
            >
              <MDBCard bgcolor="black"  >
                Are You Sure :
                <MDBButton>
                  Yes
                </MDBButton>
                <MDBButton onClick={handleClose}>
                  No
                </MDBButton>
              </MDBCard>
            </Modal>
          </Grid>
        )
      },
    ],
    []
  )

  function handleEdit(row) {
    console.log(row);
  }
  function HandleDelete(row) {
    console.log(row)
    setIsOpen(true)
    console.log("Set is open done")
  }

  const data = React.useMemo(() => makeData(100).map((item) => ({ ...item, edit: item })))
  return (
    <Styles>
      <MDBTypography fontWeight="regular" fontSize="xxs" lineHeight='md'>
        <Table columns={columns} data={data} />
      </MDBTypography>
    </Styles>
  )
}

export default App
</code>```

Body:
I am trying to create a react data table and filter the data in the table through mui textfield in a mui Modal.
Here is the image
The filters in every column must open in the mui modal .Like this example Like this example They must have the functionality to search.
Kindly suggest me the code to filter every column separately through  mui text fields in the same Modal

import React, { useState } from 'react'
import styled from 'styled-components'
import { useTable, usePagination, useFilters, useGlobalFilter, useSortBy, useAsyncDebounce } from 'react-table'
import makeData from './makeData'
import MDBTypography from 'components/MDBTypography'
import { Divider, Grid, InputAdornment, Modal, Tooltip } from '@mui/material'
import ArrowDropUpOutlinedIcon from '@mui/icons-material/ArrowDropUpOutlined';
import ArrowDropDownOutlinedIcon from '@mui/icons-material/ArrowDropDownOutlined';
import SearchIcon from "assets/images/icons/svg/medium/SearchIcon.svg";
import { matchSorter } from 'match-sorter'
import MDBInput from 'components/MDBInput'
import MDBButton from 'components/MDBButton'
import FilterListOutlinedIcon from '@mui/icons-material/FilterListOutlined';
import MDBCard from 'components/MDBCard'
const Styles = styled.div`
    padding: 1rem;
    table {
      border-spacing: 0;
      border: 1px solid #44474A;
      tr {
        :last-child {
          td {
            border-bottom: 0;
          }
        }

      }
      th{
        background:#1C1F21;
      }
      th,
      td {
        margin: 0;
        padding: 0.5rem;
        border-bottom: 1px solid #44474A;
        border-right: 1px solid #44474A;
        :last-child {
          border-right: 0;
        }
      }
    }
    .pagination {
      padding: 0.5rem;
    }
  `

// Define a default UI for filtering
function GlobalFilter({
  preGlobalFilteredRows,
  globalFilter,
  setGlobalFilter,
}) {
  const count = preGlobalFilteredRows.length
  const [value, setValue] = useState(globalFilter)
  const onChange = useAsyncDebounce(value => {
    setGlobalFilter(value || undefined)
  }, 200)
  // Set Filter popover
  const [mediaKits, setMediaKits] = useState([]);
  const handleClose = () => {
    setAnchorEl(null);
  }
  const [anchorEl, setAnchorEl] = React.useState(null);
  const open = Boolean(anchorEl);
  const id = open ? 'simple-popover' : undefined;
  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };
  return (
    <>
      <MDBInput
        search={true}
        value={value || ""}
        fullWidth
        InputProps={{
          endAdornment: (
            <InputAdornment position="end">
              <MDBTypography component="img" src={SearchIcon} />
            </InputAdornment>
          ),
        }}
        onChange={e => {
          setValue(e.target.value);
          onChange(e.target.value);
        }}
        placeholder={`Search ${count} records...`}
        variant="standard"
        width="400px"
      />

      <MDBButton
        size="medium"
        variant="contained"
        color="white"
        bgColor="smoke_light"
        fontWeight="medium"
        fontSize="md"
        borderSize="md"
        lineHeight="2xxl"
        aria-describedby={id}
        onClick={handleClick}
      >
        <FilterListOutlinedIcon
          color="white"
        />
      </MDBButton>
      <Modal
        id={id}
        open={open}
        onClose={handleClose}
      >
        <>

          <MDBCard bgcolor="black"  >
            {/* //sx={{ px: 0, pt:0, pb: 1.5, width:"min-content"}} */}
            <Grid sx={{ px: 2.5, py: 2 }}>
              <MDBTypography sx={{ pb: 1 }}>
                Filters
              </MDBTypography>
            </Grid>
            <Divider />
            <Tooltip title={`Search ${count} records...`}>
              <MDBInput
                sx={{ pr: 4, input: { cursor: 'pointer' } }}
                placeholder="Filter First Name..."
              />
            </Tooltip>
            <Divider />
            <Tooltip title={`Search ${count} records...`}>
              <MDBInput
                sx={{ pr: 4, input: { cursor: 'pointer' } }}
                placeholder="Filter Last Name..."
              />
            </Tooltip>
            <Divider />
            <Tooltip title={`Search ${count} records...`}>
              <filterGreaterThan />
            </Tooltip>
          </MDBCard>
        </>
      </Modal>
    </>
  )
}
// Define a default UI for filtering
function DefaultColumnFilter({
  column: { filterValue, preFilteredRows, setFilter },
}) {
  const count = preFilteredRows.length

  return (
    <input
      value={filterValue || ''}
      onChange={e => {
        setFilter(e.target.value || undefined) // Set undefined to remove the filter entirely
      }}
      placeholder={`Search ${count} records...`}
    />
  )
}

// This is a custom filter UI for selecting
// a unique option from a list
function SelectColumnFilter({
  column: { filterValue, setFilter, preFilteredRows, id },
}) {
  // Calculate the options for filtering
  // using the preFilteredRows
  const options = React.useMemo(() => {
    const options = new Set()
    preFilteredRows.forEach(row => {
      options.add(row.values[id])
    })
    return [...options.values()]
  }, [id, preFilteredRows])

  // Render a multi-select box
  return (
    <select
      value={filterValue}
      onChange={e => {
        setFilter(e.target.value || undefined)
      }}
    >
      <option value="">All</option>
      {options.map((option, i) => (
        <option key={i} value={option}>
          {option}
        </option>
      ))}
    </select>
  )
}

// This is a custom filter UI that uses a
// slider to set the filter value between a column's
// min and max values
function SliderColumnFilter({
  column: { filterValue, setFilter, preFilteredRows, id },
}) {
  // Calculate the min and max
  // using the preFilteredRows

  const [min, max] = React.useMemo(() => {
    let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
    let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
    preFilteredRows.forEach(row => {
      min = Math.min(row.values[id], min)
      max = Math.max(row.values[id], max)
    })
    return [min, max]
  }, [id, preFilteredRows])

  return (
    <>
      <input
        type="range"
        min={min}
        max={max}
        value={filterValue || min}
        onChange={e => {
          setFilter(parseInt(e.target.value, 10))
        }}
      />
      <button onClick={() => setFilter(undefined)}>Off</button>
    </>
  )
}

// This is a custom UI for our 'between' or number range
// filter. It uses two number boxes and filters rows to
// ones that have values between the two
function NumberRangeColumnFilter({
  column: { filterValue = [], preFilteredRows, setFilter, id },
}) {
  const [min, max] = React.useMemo(() => {
    let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
    let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
    preFilteredRows.forEach(row => {
      min = Math.min(row.values[id], min)
      max = Math.max(row.values[id], max)
    })
    return [min, max]
  }, [id, preFilteredRows])

  return (

      <input
        value={filterValue[0] || ''}
        type="number"
        onChange={e => {
          const val = e.target.value
          setFilter((old = []) => [val ? parseInt(val, 10) : undefined, old[1]])
        }}
        placeholder={`Min (${min})`}
        style={{
          width: '70px',
          marginRight: '0.5rem',
        }}
      />
      to
      <input
        value={filterValue[1] || ''}
        type="number"
        onChange={e => {
          const val = e.target.value
          setFilter((old = []) => [old[0], val ? parseInt(val, 10) : undefined])
        }}
        placeholder={`Max (${max})`}
        style={{
          width: '70px',
          marginLeft: '0.5rem',
        }}
      />

  )
}

function fuzzyTextFilterFn(rows, id, filterValue) {
  return matchSorter(rows, filterValue, { keys: [row => row.values[id]] })
}

// Let the table remove the filter if the string is empty
fuzzyTextFilterFn.autoRemove = val => !val

function Table({ columns, data }) {
  const filterTypes = React.useMemo(
    () => ({
      // Add a new fuzzyTextFilterFn filter type.
      fuzzyText: fuzzyTextFilterFn,
      // Or, override the default text filter to use
      // "startWith"
      text: (rows, id, filterValue) => {
        return rows.filter(row => {
          const rowValue = row.values[id]
          return rowValue !== undefined
            ? String(rowValue)
              .toLowerCase()
              .startsWith(String(filterValue).toLowerCase())
            : true
        })
      },
    }),
    []
  )

  const defaultColumn = React.useMemo(
    () => ({
      // Let's set up our default Filter UI
      Filter: DefaultColumnFilter,
    }),
    []
  )
  // Use the state and functions returned from useTable to build your UI
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
    state,
    visibleColumns,
    preGlobalFilteredRows,
    setGlobalFilter,
    page, // Instead of using 'rows', we'll use page,
    // which has only the rows for the active page
    // The rest of these things are super handy, too ;)
    canPreviousPage,
    canNextPage,
    pageOptions,
    pageCount,
    gotoPage,
    nextPage,
    previousPage,
    setPageSize,
    state: { pageIndex, pageSize },
  } = useTable(
    {
      columns,

      data,
      defaultColumn, // Be sure to pass the defaultColumn option
      filterTypes,
      initialState: { pageIndex: 0 },
    },
    useFilters, // useFilters!
    useGlobalFilter,
    useSortBy,
    usePagination,
  )

  // Render the UI for your table
  const firstPageRows = rows.slice(0, 20)
  return (
    <>
      {/*

            {JSON.stringify(
              {
                pageIndex,
                pageSize,
                pageCount,
                canNextPage,
                canPreviousPage,
              },
              null,
              2
            )}

 */}
      <GlobalFilter
        preGlobalFilteredRows={preGlobalFilteredRows}
        globalFilter={state.globalFilter}
        setGlobalFilter={setGlobalFilter}
      />

          {headerGroups.map(headerGroup => (

              {headerGroup.headers.map(column => (

                  {column.render('Header')}
                  {/* Add a sort direction indicator */}
                  <Grid
                    container
                    direction="row"
                    justifyContent='flex-end'
                    alignItems='flex-end'
                  >
                    <Grid
                      container
                      direction='row'
                      justifyContent="flex-end"
                      alignItems="flex-end"
                      sx={{ mt: -4.9, ml: 4 }}
                    >
                      {
                        column.isSorted ?
                          column.isSortedDesc
                            ? <ArrowDropUpOutlinedIcon color='white' sx={{ mb: 1 }} />
                            : <ArrowDropDownOutlinedIcon color='white' />
                          : ''
                      }
                    </Grid>
                  </Grid>

{column.canFilter ? column.render('Filter') : null}

              ))}

          ))}

          {page.map((row, i) => {
            prepareRow(row)
            return (

                {row.cells.map(cell => {
                  return ({cell.render('Cell')}	)
                })}

            )
          })}

      {/*
          Pagination can be built however you'd like.
          This is just a very basic UI implementation:
        */}
      <Grid
        container
        className="pagination"
        sx={{ ml: 42 }}
      >
        <Grid>
          <MDBTypography fontWeight="regular" fontSize="xxs" lineHeight='md' sx={{ mt: 1 }}>
            Page{' '}
            {/*  */}
            {pageIndex + 1} of {pageOptions.length} |
            {/* {' '} */}
          </MDBTypography>
        </Grid>
        <Grid sx={{ ml: 1, mt: -0.4 }}>
          <button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>
            {'<<'}
          </button>{' '}
          <button onClick={() => previousPage()} disabled={!canPreviousPage}>
            {'<'}
          </button>{' '}
          <button onClick={() => nextPage()} disabled={!canNextPage}>
            {'>'}
          </button>{' '}
          <button onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage}>
            {'>>'}
          </button>{' '}
        </Grid>
        {/*
            | Go to page:{' '}
            <input
              type="number"
              defaultValue={pageIndex + 1}
              onChange={e => {
                const page = e.target.value ? Number(e.target.value) - 1 : 0
                gotoPage(page)
              }}
              style={{ width: '100px' }}
            />
          {' '}
          <select
            value={pageSize}
            onChange={e => {
              setPageSize(Number(e.target.value))
            }}
          >
            {[10, 20, 30, 40, 50].map(pageSize => (
              <option key={pageSize} value={pageSize}>
                Show {pageSize}
              </option>
            ))}
          </select> */}
      </Grid>
    </>
  )
}
function filterGreaterThan(rows, id, filterValue) {
  return rows.filter(row => {
    const rowValue = row.values[id]
    return rowValue >= filterValue
  })
}

function App() {
  const [isOpen, setIsOpen] = useState(false);
  const handleOpen = () => {
    console.log('This is a test')
    setIsOpen(true);
  }
  const handleClose = () => setIsOpen(false);

  const columns = React.useMemo(
    () => [
      {
        Header: <MDBTypography sx={{ mr: 2 }}>First Name</MDBTypography>,
        accessor: 'firstName',
      },
      {
        Header: <MDBTypography sx={{ mr: 2 }}>Last Name</MDBTypography>,
        accessor: 'lastName',
        filter: 'fuzzyText'
      },
      {
        Header: <MDBTypography sx={{ mr: 2 }}>Age</MDBTypography>,
        accessor: 'age',
        Filter: SliderColumnFilter,
        filter: 'equals'
      },
      {
        Header: <MDBTypography sx={{ mr: 2 }}>Visits</MDBTypography>,
        accessor: 'visits',
        filter: filterGreaterThan,
        Filter: NumberRangeColumnFilter,
        filter: 'between',
      },
      {
        Header: <MDBTypography sx={{ mr: 2 }}>Status</MDBTypography>,
        accessor: 'status',
        Filter: SelectColumnFilter,
        filter: 'includes',
      },
      {
        Header: <MDBTypography sx={{ mr: 2 }}>Profile Progress</MDBTypography>,
        accessor: 'progress',
        Filter: SliderColumnFilter,
        filter: filterGreaterThan,
      },
      {
        Header: <MDBTypography sx={{ mr: 2 }}>Edit</MDBTypography>,
        accessor: 'edit',

        Cell: ({ value }) => (
          <Grid
            container
            justifyContent="space-between">
            <MDBButton variant="outlined" onClick={() => handleEdit(value)}>Edit</MDBButton>
            <MDBButton variant="outlined" sx={{ backgroundColor: "red" }} onClick={handleOpen}>Delrte</MDBButton>
            <Modal
              // open={isOpen}
              // onClose={handleClose}
              aria-labelledby="modal-modal-title"
              aria-describedby="modal-modal-description"
            >
              <MDBCard bgcolor="black"  >
                Are You Sure :
                <MDBButton>
                  Yes
                </MDBButton>
                <MDBButton onClick={handleClose}>
                  No
                </MDBButton>
              </MDBCard>
            </Modal>
          </Grid>
        )
      },
    ],
    []
  )

  function handleEdit(row) {
    console.log(row);
  }
  function HandleDelete(row) {
    console.log(row)
    setIsOpen(true)
    console.log("Set is open done")
  }

  const data = React.useMemo(() => makeData(100).map((item) => ({ ...item, edit: item })))
  return (

  )
}

export default App


来源: stackexchange

问:
Databricks Delta - Error: Overlapping auth mechanisms using deltaTable.detail()
In Azure Databricks. I have a unity catalog metastore created on ADLS on its own container (metastore@stgacct.dfs.core.windows.net/) connected w/ the Azure identity. Works fine.

I have a container on the same storage account called data. I'm using Notebook-scoped creds to gain access to that container. Using abfss://data@stgacct... Works fine.

Using the python Delta API, I'm creating an object for my DeltaTable using: deltaTable = DeltaTable.forName(spark, "mycat.myschema.mytable"). I'm able to perform normal Delta functions using that object like MERGE. Works fine.

However, if I attempt to run the deltaTable.detail() command, I get the error: "Your query is attempting to access overlapping paths through multiple authorization mechanisms, which is not currently supported."

It's as if Spark doesn't know which credential to use to fulfill the .detail() command; the metastore identity or the SPN I used when I scoped my creds for the data container - which also has rights to the metastore container.

To test: If I restart my cluster, which drops the spark conf for ADLS, and I attempt to run the command deltaTable = DeltaTable.forName(spark, "mycat.myschema.mytable") and then deltaTable.detail(), I get the error "Failure to initialize configurationInvalid configuration value detected for fs.azure.account.key" - as if it's not using the metastore credentials which I would have expected since it's a unity/managed table (??).

Suggestions?

ContentLicense: CC BY-SA 4.0


问:
How do I play a game I've coded on pycharm using pygame onto retropi?
Good evening,
I was wondering how to move a game from pygame to retropi software to be used with the picade? Also, how would I incorporate the game controls (buttons instead of keys) in my program to assure it is compatible if I can move it over.
Many thanks,
Quantum Cat

I have researched into uploading games using a USB in ROM, not sure if I could do this with my own code? Im a little bit of a newbie :)


问:
pyspark - parallelize train-val-test splits for timeseries data non-randomly
I have a dataframe for multiple customers (6,000+) each having 3 years worth of timeseries data. I'm using pyspark and would like to split each customer's data into training, validation and testing dataset and recombine each of them separately.

For example, this is the dataset I have,

Customer
Customer data
DateTime

A
1111
2010-01-01 00:00:00

A
...
...

A
4590
2012-12-31 23:00:00

B
9935
2010-01-01 00:00:00

B
...
...

B
2387
2012-12-31 23:00:00

C
...
...

And, here is a short pseudocode of what I aim to achieve,

```<code>train_total, val_total, test_total = pyspark dataframe, pyspark dataframe, pyspark dataframe
for customer in customers:
    df_filtered = df.filter(df.Customer == customer)
    train, val, test = split_train_val_test(df_filtered) # split non-randomly
    train_total += train
    val_total += val
    test_total += test
</code>```

How can I parallelize this operation to make it run faster? Or would it make more sense to use partitionBy() on the Customer column, save each customers data in a different file, re-read and then perform the splits?

Is there any inbuilt pyspark function that splits a dataframe into train, val and test non-randomly?

Body:
I have a dataframe for multiple customers (6,000+) each having 3 years worth of timeseries data. I'm using pyspark and would like to split each customer's data into training, validation and testing dataset and recombine each of them separately.

For example, this is the dataset I have,

Customer
Customer data
DateTime

A
1111
2010-01-01 00:00:00

A
...
...

A
4590
2012-12-31 23:00:00

B
9935
2010-01-01 00:00:00

B
...
...

B
2387
2012-12-31 23:00:00

C
...
...

And, here is a short pseudocode of what I aim to achieve,

train_total, val_total, test_total = pyspark dataframe, pyspark dataframe, pyspark dataframe
for customer in customers:
    df_filtered = df.filter(df.Customer == customer)
    train, val, test = split_train_val_test(df_filtered) # split non-randomly
    train_total += train
    val_total += val
    test_total += test

How can I parallelize this operation to make it run faster? Or would it make more sense to use partitionBy() on the Customer column, save each customers data in a different file, re-read and then perform the splits?

Is there any inbuilt pyspark function that splits a dataframe into train, val and test non-randomly?


问:
Upload PDF with Next.js api route
I'm sending a PDF upload as part of a payload to an in-house tool that is separate from my Next.js application through an API route. I'm having trouble getting the FileList to upload correctly. It's part of a form built with react-hook-form, I'm appending the pdf to formData, and it's being correctly converted to a binary that submits to the API route. However, the API hangs and doesn't do anything. This is what my component looks like:

OnboardingDetails.tsx

```<code>import { ChangeEvent } from 'react';

import { useRouter } from 'next/router';

import { Button, Input, Spinner } from '@vero/ui';
import { useOnboardingStep } from 'client-data/hooks/use-onboarding-step';
import { inferMutationInpu } from 'client-data/utils/trpc';
import { env } from 'env/client.mjs';
import { OnboardingPageProps } from 'pages/onboarding';
import { Controller, useForm } from 'react-hook-form';
import toast from 'react-hot-toast';

type InputType = inferMutationInput<'users.onboarding-details'>;

export const OnboardingDetails = ({
  user,
}: {
  user: OnboardingPageProps['user'];
}) => {
  const router = useRouter();
  useOnboardingStep();

  const {
    handleSubmit,
    register,
    watch,
    control,
    formState: { errors },
  } = useForm<InputType>({
    defaultValues: {
      resume: null,
    },
  });

  const onSubmit = async (values: InputType) => {
    if (!values.resume) {
      toast.error(`Resume is required.`);
      return;
    }

    const formData = new FormData();
    formData.append('resume', values.resume);

    await fetch(`/api/upload-user`, {
      method: 'POST',
      body: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  };

  return (
    <>
      <h3 className="m-0 p-0 text-3xl">What are your contact details?</h3>
      <form
        className="flex w-full flex-col gap-6"
        onSubmit={handleSubmit(onSubmit)}
      >
        <Controller
          name="resume"
          control={control}
          defaultValue={null}
          render={({ field }) => (
            <Input
              showLabel
              label="Resume"
              type="file"
              onChange={(e) => {
                field.onChange(e.target.files);
              }}
            />
          )}
        />
        <Button
          type="submit"
          className="btn-primary"
          disabled={isLoading}
          icon={isLoading && <Spinner />}
        >
          Next
        </Button>
      </form>
    </>
  );
};

</code>```

Like I said, when I submit the form I'm able to see the pdf that I upload converted to a binary, but I don't receive a response; this is what my API route looks like:

upload-user.ts

```<code>import type { NextApiRequest, NextApiResponse } from 'next';

import { authOptions } from './auth/[...nextauth]';

import { getServerSession } from '@vero/lib/auth';
import { prisma } from '@vero/prisma';
import { uploadUser } from '@vero/rater';
import { env } from 'env/server.mjs';

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  const body = req.body;

  const session = await getServerSession({ req, res }, authOptions);

  try {
    if (req.method !== 'POST') {
      res.status(405).json({ error: 'Method Not Allowed' });
      return;
    }

    if (!session) {
      res.status(401).json({ error: 'Unauthorized' });
      return;
    }

    const user = await prisma.user.findUnique({
      where: {
        id: session.user.id,
      },
      select: {
        id: true,
        name: true,
        email: true,
        recruit: {
          select: {
            github_username: true,
          },
        },
      },
    });

    if (!user) {
      res.status(401).json({ error: 'Unauthorized' });
      return;
    }

    await uploadUser({
      apiKey: env.RATER_API_KEY,
      baseUrl: env.RATER_API,
      userEmail: user.email as string,
      userName: user.name as string,
      usernameList: user?.recruit?.github_username as string,
      userId: user.id,
      runAll: true,
      resume: body.resume[0],
    });

    res.status(200).json({ success: true });
  } catch (error) {
    res.status(500).json({ success: false, error });
  }
};

export default handler;
</code>```

And then, my uploadUser function:

```<code>import axios from 'axios';
import FormData from 'form-data';
import fs from 'fs';
import { z } from 'zod';

const UploadUserInput = z.object({
  apiKey: z.string(),
  baseUrl: z.string().url(),
  usernameList: z.string(),
  userEmail: z.string(),
  userName: z.string(),
  userId: z.string(),
  resume: z.any().optional(),
  runAll: z.boolean(),
});

const GetUsernameFromIdInput = z.object({
  accountId: z.string(),
});

export const getUsernameFromId = async (args: { accountId: string }) => {
  const { accountId } = GetUsernameFromIdInput.parse(args);

  const res = await fetch(`https://api.github.com/user/${accountId}`);

  const userData = await res.json();

  return userData.login;
};

export const uploadUser = async (args: {
  apiKey: string;
  baseUrl: string;
  usernameList: string;
  userEmail: string;
  userName: string;
  runAll: boolean;
  userId: string;
  resume?: File;
}) => {
  const {
    apiKey,
    baseUrl,
    usernameList,
    userEmail,
    userName,
    runAll,
    userId,
    resume,
  } = UploadUserInput.parse(args);

  const data = new FormData();
  data.append('username_list', usernameList);
  data.append('user_email', userEmail);
  data.append('user_name', userName);
  data.append('school_user_id', userId);
  data.append('resume', resume);

  const config = {
    method: 'post',
    url: `${baseUrl}/api/upload-user/?runAllScrapers=${runAll}`,
    headers: {
      Authorization: apiKey,
    },
    data: data,
  };

  return await axios(config);
};

</code>```

To clarify, I need to be able to submit the PDF upload from the client to the server, then send the data to our external tool. I'm receiving the binary from the client, and am even able to log it in the req.body, but I can't do anything with it beyond that. It just makes the API route hang up.

Title: Upload PDF with Next.js api route

Body:
I'm sending a PDF upload as part of a payload to an in-house tool that is separate from my Next.js application through an API route. I'm having trouble getting the FileList to upload correctly. It's part of a form built with react-hook-form, I'm appending the pdf to formData, and it's being correctly converted to a binary that submits to the API route. However, the API hangs and doesn't do anything. This is what my component looks like:

OnboardingDetails.tsx

import { ChangeEvent } from 'react';

import { useRouter } from 'next/router';

import { Button, Input, Spinner } from '@vero/ui';
import { useOnboardingStep } from 'client-data/hooks/use-onboarding-step';
import { inferMutationInpu } from 'client-data/utils/trpc';
import { env } from 'env/client.mjs';
import { OnboardingPageProps } from 'pages/onboarding';
import { Controller, useForm } from 'react-hook-form';
import toast from 'react-hot-toast';

type InputType = inferMutationInput<'users.onboarding-details'>;

export const OnboardingDetails = ({
  user,
}: {
  user: OnboardingPageProps['user'];
}) => {
  const router = useRouter();
  useOnboardingStep();

  const {
    handleSubmit,
    register,
    watch,
    control,
    formState: { errors },
  } = useForm<InputType>({
    defaultValues: {
      resume: null,
    },
  });

  const onSubmit = async (values: InputType) => {
    if (!values.resume) {
      toast.error(`Resume is required.`);
      return;
    }

    const formData = new FormData();
    formData.append('resume', values.resume);

    await fetch(`/api/upload-user`, {
      method: 'POST',
      body: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  };

  return (
    <>

What are your contact details?

      <form
        className="flex w-full flex-col gap-6"
        onSubmit={handleSubmit(onSubmit)}
      >
        <Controller
          name="resume"
          control={control}
          defaultValue={null}
          render={({ field }) => (
            <Input
              showLabel
              label="Resume"
              type="file"
              onChange={(e) => {
                field.onChange(e.target.files);
              }}
            />
          )}
        />
        <Button
          type="submit"
          className="btn-primary"
          disabled={isLoading}
          icon={isLoading && <Spinner />}
        >
          Next
        </Button>
      </form>
    </>
  );
};

Like I said, when I submit the form I'm able to see the pdf that I upload converted to a binary, but I don't receive a response; this is what my API route looks like:

upload-user.ts

import type { NextApiRequest, NextApiResponse } from 'next';

import { authOptions } from './auth/[...nextauth]';

import { getServerSession } from '@vero/lib/auth';
import { prisma } from '@vero/prisma';
import { uploadUser } from '@vero/rater';
import { env } from 'env/server.mjs';

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  const body = req.body;

  const session = await getServerSession({ req, res }, authOptions);

  try {
    if (req.method !== 'POST') {
      res.status(405).json({ error: 'Method Not Allowed' });
      return;
    }

    if (!session) {
      res.status(401).json({ error: 'Unauthorized' });
      return;
    }

    const user = await prisma.user.findUnique({
      where: {
        id: session.user.id,
      },
      select: {
        id: true,
        name: true,
        email: true,
        recruit: {
          select: {
            github_username: true,
          },
        },
      },
    });

    if (!user) {
      res.status(401).json({ error: 'Unauthorized' });
      return;
    }

    await uploadUser({
      apiKey: env.RATER_API_KEY,
      baseUrl: env.RATER_API,
      userEmail: user.email as string,
      userName: user.name as string,
      usernameList: user?.recruit?.github_username as string,
      userId: user.id,
      runAll: true,
      resume: body.resume[0],
    });

    res.status(200).json({ success: true });
  } catch (error) {
    res.status(500).json({ success: false, error });
  }
};

export default handler;

And then, my uploadUser function:

import axios from 'axios';
import FormData from 'form-data';
import fs from 'fs';
import { z } from 'zod';

const UploadUserInput = z.object({
  apiKey: z.string(),
  baseUrl: z.string().url(),
  usernameList: z.string(),
  userEmail: z.string(),
  userName: z.string(),
  userId: z.string(),
  resume: z.any().optional(),
  runAll: z.boolean(),
});

const GetUsernameFromIdInput = z.object({
  accountId: z.string(),
});

export const getUsernameFromId = async (args: { accountId: string }) => {
  const { accountId } = GetUsernameFromIdInput.parse(args);

  const res = await fetch(`https://api.github.com/user/${accountId}`);

  const userData = await res.json();

  return userData.login;
};

export const uploadUser = async (args: {
  apiKey: string;
  baseUrl: string;
  usernameList: string;
  userEmail: string;
  userName: string;
  runAll: boolean;
  userId: string;
  resume?: File;
}) => {
  const {
    apiKey,
    baseUrl,
    usernameList,
    userEmail,
    userName,
    runAll,
    userId,
    resume,
  } = UploadUserInput.parse(args);

  const data = new FormData();
  data.append('username_list', usernameList);
  data.append('user_email', userEmail);
  data.append('user_name', userName);
  data.append('school_user_id', userId);
  data.append('resume', resume);

  const config = {
    method: 'post',
    url: `${baseUrl}/api/upload-user/?runAllScrapers=${runAll}`,
    headers: {
      Authorization: apiKey,
    },
    data: data,
  };

  return await axios(config);
};

To clarify, I need to be able to submit the PDF upload from the client to the server, then send the data to our external tool. I'm receiving the binary from the client, and am even able to log it in the req.body, but I can't do anything with it beyond that. It just makes the API route hang up.


问:
How to add sets and reps to Exercise collection in Firebase Firestore
Perhaps, I am not asking the correct question, this has been the issue for me (not fully understanding the problem), and Im not actually sure what it is that Im trying to ask or solve exactly, but I will explain my thoughts as best I can.

I am currently trying to create a fitness tracker app. I am currently using firestore database. To keep it simple I just want to be able to select an Exercise (i.e bench press), and then have sets attached, with reps and the amount of weight inside the reps category.  Currently I am thinking about it as...

Collection: "Exercises"

Documents:
Field: Name: Bench Press
Field: Muscle Group: Chest

I would like to be able to select the Exercise name, and then prompt the user to individual sets that have fields that accept a number for the weight (lbs) and reps.  I would like the numerical fields to have default values of null or 0 since the application is awaiting on that data to be entered by the user.  Any help would be greatly appreciated as this is my first web app project I am building in React.


问:
QScintilla syntax highlighting with QsciLexerCustom - UTF-8 issue with german characters
Much like this related question, I found myself using QScintilla to create a syntax highlighter that has to deal with non-ASCII characters (é, ä, ß, etc...). I use the trick described in the comments of that question to solve the problem, styling the characters base on the length of the utf-8 bytes rather than the Latin-1 bytes. When styling the entire document, it works fine.

However, my issue arises when using the start/end parameters to only style part of the document as there seems to be a mismatch between the start/end parameters and the actual length of the text being styled. I need to use this as I am dealing with large files that cause a 1-2 second input delay if I continuously style the entire document.

I have the following very simple example:

```<code>é

; Comment
</code>```

When I open the file, which runs the highlighter from start to finish it looks like that:

However, if I remove and re-type the comment, the colouring will always be one letter off.

This effect stacks indefinitely, with every non-ASCII character, the colouring goes off by another letter until it is a mess.

I have provided a minimal reproducible example below. All you have to do to notice the problem is start a comment below the last line, you will notice that your styling is always one off.

import sys
from PyQt6.QtWidgets import *
from PyQt6.QtCore import *
from PyQt6.QtGui import *
from PyQt6.Qsci import *
import re

class MyLexer(QsciLexerCustom):
    def __init__(self, parent):
        super(MyLexer, self).__init__(parent)
        self.setDefaultColor(QColor("#ff000000"))
        self.setDefaultPaper(QColor("#ffffffff"))
        self.setDefaultFont(QFont("Consolas", 14))

        self.setColor(QColor("#ff000000"), 0)   # Style 0: black
        self.setColor(QColor("#ff007f00"), 3)   # Style 3: green

        self.setPaper(QColor("#ffffffff"), 0)   # Style 0: white
        self.setPaper(QColor("#ffffffff"), 3)   # Style 3: white

        self.setFont(QFont("Consolas", 14, weight=QFont.Weight.Bold), 0)   # Style 0: Consolas 14pt
        self.setFont(QFont("Consolas", 14, weight=QFont.Weight.Bold), 3)   # Style 3: Consolas 14pt

    def language(self):
        return "SimpleLanguage"

    def description(self, style):
        return str(style)

    def styleText(self, start, end):
        self.startStyling(start)
        text = self.parent().text()[start:end]
        p = re.compile(r"[*]\/|\/[*]|\s+|\w+|\W")

        token_list = [ (token, len(bytearray(token, "utf-8"))) for token in p.findall(text)]

        editor = self.parent()
        apply_until_linebreak = None
        if start > 0:
            previous_style_nr = editor.SendScintilla(editor.SCI_GETSTYLEAT, start - 1)
            if previous_style_nr in [2, 3]:
                apply_until_linebreak = previous_style_nr

        for i, token in enumerate(token_list):
            if apply_until_linebreak is not None:
                if "\n" in token[0]:
                    apply_until_linebreak = None
                    self.setStyling(token[1], 0)
                else:
                    self.setStyling(token[1], apply_until_linebreak)
            else:
                if token[0] in ["/", ";"]:
                    apply_until_linebreak = 3
                    self.setStyling(token[1], 3)
                else:
                    self.setStyling(token[1], 0)

myCodeSample = r"""
This is white

// This is a green comment

This is white again

// This comment has a (ä) special character
"""

class CustomMainWindow(QMainWindow):
    def __init__(self):
        super(CustomMainWindow, self).__init__()
        self.setGeometry(300, 300, 800, 400)
        self.setWindowTitle("QScintilla Test")

        self.__frm = QFrame(self)
        self.__frm.setStyleSheet("QWidget { background-color: #ffeaeaea }")
        self.__lyt = QVBoxLayout()
        self.__frm.setLayout(self.__lyt)
        self.setCentralWidget(self.__frm)
        self.__myFont = QFont()
        self.__myFont.setPointSize(14)

        self.__editor = QsciScintilla()
        self.__editor.setText(myCodeSample)
        self.__editor.setLexer(None)            # We install lexer later
        self.__editor.setUtf8(True)             # Set encoding to UTF-8
        self.__editor.setFont(self.__myFont)    # Gets overridden by lexer later on

        self.__lexer = MyLexer(self.__editor)
        self.__editor.setLexer(self.__lexer)

        self.__lyt.addWidget(self.__editor)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    QApplication.setStyle(QStyleFactory.create('Fusion'))
    myGUI = CustomMainWindow()
    sys.exit(app.exec())
```

Body:
Much like this related question, I found myself using QScintilla to create a syntax highlighter that has to deal with non-ASCII characters (é, ä, ß, etc...). I use the trick described in the comments of that question to solve the problem, styling the characters base on the length of the utf-8 bytes rather than the Latin-1 bytes. When styling the entire document, it works fine.

However, my issue arises when using the start/end parameters to only style part of the document as there seems to be a mismatch between the start/end parameters and the actual length of the text being styled. I need to use this as I am dealing with large files that cause a 1-2 second input delay if I continuously style the entire document.

I have the following very simple example:

é

; Comment

When I open the file, which runs the highlighter from start to finish it looks like that:

However, if I remove and re-type the comment, the colouring will always be one letter off.

This effect stacks indefinitely, with every non-ASCII character, the colouring goes off by another letter until it is a mess.

I have provided a minimal reproducible example below. All you have to do to notice the problem is start a comment below the last line, you will notice that your styling is always one off.

import sys
from PyQt6.QtWidgets import *
from PyQt6.QtCore import *
from PyQt6.QtGui import *
from PyQt6.Qsci import *
import re

class MyLexer(QsciLexerCustom):
    def __init__(self, parent):
        super(MyLexer, self).__init__(parent)
        self.setDefaultColor(QColor("#ff000000"))
        self.setDefaultPaper(QColor("#ffffffff"))
        self.setDefaultFont(QFont("Consolas", 14))

        self.setColor(QColor("#ff000000"), 0)   # Style 0: black
        self.setColor(QColor("#ff007f00"), 3)   # Style 3: green

        self.setPaper(QColor("#ffffffff"), 0)   # Style 0: white
        self.setPaper(QColor("#ffffffff"), 3)   # Style 3: white

        self.setFont(QFont("Consolas", 14, weight=QFont.Weight.Bold), 0)   # Style 0: Consolas 14pt
        self.setFont(QFont("Consolas", 14, weight=QFont.Weight.Bold), 3)   # Style 3: Consolas 14pt

    def language(self):
        return "SimpleLanguage"

    def description(self, style):
        return str(style)

    def styleText(self, start, end):
        self.startStyling(start)
        text = self.parent().text()[start:end]
        p = re.compile(r"[*]\/|\/[*]|\s+|\w+|\W")

        token_list = [ (token, len(bytearray(token, "utf-8"))) for token in p.findall(text)]

        editor = self.parent()
        apply_until_linebreak = None
        if start > 0:
            previous_style_nr = editor.SendScintilla(editor.SCI_GETSTYLEAT, start - 1)
            if previous_style_nr in [2, 3]:
                apply_until_linebreak = previous_style_nr

        for i, token in enumerate(token_list):
            if apply_until_linebreak is not None:
                if "\n" in token[0]:
                    apply_until_linebreak = None
                    self.setStyling(token[1], 0)
                else:
                    self.setStyling(token[1], apply_until_linebreak)
            else:
                if token[0] in ["/", ";"]:
                    apply_until_linebreak = 3
                    self.setStyling(token[1], 3)
                else:
                    self.setStyling(token[1], 0)

myCodeSample = r"""
This is white

// This is a green comment

This is white again

// This comment has a (ä) special character
"""

class CustomMainWindow(QMainWindow):
    def __init__(self):
        super(CustomMainWindow, self).__init__()
        self.setGeometry(300, 300, 800, 400)
        self.setWindowTitle("QScintilla Test")

        self.__frm = QFrame(self)
        self.__frm.setStyleSheet("QWidget { background-color: #ffeaeaea }")
        self.__lyt = QVBoxLayout()
        self.__frm.setLayout(self.__lyt)
        self.setCentralWidget(self.__frm)
        self.__myFont = QFont()
        self.__myFont.setPointSize(14)

        self.__editor = QsciScintilla()
        self.__editor.setText(myCodeSample)
        self.__editor.setLexer(None)            # We install lexer later
        self.__editor.setUtf8(True)             # Set encoding to UTF-8
        self.__editor.setFont(self.__myFont)    # Gets overridden by lexer later on

        self.__lexer = MyLexer(self.__editor)
        self.__editor.setLexer(self.__lexer)

        self.__lyt.addWidget(self.__editor)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    QApplication.setStyle(QStyleFactory.create('Fusion'))
    myGUI = CustomMainWindow()
    sys.exit(app.exec())


问:
Inserting data into a stats table with merge - An action of type 'INSERT' is not allowed in the 'WHEN MATCHED' clause of a MERGE statement
I have two tables

The first table

```<code>stats {
Id,
stat1 decimal,
stat2 decimal,
stat3 decimal,
[LastChangeDate] datetime2
}
</code>```

The second table

```<code>statsHistory {
Id,
stat1 decimal,
stat2 decimal,
stat3 decimal,
[LastChangeDate] datetime2
DateGenerated Date
}
</code>```

The statsHistory table is designed to be a caching of the daily stats data to reduce the recalculation of the daily stats based on session data.

I'm trying to use a merge statement to pull the data from the stats table into the statsHistory table. I intend to have this stored procedure called nightly at a set time.

```<code>;WITH C1 AS (
  SELECT
    ROW_NUMBER() OVER(PARTITION BY uc.Id ORDER BY [DayDateGenerated] DESC) as rowNumber,
        uc.[Id]
      ,uc.[stat1]
      ,uc.[stat2]
      ,uc.[stat3]
      ,UCH.DayDateGenerated
UCH.[stat1]
      ,UCH.[stat2]
      ,UCH.[stat3]

  FROM
  [UserConcepts] as uc
  LEFT OUTER JOIN [UserConceptsDayHistory] as UCH on
  UCH.[MemberId] = uc.[MemberId] AND UCH.[ForConceptId] = uc.[MemberId]
)

Merge [UserConceptsDayHistory] AS TARGET
  USING(
    select * from C1
    WHERE rowNumber = 1
    --AND CONVERT(DATE,[LastChangeDate]) < CONVERT(DATE,DateAdd(GetUtcDAte(),-1))
  ) AS source
  ON(target.[MemberId] = source.[MemberId] AND target.[ForConceptId] = source.[ForConceptId])
  WHEN not MATCHED THEN
        insert(stat1
      ,stat2
      ,stat3
      ,[LastChangeDate]
      ,DateGenerated
)
      values
      (source.stat1
      ,source.stat2
      ,source.stat3
      ,source.[LastChangeDate]
      ,source.[LastChangeDate]
      )
     WHEN  MATCHED  AND  source.DayDateGenerated = target.DayDateGenerated AND source.[TotalSessions] != target.[TotalSessions] THEN
     update SET
     stat1 = source.stat1
      ,stat2= source.stat2 - target.stat3
      ,stat3  = source.stat3
      ,[LastChangeDate]  = source.[LastChangeDate],
    DateGenerated = source.[LastChangeDate]

       WHEN  MATCHED  AND  source.DayDateGenerated IS NOT NULL  AND  source.DayDateGenerated != target.DayDateGenerated THEN
        insert(stat1
      ,stat2
      ,stat3
      ,[LastChangeDate]
      ,DateGenerated
)
      values
      (source.stat1
      ,source.stat2 - target.stat3
      ,source.stat3
      ,source.[LastChangeDate]
      ,source.[LastChangeDate]
      )

      OUTPUT $action, inserted.*, deleted.*;
</code>```

As the history table could have many rows I had hoped to have conditional match cases where I could insert where a row existed in the table but not for that date, however, I get the following SQL error:

An action of type 'INSERT' is not allowed in the 'WHEN MATCHED' clause of a MERGE statement

I understand that I cannot achieve what I was hoping for with the merge statement, however, was wondering if there are any good alternative approaches to this issue.

Any help would be gratefully appreciated.

Body:
I have two tables

The first table

stats {
Id,
stat1 decimal,
stat2 decimal,
stat3 decimal,
[LastChangeDate] datetime2
}

The second table

statsHistory {
Id,
stat1 decimal,
stat2 decimal,
stat3 decimal,
[LastChangeDate] datetime2
DateGenerated Date
}

The statsHistory table is designed to be a caching of the daily stats data to reduce the recalculation of the daily stats based on session data.

I'm trying to use a merge statement to pull the data from the stats table into the statsHistory table. I intend to have this stored procedure called nightly at a set time.

;WITH C1 AS (
  SELECT
    ROW_NUMBER() OVER(PARTITION BY uc.Id ORDER BY [DayDateGenerated] DESC) as rowNumber,
        uc.[Id]
      ,uc.[stat1]
      ,uc.[stat2]
      ,uc.[stat3]
      ,UCH.DayDateGenerated
UCH.[stat1]
      ,UCH.[stat2]
      ,UCH.[stat3]

  FROM
  [UserConcepts] as uc
  LEFT OUTER JOIN [UserConceptsDayHistory] as UCH on
  UCH.[MemberId] = uc.[MemberId] AND UCH.[ForConceptId] = uc.[MemberId]
)

Merge [UserConceptsDayHistory] AS TARGET
  USING(
    select * from C1
    WHERE rowNumber = 1
    --AND CONVERT(DATE,[LastChangeDate]) < CONVERT(DATE,DateAdd(GetUtcDAte(),-1))
  ) AS source
  ON(target.[MemberId] = source.[MemberId] AND target.[ForConceptId] = source.[ForConceptId])
  WHEN not MATCHED THEN
        insert(stat1
      ,stat2
      ,stat3
      ,[LastChangeDate]
      ,DateGenerated
)
      values
      (source.stat1
      ,source.stat2
      ,source.stat3
      ,source.[LastChangeDate]
      ,source.[LastChangeDate]
      )
     WHEN  MATCHED  AND  source.DayDateGenerated = target.DayDateGenerated AND source.[TotalSessions] != target.[TotalSessions] THEN
     update SET
     stat1 = source.stat1
      ,stat2= source.stat2 - target.stat3
      ,stat3  = source.stat3
      ,[LastChangeDate]  = source.[LastChangeDate],
    DateGenerated = source.[LastChangeDate]

       WHEN  MATCHED  AND  source.DayDateGenerated IS NOT NULL  AND  source.DayDateGenerated != target.DayDateGenerated THEN
        insert(stat1
      ,stat2
      ,stat3
      ,[LastChangeDate]
      ,DateGenerated
)
      values
      (source.stat1
      ,source.stat2 - target.stat3
      ,source.stat3
      ,source.[LastChangeDate]
      ,source.[LastChangeDate]
      )

      OUTPUT $action, inserted.*, deleted.*;

As the history table could have many rows I had hoped to have conditional match cases where I could insert where a row existed in the table but not for that date, however, I get the following SQL error:

An action of type 'INSERT' is not allowed in the 'WHEN MATCHED' clause of a MERGE statement

I understand that I cannot achieve what I was hoping for with the merge statement, however, was wondering if there are any good alternative approaches to this issue.

Any help would be gratefully appreciated.


问:
compute timeseries with values from a column of a pandas dataframe
I have two dataframes df_t with columns: id, user_id, timestamp score and df_u with column user_id. A user_id in df_t may be repeated while it is unique in df_u. I want to compute a timeseries for each user_id of length 365, one step for each day of the year 2019. Each timestep needs to have the score of the user_id on that day. In df_t I can have timestamp before and after the 2019 and also there are missing days in 2019, I need to insert this day with a score o -1 on the timeseries.

So this is the code

```<code>import pandas as pd
import numpy as np

df_t = pd.DataFrame({'id': [1, 2, 3, 4],
                    'user_id': [1, 2, 2, 2],
                    'timestamp': ["2012-01-01", "2019-01-20", "2019-04-03", "2019-05-01"],
                    'score': [1, 3, 3, 4]
})
print(df_t)
df_u = pd.DataFrame({'user_id': [1, 2]})
print(df_u)

df_u_expected = pd.DataFrame({'user_id': [1, 2],
                              'scores_list':[
                                  ["list of 365 '-1' since it does not have any score in 2019"],
                                  ["-1, ..., 3, ... 3, ..., 4 ..., -1, ..."]
                              ]
})
print(df_u_expected)
</code>```

Any idea on how to do this?

Body:
I have two dataframes df_t with columns: id, user_id, timestamp score and df_u with column user_id. A user_id in df_t may be repeated while it is unique in df_u. I want to compute a timeseries for each user_id of length 365, one step for each day of the year 2019. Each timestep needs to have the score of the user_id on that day. In df_t I can have timestamp before and after the 2019 and also there are missing days in 2019, I need to insert this day with a score o -1 on the timeseries.

So this is the code

import pandas as pd
import numpy as np

df_t = pd.DataFrame({'id': [1, 2, 3, 4],
                    'user_id': [1, 2, 2, 2],
                    'timestamp': ["2012-01-01", "2019-01-20", "2019-04-03", "2019-05-01"],
                    'score': [1, 3, 3, 4]
})
print(df_t)
df_u = pd.DataFrame({'user_id': [1, 2]})
print(df_u)

df_u_expected = pd.DataFrame({'user_id': [1, 2],
                              'scores_list':[
                                  ["list of 365 '-1' since it does not have any score in 2019"],
                                  ["-1, ..., 3, ... 3, ..., 4 ..., -1, ..."]
                              ]
})
print(df_u_expected)

Any idea on how to do this?


问:
An error occurred while processing the post-install hook of the Podfile
Hi I'm working with Flutter 2.2.2 and I'm having some issues when i try to run the command pod install
`An error occurred while processing the post-install hook of the Podfile.

[Xcodeproj] Consistency issue: build setting IPHONEOS_DEPLOYMENT_TARGET has multiple values: `{"Release"=>"14.0", "Debug"=>"8.0", "Profile"=>"8.0"}``

I have modified my podfile but the error is the same

```<code># Uncomment this line to define a global platform for your project
 platform :ios, '14.0'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
  use_frameworks!
  use_modular_headers!
pod 'OneSignalXCFramework', '>= 3.0.0', '< 4.0'
pod 'Firebase'
pod 'Firebase/Auth'
pod 'Firebase/Analytics'
pod 'Firebase/Messaging'
pod 'Firebase/Core'
pod 'Firebase/Crashlytics'
pod 'FBSDKLoginKit'
pod 'Branch'
  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end
post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['IPHONEOS_DEPLOYMENT_TARGET']='14.0'
    flutter_additional_ios_build_settings(target)
    end
  end
end
target 'OneSignalNotificationServiceExtension' do
  use_frameworks!
  pod 'OneSignalXCFramework', '>= 3.0.0', '< 4.0'
end

</code>```

Can someone know how to solve it? I have tried many possible solutions but the results are the same, I tried running flutter clean -> pod update -> pod install. I don't know if this helps but I'm also using pod version: 1.11.3

I have run many commands hoping that the app is going to execute but I only have this error.

Body:
Hi I'm working with Flutter 2.2.2 and I'm having some issues when i try to run the command pod install
`An error occurred while processing the post-install hook of the Podfile.

[Xcodeproj] Consistency issue: build setting IPHONEOS_DEPLOYMENT_TARGET has multiple values: `{"Release"=>"14.0", "Debug"=>"8.0", "Profile"=>"8.0"}``

I have modified my podfile but the error is the same

# Uncomment this line to define a global platform for your project
 platform :ios, '14.0'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
  use_frameworks!
  use_modular_headers!
pod 'OneSignalXCFramework', '>= 3.0.0', '< 4.0'
pod 'Firebase'
pod 'Firebase/Auth'
pod 'Firebase/Analytics'
pod 'Firebase/Messaging'
pod 'Firebase/Core'
pod 'Firebase/Crashlytics'
pod 'FBSDKLoginKit'
pod 'Branch'
  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end
post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['IPHONEOS_DEPLOYMENT_TARGET']='14.0'
    flutter_additional_ios_build_settings(target)
    end
  end
end
target 'OneSignalNotificationServiceExtension' do
  use_frameworks!
  pod 'OneSignalXCFramework', '>= 3.0.0', '< 4.0'
end

Can someone know how to solve it? I have tried many possible solutions but the results are the same, I tried running flutter clean -> pod update -> pod install. I don't know if this helps but I'm also using pod version: 1.11.3

I have run many commands hoping that the app is going to execute but I only have this error.


问:
React social media app reverse post order
I made a social media app and this is  my homepage

```<code>import { Box, useMediaQuery } from "@mui/material";
import { useSelector } from "react-redux";
import Navbar from "scenes/navbar";
import UserWidget from "scenes/widgets/UserWidget";
import MyPostWidget from "scenes/widgets/MyPostWidget";
import PostsWidget from "scenes/widgets/PostsWidget";
import AdvertWidget from "scenes/widgets/AdvertWidget";
import FriendListWidget from "scenes/widgets/FriendListWidget";

const HomePage = () => {
  const isNonMobileScreens = useMediaQuery("(min-width:1000px)");
  const { _id, picturePath } = useSelector((state) => state.user);

  return (
    <Box>
      <Navbar />
      <Box
        width="100%"
        padding="2rem 6%"
        display={isNonMobileScreens ? "flex" : "block"}
        gap="0.5rem"
        justifyContent="space-between"
      >
        <Box flexBasis={isNonMobileScreens ? "26%" : undefined}>
          <UserWidget userId={_id} picturePath={picturePath} />
        </Box>
        <Box
          flexBasis={isNonMobileScreens ? "42%" : undefined}
          mt={isNonMobileScreens ? undefined : "2rem"}
        >
          <MyPostWidget picturePath={picturePath} />
          <PostsWidget userId={_id} />
        </Box>
        {isNonMobileScreens && (
          <Box flexBasis="26%">
            <AdvertWidget />
            <Box m="2rem 0" />
            <FriendListWidget userId={_id} />
          </Box>
        )}
      </Box>
    </Box>
  );
};

export default HomePage;
</code>```

and this is my post widget

```<code>import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { setPosts } from "state";
import PostWidget from "./PostWidget";

const PostsWidget = ({ userId, isProfile = false }) => {
  const dispatch = useDispatch();
  const posts = useSelector((state) => state.posts);
  const token = useSelector((state) => state.token);

  const getPosts = async () => {
    const response = await fetch("http://localhost:3001/posts", {
      method: "GET",
      headers: { Authorization: `Bearer ${token}` },
    });
    const data = await response.json();
    dispatch(setPosts({ posts: data }));
  };

  const getUserPosts = async () => {
    const response = await fetch(
      `http://localhost:3001/posts/${userId}/posts`,
      {
        method: "GET",
        headers: { Authorization: `Bearer ${token}` },
      }
    );
    const data = await response.json();
    dispatch(setPosts({ posts: data }));
  };

  useEffect(() => {
    if (isProfile) {
      getUserPosts();
    } else {
      getPosts();
    }
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <>
      {posts.map(
        ({
          _id,
          userId,
          firstName,
          lastName,
          description,
          location,
          picturePath,
          userPicturePath,
          likes,
          comments,
          createdAt,
        }) => (
          <PostWidget
            key={_id}
            postId={_id}
            postUserId={userId}
            name={`${firstName} ${lastName}`}
            description={description}
            location={location}
            picturePath={picturePath}
            userPicturePath={userPicturePath}
            likes={likes}
            comments={comments}
            createdAt={createdAt} // Pass the createdAt field as a prop to the PostWidget component
          />
        )
      )}
    </>
  );
};

export default PostsWidget;
</code>```

when I post new post in my page old posts are staying on top and new posts are going below of the page how can I fix this. its my oldest old post post but it is top . I use mongodb and my posts hase timestamps I want to order with timestamps

Body:
I made a social media app and this is  my homepage

import { Box, useMediaQuery } from "@mui/material";
import { useSelector } from "react-redux";
import Navbar from "scenes/navbar";
import UserWidget from "scenes/widgets/UserWidget";
import MyPostWidget from "scenes/widgets/MyPostWidget";
import PostsWidget from "scenes/widgets/PostsWidget";
import AdvertWidget from "scenes/widgets/AdvertWidget";
import FriendListWidget from "scenes/widgets/FriendListWidget";

const HomePage = () => {
  const isNonMobileScreens = useMediaQuery("(min-width:1000px)");
  const { _id, picturePath } = useSelector((state) => state.user);

  return (
    <Box>
      <Navbar />
      <Box
        width="100%"
        padding="2rem 6%"
        display={isNonMobileScreens ? "flex" : "block"}
        gap="0.5rem"
        justifyContent="space-between"
      >
        <Box flexBasis={isNonMobileScreens ? "26%" : undefined}>
          <UserWidget userId={_id} picturePath={picturePath} />
        </Box>
        <Box
          flexBasis={isNonMobileScreens ? "42%" : undefined}
          mt={isNonMobileScreens ? undefined : "2rem"}
        >
          <MyPostWidget picturePath={picturePath} />
          <PostsWidget userId={_id} />
        </Box>
        {isNonMobileScreens && (
          <Box flexBasis="26%">
            <AdvertWidget />
            <Box m="2rem 0" />
            <FriendListWidget userId={_id} />
          </Box>
        )}
      </Box>
    </Box>
  );
};

export default HomePage;

and this is my post widget

import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { setPosts } from "state";
import PostWidget from "./PostWidget";

const PostsWidget = ({ userId, isProfile = false }) => {
  const dispatch = useDispatch();
  const posts = useSelector((state) => state.posts);
  const token = useSelector((state) => state.token);

  const getPosts = async () => {
    const response = await fetch("http://localhost:3001/posts", {
      method: "GET",
      headers: { Authorization: `Bearer ${token}` },
    });
    const data = await response.json();
    dispatch(setPosts({ posts: data }));
  };

  const getUserPosts = async () => {
    const response = await fetch(
      `http://localhost:3001/posts/${userId}/posts`,
      {
        method: "GET",
        headers: { Authorization: `Bearer ${token}` },
      }
    );
    const data = await response.json();
    dispatch(setPosts({ posts: data }));
  };

  useEffect(() => {
    if (isProfile) {
      getUserPosts();
    } else {
      getPosts();
    }
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <>
      {posts.map(
        ({
          _id,
          userId,
          firstName,
          lastName,
          description,
          location,
          picturePath,
          userPicturePath,
          likes,
          comments,
          createdAt,
        }) => (
          <PostWidget
            key={_id}
            postId={_id}
            postUserId={userId}
            name={`${firstName} ${lastName}`}
            description={description}
            location={location}
            picturePath={picturePath}
            userPicturePath={userPicturePath}
            likes={likes}
            comments={comments}
            createdAt={createdAt} // Pass the createdAt field as a prop to the PostWidget component
          />
        )
      )}
    </>
  );
};

export default PostsWidget;

when I post new post in my page old posts are staying on top and new posts are going below of the page how can I fix this. its my oldest old post post but it is top . I use mongodb and my posts hase timestamps I want to order with timestamps


问:
"Message: invalid data; odd-length - 0x0" error, solidity or javascript error
We wrote a Smart Contract in Solidity language. It has a function taking a string as one of it's arguments. We also wrote unit tests for the functions. The unit test for a function I mentioned just yet gives an error as follows:

```<code>Message: invalid data; odd-length - 0x0.
</code>```

How can we fix the issue?

We are certain it gives error due to this argument being string because the call doesn't enter the solidity function at all; we did console.log() and it didn't log . We are developing in Remix compiler.

//the call I make from js test code, user_account2 being an address:

```<code>await mygov.connect(user_account2).submitSurvey("abc", 21e6 , 3 , 2);
</code>```

//the function from the solidity smart contract:

```<code>function submitSurvey(string memory ipfshash,uint surveydeadline,uint numchoices, uint atmostchoice) public returns (uint surveyid) {
    User storage owner = users[msg.sender];
    require(isMember(owner), "1");
    require(owner.myGovTokens >=2, "2");
    require(owner.myGovTokens >2  || owner.myGovTokensLockedUntil <= block.timestamp, "3");
    uint[] memory results = new uint[](numchoices) ;

    Survey memory mysurvey = Survey({
                Ipfshash : ipfshash,
                Owner: msg.sender,
                Deadline: surveydeadline,
                SurveyId: surveyid,
                AtmostChoice: atmostchoice,
                NumChoices: numchoices,
                NumTaken : 0,
                Results : results
                });

    transferToken(address(this), 2);
    address payable to_sc = payable(address(this));

    transfer(to_sc, surveyCreationFee);
    donatedWei += surveyCreationFee;

    surveys.push(mysurvey);
    surveyid = surveys.length - 1 ;
    mysurvey.SurveyId = surveyid;
    return (surveyid);
}
</code>```

Body:
We wrote a Smart Contract in Solidity language. It has a function taking a string as one of it's arguments. We also wrote unit tests for the functions. The unit test for a function I mentioned just yet gives an error as follows:

Message: invalid data; odd-length - 0x0.

How can we fix the issue?

We are certain it gives error due to this argument being string because the call doesn't enter the solidity function at all; we did console.log() and it didn't log . We are developing in Remix compiler.

//the call I make from js test code, user_account2 being an address:

await mygov.connect(user_account2).submitSurvey("abc", 21e6 , 3 , 2);

//the function from the solidity smart contract:

function submitSurvey(string memory ipfshash,uint surveydeadline,uint numchoices, uint atmostchoice) public returns (uint surveyid) {
    User storage owner = users[msg.sender];
    require(isMember(owner), "1");
    require(owner.myGovTokens >=2, "2");
    require(owner.myGovTokens >2  || owner.myGovTokensLockedUntil <= block.timestamp, "3");
    uint[] memory results = new uint[](numchoices) ;

    Survey memory mysurvey = Survey({
                Ipfshash : ipfshash,
                Owner: msg.sender,
                Deadline: surveydeadline,
                SurveyId: surveyid,
                AtmostChoice: atmostchoice,
                NumChoices: numchoices,
                NumTaken : 0,
                Results : results
                });

    transferToken(address(this), 2);
    address payable to_sc = payable(address(this));

    transfer(to_sc, surveyCreationFee);
    donatedWei += surveyCreationFee;

    surveys.push(mysurvey);
    surveyid = surveys.length - 1 ;
    mysurvey.SurveyId = surveyid;
    return (surveyid);
}


问:
docker host: use docker dns to resolve container name from host network
I need to resolve a container name to the IP Address from the docker host.

The reason for this is, i need a container to run on the host network, but it must be also able to resolve the container "backend" which it connects also to. (The container must be send & receive multicast packets)

docker-compose.yml

version: "3"
services:

  database:
    image: mongo
    container_name: database
    hostname: database
    ports:
      - "27017:27017"

  backend:
    image: "project/backend:latest"
    container_name: backend
    hostname: backend
    environment:
      - NODE_ENV=production
      - DATABASE_HOST=database
      - UUID=5025f846-7587-11ed-9ca7-8b992b5e7dd3
    ports:
      - "8080:8080"
    depends_on:
      - database
    tty: true

  frontend:
    image: "project/frontend:latest"
    container_name: frontend
    hostname: frontend
    ports:
      - "80:80"
      - "443:443"
    depends_on:
      - backend
    environment:
      - BACKEND_HOST=backend
  connector:
    image: "project/connector:latest"
    container_name: connector
    hostname: connector
    ports:
      - "1900:1900/udp"
    #expose:
    #  - "1900/udp"
    environment:
      - NODE_ENV=production
      - BACKEND_HOST=backend
      - STARTUP_DELAY=1500
    depends_on:
      - backend
    network_mode: host
    tty: true
```
<p>How can i resolve the hostname "backend" via docker from the docker host?</p>
<p><code>dig backend @127.0.0.11</code> & <code>dig backend @172.17.0.1</code> did not work.</p>
<p>A test with a docker ubuntu image & socat proves, that i can receive ssdp multicast packets:</p>
<pre class="lang-bash prettyprint-override"><code>docker run --net host -it --rm ubuntu
socat UDP4-RECVFROM:1900,ip-add-membership=239.255.255.250:0.0.0.0,fork -
</code>```

The only problem i now have is the DNS/Container name resolution from the host (network).

TL;DR

The container "connector" must be on the host network,but also be able to resolve the container name "backend" to the docker internal IP Address.

NOTE: Perhaps this is better suited on superuser or similar?

Body:
I need to resolve a container name to the IP Address from the docker host.

The reason for this is, i need a container to run on the host network, but it must be also able to resolve the container "backend" which it connects also to. (The container must be send & receive multicast packets)

docker-compose.yml

version: "3"
services:

  database:
    image: mongo
    container_name: database
    hostname: database
    ports:
      - "27017:27017"

  backend:
    image: "project/backend:latest"
    container_name: backend
    hostname: backend
    environment:
      - NODE_ENV=production
      - DATABASE_HOST=database
      - UUID=5025f846-7587-11ed-9ca7-8b992b5e7dd3
    ports:
      - "8080:8080"
    depends_on:
      - database
    tty: true

  frontend:
    image: "project/frontend:latest"
    container_name: frontend
    hostname: frontend
    ports:
      - "80:80"
      - "443:443"
    depends_on:
      - backend
    environment:
      - BACKEND_HOST=backend
  connector:
    image: "project/connector:latest"
    container_name: connector
    hostname: connector
    ports:
      - "1900:1900/udp"
    #expose:
    #  - "1900/udp"
    environment:
      - NODE_ENV=production
      - BACKEND_HOST=backend
      - STARTUP_DELAY=1500
    depends_on:
      - backend
    network_mode: host
    tty: true

How can i resolve the hostname "backend" via docker from the docker host?

dig backend @127.0.0.11 & dig backend @172.17.0.1 did not work.

A test with a docker ubuntu image & socat proves, that i can receive ssdp multicast packets:

docker run --net host -it --rm ubuntu
socat UDP4-RECVFROM:1900,ip-add-membership=239.255.255.250:0.0.0.0,fork -

The only problem i now have is the DNS/Container name resolution from the host (network).

TL;DR

The container "connector" must be on the host network,but also be able to resolve the container name "backend" to the docker internal IP Address.

NOTE: Perhaps this is better suited on superuser or similar?


问:
How to bypass user acknowledge (OAuth 2.0) for Google Calendar API usage?
I want to be able to make some basic Google Calendar integrations using the respective calendar API. Is there a way to achieve this (from a javascript side or from an ASP.NET or Node.js side) WITHOUT having the front-end user confirm on the acknowledgement screen (part of OAuth 2.0) auth process?

PS - I'm trying to provide the best user experience for my customers using my web app (ASP.NET React JS app). I have multiple services (e.g. Google Calendar, DropBox, and another 3rd party email provider) which I'm trying to tie altogether into a seamless UX.

Thanks.


问:
Why webscraping code does not give me the results i want, what code should i use?
I need code for mouse hovering for data scraping for a specific bookie, the opening odds show only with mouse hovering and i want to  extract them

this is the site and a match for an example https://www.oddsmath.com/football/england/championship-1278/2022-12-26/watford-vs-millwall-4014497/

I am a newbie when it comes to this i have tried this code but it does not work

```<code>var rows = document.getElementsByClassName('lo');
var row;
for (var i = rows.length - 2; i >= 0; i--) {
    row = rows[i];
    if(row.innerHTML.includes('\"blogos l581\"')) {
        var event = new Event('mouseover');
        row.children[2].children[0].dispatchEvent(event);
        break;
    }
}
</code>```

Body:
I need code for mouse hovering for data scraping for a specific bookie, the opening odds show only with mouse hovering and i want to  extract them

this is the site and a match for an example https://www.oddsmath.com/football/england/championship-1278/2022-12-26/watford-vs-millwall-4014497/

I am a newbie when it comes to this i have tried this code but it does not work

var rows = document.getElementsByClassName('lo');
var row;
for (var i = rows.length - 2; i >= 0; i--) {
    row = rows[i];
    if(row.innerHTML.includes('\"blogos l581\"')) {
        var event = new Event('mouseover');
        row.children[2].children[0].dispatchEvent(event);
        break;
    }
}


问:
Adding key functionality to OnTriggerEnter
I have 2 scripts which are working almost perfectly for me.

PlayerPositionCorrection on player :

```<code>public class PlayerPositionCorrection : MonoBehaviour
{

    Transform _playerTransform;
    public float _xAxys;
    public float _newXAxys;

    private void Start()
    {
        _playerTransform = GetComponent<Transform>();
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("ChangePlayerPosition"))
        {
            Debug.Log("Check if Collided With : " + other.gameObject.name);
            _newXAxys = other.GetComponent<PositionCorrector>()._newXAxys;
            Debug.Log("New XAxys value : " + _newXAxys);
        }
    }
}

</code>```

and PositionCorrector on object with collider :

```<code>public class PositionCorrector : MonoBehaviour
{

    public float _newXAxys = 4;
    public Vector3 _playerPostion;
    //public int _optionNumber = 1;

    [SerializeField] bool _isInTriggerZone = false;

    private void Update()
    {

    }

    private void OnTriggerEnter(Collider other)
    {
        if (Input.GetKeyDown("p") && other.CompareTag("Player"))
        {
            _playerPostion = other.transform.position;
            _playerPostion = new Vector3(_newXAxys, _playerPostion.y, _playerPostion.z);
        }

    }

}
</code>```

I try to add to this script PositionCorrector one future when character/player collide with object AND PRESS ANY KEY (for this purpose can be 'P') then change his position. But when character  collide witch object (character) don't wait for press key just immediately changing position.

And this is what I added :

```<code>
private void OnTriggerEnter(Collider other)
{
    if (Input.GetKeyDown("p") && other.CompareTag("Player"))
    {
        _playerPostion = other.transform.position;
        _playerPostion = new Vector3(_newXAxys, _playerPostion.y, _playerPostion.z);
    }

}

</code>```

Body:
I have 2 scripts which are working almost perfectly for me.

PlayerPositionCorrection on player :

public class PlayerPositionCorrection : MonoBehaviour
{

    Transform _playerTransform;
    public float _xAxys;
    public float _newXAxys;

    private void Start()
    {
        _playerTransform = GetComponent<Transform>();
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("ChangePlayerPosition"))
        {
            Debug.Log("Check if Collided With : " + other.gameObject.name);
            _newXAxys = other.GetComponent<PositionCorrector>()._newXAxys;
            Debug.Log("New XAxys value : " + _newXAxys);
        }
    }
}

and PositionCorrector on object with collider :

public class PositionCorrector : MonoBehaviour
{

    public float _newXAxys = 4;
    public Vector3 _playerPostion;
    //public int _optionNumber = 1;

    [SerializeField] bool _isInTriggerZone = false;

    private void Update()
    {

    }

    private void OnTriggerEnter(Collider other)
    {
        if (Input.GetKeyDown("p") && other.CompareTag("Player"))
        {
            _playerPostion = other.transform.position;
            _playerPostion = new Vector3(_newXAxys, _playerPostion.y, _playerPostion.z);
        }

    }

}

I try to add to this script PositionCorrector one future when character/player collide with object AND PRESS ANY KEY (for this purpose can be 'P') then change his position. But when character  collide witch object (character) don't wait for press key just immediately changing position.

And this is what I added :

private void OnTriggerEnter(Collider other)
{
    if (Input.GetKeyDown("p") && other.CompareTag("Player"))
    {
        _playerPostion = other.transform.position;
        _playerPostion = new Vector3(_newXAxys, _playerPostion.y, _playerPostion.z);
    }

}


问:
How to use dotnet core GpioController events for ABElectronics IO PI card?
I have written a first version a of dotnet core application on Raspberry Pi for the IO PI expansion card, using the ABElectronics library provided here

This card is based on the MCP23017 microchip.

However, I have two issues:

There is no event or real hardware interrupt, so I need to perform active input reading which is CPU consuming.

I am able to handle up to 6 input pins. After that, I run into performance issue and cannot read inputs every 2 ms as needed (I am counting 69 ticks for each centiliter of liquid the user is serving through a beer system attached to the IO Pi card).

So, I would like to use the Microsoft GpioController library found here.

To use the callback registration mechanism in attempt of making it less CPU expensive and reach better performance.

My questions to you please:

Is it possible to use this Microsoft lib to support this AB Electronics IO PI card? If yes, which driver or config to use?

Any example please?

Thank you for your help.