问:
react hook form with react select to choose prisma object
I am trying to figure out how to use Select inside a react hook form to choose an object that is generated from a related model in Prisma.

I have models in Prisma for IssueGroup and Category. The tables are:

```<code>model IssueGroup {
  id              String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
  title           String
  description     String
  issues          Issue[]
  categories      Category[]
  createdAt       DateTime @default(now()) @db.Timestamptz(6)
  updatedAt       DateTime @default(now()) @updatedAt @db.Timestamptz(6)
}

model Category {
  id              String      @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
  title           String
  issueGroup      IssueGroup  @relation(fields: [issueGroupId], references: [id], onDelete: Cascade, onUpdate: Cascade)
  issueGroupId    String      @db.Uuid
  issue           Issue       @relation(fields: [issueId], references: [id], onDelete: Cascade, onUpdate: Cascade)
  issueId         String      @db.Uuid
  subscribers     UserCategory[]
  createdAt       DateTime    @default(now()) @db.Timestamptz(6)
  updatedAt       DateTime    @default(now()) @updatedAt @db.Timestamptz(6)
}
</code>```

I am trying to make a category form, which will include a Select option menu to select an issueGroup to which a Category is assigned.

I am having difficulty in figuring out how to give those options to the form and how to save the selected option to the table.

I have a form with the following attempt:

```<code>import React, { useState } from 'react';

import { gql } from "@apollo/client"
import {
  Box,
  Button,
  ButtonGroup,
  IconButton,
  useDisclosure,
  Wrap,
  Stack,
  Table,
  Tbody,
  Tr,
  Td,
  TableContainer,
  Text
} from "@chakra-ui/react"
import Head from "next/head"
import { useToast } from "lib/hooks/useToast"
import { useForm } from "lib/hooks/useForm"
import { Form } from "components/Form"
import { FormError } from "components/FormError"
import { Input } from "components/Input"
import { Textarea } from "components/Textarea"

import {
    CategoryInput,
    useAllCategoriesQuery,
    useAllIssueGroupsQuery,
    useCreateCategoryMutation,
    useUpdateCategoryMutation,
    useDeleteCategoryMutation,
    Category as CategoryGQLType,
    IssueGroup as IssueGroupGQLType,
    AllIssueGroupsDocument,
}  from "lib/graphql"
import { Modal } from "components/Modal"
import Yup from "lib/yup"
import { useController } from "react-hook-form"
import { Select } from "chakra-react-select"
import IssueGroups from "../issues"

const __ = gql`

  mutation CreateCategory($data: CategoryInput!) {
    createCategory(data: $data) {
      id
      title

    }
  }
  query AllCategories {
    allCategories {
      id
      title
    }
  }

  query AllIssueGroups {
    allIssueGroups {
        id
        title
    }
  }

  mutation updateCategory($id: String!) {
    updateCategory(id: $id) {
        id
        title

    }
  }

  mutation deleteCategory($id: String!) {
    deleteCategory(id: $id) {
      id
      title
      issues

    }
  }
`

const CategorySchema = Yup.object().shape({
    title: Yup.string().required(),
    description: Yup.string().required(),
    // issues: Yup.string()
  })

function Categories() {
  const toast = useToast()
  const modalProps = useDisclosure()
  const modalPropsUpdate = useDisclosure()
  const [createCategory] = useCreateCategoryMutation()
  const [updateCategory] = useUpdateCategoryMutation()
  const [deleteCategory] = useDeleteCategoryMutation()
  const {  data: categories, refetch: refetchAllCategories } = useAllCategoriesQuery()
  const { data: issueGroups, refetch: refetchAllIssueGroups } = useAllIssueGroupsQuery()
  const defaultValues = {
    title: "",
    issueGroup: "",
    // issues: "",
  }
  const form = useForm({ defaultValues, schema: CategorySchema })
  const [selectedCategory, setSelectedCategory ] = React.useState<Omit<
  CategoryGQLType,
  "createdAt" | "updatedAt" | "issues"
> | null>(null)

  const [selectedIssueGroup, setSelectedIssueGroup ] = React.useState<Omit<
    IssueGroupGQLType,
    "createdAt" | "updatedAt" | "issues" | "description" | "categories"
    > | null>(null)

  const selectIssueGroupOptions = [
    { value: issueGroups.id , label: issueGroups.title}
  ]
</code>```

// i think this version of making an array of key value pairs that uses the issueGroup.id and issueGroup.title is wrong, but I can't find an example of how to do this. Currently, the form generates a select menu that is empty - there are entries in the issueGroup psql table that should be used.

```<code>    const {
        field: { onChange, onBlur, value, ref },
        fieldState: {error},
    } = useController({
        name: "issueGroups",
        control: form.control,
        rules: {
            required: true
        },
        defaultValue: "",
    })

    const { onClose } = useDisclosure()

    const onCreateSubmit = async (data: CategoryInput) => {
        return await form.handler(
            () =>
            createCategory({ variables: {
                data: {
                    ...data,
                    issueGroupId: data.issueGroupId.value,
</code>```

// this line creates a vs code error message that says it does not know what 'value' means and invites me to use valueOf. The error message in the console is:

TypeError: Cannot read properties of undefined (reading 'value')
at form.handler.onSuccess

I don't know what that means.  Github copilot guesses it should be this:

```<code>issueGroupId: data.issueGroupId.value(),
</code>```

When I try that suggestion, the error message says:

TypeError: Cannot read properties of undefined (reading 'valueOf')
at form.handler.onSuccess

```<code>                }
            } }),
            {
                onSuccess: async (data) => {
                    await fetch("api/category", { method: "POST" }),
                    toast({
                        title: "Category created",
                        status: "success",
                    })

                    form.reset(defaultValues)
                    onClose()
                    refetchAllCategories()
                }
            }
        )
    }

  return (
    <Box>
      <Head>
        <title>react hook form with react select options for controlled component</title>
      </Head>

      <Wrap mb={4} spacing={2}>
        <Button
          onClick={modalProps.onOpen}

        >
          Create category
        </Button>
      </Wrap>

      <Modal {...modalProps} title="Create Category">

        <Form {...form} onSubmit={onCreateSubmit}>
            <Stack>
                <Input name="title" label="Title"  />

                <Textarea name="description" label="Describe" rows={4} />
                <Select
                    options={selectIssueGroupOptions}
                    placeholder="Select issue group"
                    closeMenuOnSelect={true}
                    onBlur={onBlur}
                    onChange={onChange}
                    value={value}
                    ref={ref}
                />
                <Text>{error?.message}</Text>

                <FormError />
                <ButtonGroup>
                <Button onClick={modalProps.onClose}>Cancel</Button>
                <Button
                    type="submit"
                >
                    Create
                </Button>
                </ButtonGroup>
            </Stack>
            </Form>
      </Modal>

        <TableContainer maxW="80%">
            <Table variant='simple'>
            <Tbody>
            {categories?.allCategories.map((category) => (
                <Tr key={category.id}>

                <Td>
                    <Text textStyle="h6">{category.title}</Text>

                </Td>
                <Td>
                    <ButtonGroup>
                    <IconButton
                        onClick={() => {
                            setSelectedCategory(category)
                            modalPropsUpdate.onOpen()
                        }}

                    />

                        <Modal {...modalPropsUpdate } title="Edit Category"  >

                            <Form {...form} onSubmit={handleUpdateSubmit}>
                                <Stack>
                                    <Input name="title" label="Title" defaultValue={category.title} />

                                    <Textarea name="description" label="Describe" rows={4} defaultValue={category.description} />

                                    <FormError />
                                    <ButtonGroup>
                                    <Button onClick={modalPropsUpdate.onClose}>Cancel</Button>
                                    <Button
                                        type="submit"
                                    >
                                        Save changes
                                    </Button>
                                    </ButtonGroup>
                                </Stack>
                            </Form>
                        </Modal>

                    <IconButton
                        variant='outline'
                        color="brand.tomato"
                        fontWeight="normal"
                        backgroundColor="brand.white"
                        aria-label='Call Sage'
                        fontSize='15px'
                        ml={4}
                        icon={<CgTrash />}
                        onClick={() => onDeleteCategory(category.id)}
                        _hover={{
                        backgroundColor: "brand.tomato",
                        color: "brand.white",
                        }}
                    />
                    </ButtonGroup>

                </Td>

                </Tr>
                ))}
            </Tbody>

            </Table>
        </TableContainer>

    </Box>
  )
}

Categories.getLayout = (page: React.ReactNode) => {page}

export default Categories
</code>```

Can anyone see what is required to populate a select menu with options that are the id and title of the parent model?

Body:
I am trying to figure out how to use Select inside a react hook form to choose an object that is generated from a related model in Prisma.

I have models in Prisma for IssueGroup and Category. The tables are:

model IssueGroup {
  id              String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
  title           String
  description     String
  issues          Issue[]
  categories      Category[]
  createdAt       DateTime @default(now()) @db.Timestamptz(6)
  updatedAt       DateTime @default(now()) @updatedAt @db.Timestamptz(6)
}

model Category {
  id              String      @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
  title           String
  issueGroup      IssueGroup  @relation(fields: [issueGroupId], references: [id], onDelete: Cascade, onUpdate: Cascade)
  issueGroupId    String      @db.Uuid
  issue           Issue       @relation(fields: [issueId], references: [id], onDelete: Cascade, onUpdate: Cascade)
  issueId         String      @db.Uuid
  subscribers     UserCategory[]
  createdAt       DateTime    @default(now()) @db.Timestamptz(6)
  updatedAt       DateTime    @default(now()) @updatedAt @db.Timestamptz(6)
}

I am trying to make a category form, which will include a Select option menu to select an issueGroup to which a Category is assigned.

I am having difficulty in figuring out how to give those options to the form and how to save the selected option to the table.

I have a form with the following attempt:

import React, { useState } from 'react';

import { gql } from "@apollo/client"
import {
  Box,
  Button,
  ButtonGroup,
  IconButton,
  useDisclosure,
  Wrap,
  Stack,
  Table,
  Tbody,
  Tr,
  Td,
  TableContainer,
  Text
} from "@chakra-ui/react"
import Head from "next/head"
import { useToast } from "lib/hooks/useToast"
import { useForm } from "lib/hooks/useForm"
import { Form } from "components/Form"
import { FormError } from "components/FormError"
import { Input } from "components/Input"
import { Textarea } from "components/Textarea"

import {
    CategoryInput,
    useAllCategoriesQuery,
    useAllIssueGroupsQuery,
    useCreateCategoryMutation,
    useUpdateCategoryMutation,
    useDeleteCategoryMutation,
    Category as CategoryGQLType,
    IssueGroup as IssueGroupGQLType,
    AllIssueGroupsDocument,
}  from "lib/graphql"
import { Modal } from "components/Modal"
import Yup from "lib/yup"
import { useController } from "react-hook-form"
import { Select } from "chakra-react-select"
import IssueGroups from "../issues"

const __ = gql`

  mutation CreateCategory($data: CategoryInput!) {
    createCategory(data: $data) {
      id
      title

    }
  }
  query AllCategories {
    allCategories {
      id
      title
    }
  }

  query AllIssueGroups {
    allIssueGroups {
        id
        title
    }
  }

  mutation updateCategory($id: String!) {
    updateCategory(id: $id) {
        id
        title

    }
  }

  mutation deleteCategory($id: String!) {
    deleteCategory(id: $id) {
      id
      title
      issues

    }
  }
`

const CategorySchema = Yup.object().shape({
    title: Yup.string().required(),
    description: Yup.string().required(),
    // issues: Yup.string()
  })

function Categories() {
  const toast = useToast()
  const modalProps = useDisclosure()
  const modalPropsUpdate = useDisclosure()
  const [createCategory] = useCreateCategoryMutation()
  const [updateCategory] = useUpdateCategoryMutation()
  const [deleteCategory] = useDeleteCategoryMutation()
  const {  data: categories, refetch: refetchAllCategories } = useAllCategoriesQuery()
  const { data: issueGroups, refetch: refetchAllIssueGroups } = useAllIssueGroupsQuery()
  const defaultValues = {
    title: "",
    issueGroup: "",
    // issues: "",
  }
  const form = useForm({ defaultValues, schema: CategorySchema })
  const [selectedCategory, setSelectedCategory ] = React.useState<Omit<
  CategoryGQLType,
  "createdAt" | "updatedAt" | "issues"
> | null>(null)

  const [selectedIssueGroup, setSelectedIssueGroup ] = React.useState<Omit<
    IssueGroupGQLType,
    "createdAt" | "updatedAt" | "issues" | "description" | "categories"
    > | null>(null)

  const selectIssueGroupOptions = [
    { value: issueGroups.id , label: issueGroups.title}
  ]

// i think this version of making an array of key value pairs that uses the issueGroup.id and issueGroup.title is wrong, but I can't find an example of how to do this. Currently, the form generates a select menu that is empty - there are entries in the issueGroup psql table that should be used.

    const {
        field: { onChange, onBlur, value, ref },
        fieldState: {error},
    } = useController({
        name: "issueGroups",
        control: form.control,
        rules: {
            required: true
        },
        defaultValue: "",
    })

    const { onClose } = useDisclosure()

    const onCreateSubmit = async (data: CategoryInput) => {
        return await form.handler(
            () =>
            createCategory({ variables: {
                data: {
                    ...data,
                    issueGroupId: data.issueGroupId.value,

// this line creates a vs code error message that says it does not know what 'value' means and invites me to use valueOf. The error message in the console is:

TypeError: Cannot read properties of undefined (reading 'value')
at form.handler.onSuccess

I don't know what that means.  Github copilot guesses it should be this:

issueGroupId: data.issueGroupId.value(),

When I try that suggestion, the error message says:

TypeError: Cannot read properties of undefined (reading 'valueOf')
at form.handler.onSuccess

                }
            } }),
            {
                onSuccess: async (data) => {
                    await fetch("api/category", { method: "POST" }),
                    toast({
                        title: "Category created",
                        status: "success",
                    })

                    form.reset(defaultValues)
                    onClose()
                    refetchAllCategories()
                }
            }
        )
    }

  return (
    <Box>

        <title>react hook form with react select options for controlled component</title>

      <Wrap mb={4} spacing={2}>
        <Button
          onClick={modalProps.onOpen}

        >
          Create category
        </Button>
      </Wrap>

      <Modal {...modalProps} title="Create Category">

        <Form {...form} onSubmit={onCreateSubmit}>
            <Stack>
                <Input name="title" label="Title"  />

                <Textarea name="description" label="Describe" rows={4} />
                <Select
                    options={selectIssueGroupOptions}
                    placeholder="Select issue group"
                    closeMenuOnSelect={true}
                    onBlur={onBlur}
                    onChange={onChange}
                    value={value}
                    ref={ref}
                />
                <Text>{error?.message}</Text>

                <FormError />
                <ButtonGroup>
                <Button onClick={modalProps.onClose}>Cancel</Button>
                <Button
                    type="submit"
                >
                    Create
                </Button>
                </ButtonGroup>
            </Stack>
            </Form>
      </Modal>

        <TableContainer maxW="80%">

            {categories?.allCategories.map((category) => (

                    <Text textStyle="h6">{category.title}</Text>

                    <ButtonGroup>
                    <IconButton
                        onClick={() => {
                            setSelectedCategory(category)
                            modalPropsUpdate.onOpen()
                        }}

                    />

                        <Modal {...modalPropsUpdate } title="Edit Category"  >

                            <Form {...form} onSubmit={handleUpdateSubmit}>
                                <Stack>
                                    <Input name="title" label="Title" defaultValue={category.title} />

                                    <Textarea name="description" label="Describe" rows={4} defaultValue={category.description} />

                                    <FormError />
                                    <ButtonGroup>
                                    <Button onClick={modalPropsUpdate.onClose}>Cancel</Button>
                                    <Button
                                        type="submit"
                                    >
                                        Save changes
                                    </Button>
                                    </ButtonGroup>
                                </Stack>
                            </Form>
                        </Modal>

                    <IconButton
                        variant='outline'
                        color="brand.tomato"
                        fontWeight="normal"
                        backgroundColor="brand.white"
                        aria-label='Call Sage'
                        fontSize='15px'
                        ml={4}
                        icon={<CgTrash />}
                        onClick={() => onDeleteCategory(category.id)}
                        _hover={{
                        backgroundColor: "brand.tomato",
                        color: "brand.white",
                        }}
                    />
                    </ButtonGroup>

                ))}

        </TableContainer>

    </Box>
  )
}

Categories.getLayout = (page: React.ReactNode) => {page}

export default Categories

Can anyone see what is required to populate a select menu with options that are the id and title of the parent model?


来源: stackexchange

问:
GetServersideProps triggers only on some pages witgh next/link in Dev mode
I have a weird behavior with my next pages.

I develop an Admin Dashboard using Next.js

Pages are rendered on server side to fetch the content

But on one page getServerSideProps is only triggered when refreshing the page, not by clicking on the Next/Link

This site doesn't work:
`

```<code>import Head from 'next/head'
import { Portal, Card } from '@layout'
import { GetServerSideProps } from 'next'
import Datatable from '@components/datatable/Datatable'
import { translate, verifyUser } from '@functions'
import { ApiType, Category, User } from '@types'
import Widget from '../../layout/widget/Widget'
import { apiUpdateItem } from '../../functions/api/products/apiProducts'
import { useRouter } from 'next/router'
import { BreadcrumbContext } from '../../context/BreadcrumbContext'
import { useContext } from 'react'

type ItemPageType = {
  categories: ApiType<Category>[]
  user: User
}
const ItemPage = ({ categories, user }:ItemPageType) => {
  const router = useRouter()
  const onSave = (data:any, id:number) => {
    apiUpdateItem({ token: user.jwt, data:data, id:id, collection: 'categories' }).then(res => {
      if(res.ok)
        router.replace(router.asPath).then()
    })
  }
  const onDelete = (e:any) => {
    console.log(e)
  }
  return (
    <>
      <Head>
        <title>Wolke 7 - Items</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <Widget width={'full'} height={'maxHeight'}>
        <Card>
          <Datatable list={categories} attributes={['name', 'highlight', 'products']} showTools onSave={onSave} onDelete={onDelete} onAdd={() => console.log('add')}/>
        </Card>
      </Widget>
    </>
  )
}
export const getServerSideProps:GetServerSideProps = async(ctx) => {
  const verify = await verifyUser(ctx)
  if(verify !== null) {
    const categories = await fetch(`${process.env.BACKEND}/api/categories/?populate[0]=products&populate[1]=products.variants&sort=order:asc`, {
      method: 'GET',
      headers: {
        'Authorization': 'Bearer ' + verify.jwt
      }
    }).then(res => res.json().then())
    return {
      props: {
        categories: categories.data,
        user: {
          jwt: verify.jwt,
          ...verify.user
        }
      }
    }
  }
  return {
    props:{}
  }
}
export default ItemPage

</code>```

`

For some reason it works completely fine for this page:
`

```<code>import type { GetServerSideProps } from 'next'
import Head from 'next/head'
import { Card, Portal, Widget } from '@layout'
import React from 'react'
import { ApiType, Order, User } from '@types'
import { useRouter } from 'next/router'

import { translate, verifyUser } from '@functions'
import Datatable from '@components/datatable/Datatable'

type ActiveOrderPageType = {
  activeOrders: ApiType<Order>[]
  user: User
}
const ActiveOrderPage = ({ activeOrders, user }:ActiveOrderPageType) => {
  return (
    <>
      <Head>
        <title>Wolke7 - {translate('activeOrders')}</title>
        <meta name="description" content="Active Order Page" />
        <link rel="icon" href="/cascade_favicon.png" />
      </Head>
      <Portal location={'headerTitle'}>
        {translate('ActiveOrders')}
      </Portal>
      <Widget width={'full'} height={'maxHeight'}>
        <Card>
          <Datatable list={activeOrders} attributes={['orderNumber', 'createdAt', 'orderPositions', 'total']} onAdd={() => console.log('add')}/>
        </Card>
      </Widget>
    </>
  )
}
export const getServerSideProps:GetServerSideProps = async(ctx) => {
  const verify = await verifyUser(ctx, true)
  if(verify !== null) {
    const activeOrders = await fetch(`${process.env.BACKEND}/api/active-orders/?populate[0]=orderPositions&sort=createdAt:desc`, {
      method: 'GET',
      headers: {
        'Authorization': 'Bearer ' + verify.jwt
      }
    }).then(res => res.json())
    return { props:{
      activeOrders: activeOrders.data,
      user: {
        jwt: verify.jwt,
        ...verify.user
      }
    } }
  }
  return {
    props: {}
  }
}
export default ActiveOrderPage

</code>```

`

In Production, everything works fine and content is fetched as it should.
Only the categories page does not trigger getServerSideProps in dev mode for some reason.

I expected that getServerSideProps gets triggered on any page called by Next/Link in dev mode

The link component is exactly the same for both pages

ContentLicense: CC BY-SA 4.0

Body:
I have a weird behavior with my next pages.

I develop an Admin Dashboard using Next.js

Pages are rendered on server side to fetch the content

But on one page getServerSideProps is only triggered when refreshing the page, not by clicking on the Next/Link

This site doesn't work:
`

import Head from 'next/head'
import { Portal, Card } from '@layout'
import { GetServerSideProps } from 'next'
import Datatable from '@components/datatable/Datatable'
import { translate, verifyUser } from '@functions'
import { ApiType, Category, User } from '@types'
import Widget from '../../layout/widget/Widget'
import { apiUpdateItem } from '../../functions/api/products/apiProducts'
import { useRouter } from 'next/router'
import { BreadcrumbContext } from '../../context/BreadcrumbContext'
import { useContext } from 'react'

type ItemPageType = {
  categories: ApiType<Category>[]
  user: User
}
const ItemPage = ({ categories, user }:ItemPageType) => {
  const router = useRouter()
  const onSave = (data:any, id:number) => {
    apiUpdateItem({ token: user.jwt, data:data, id:id, collection: 'categories' }).then(res => {
      if(res.ok)
        router.replace(router.asPath).then()
    })
  }
  const onDelete = (e:any) => {
    console.log(e)
  }
  return (
    <>

        <title>Wolke 7 - Items</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />

      <Widget width={'full'} height={'maxHeight'}>
        <Card>
          <Datatable list={categories} attributes={['name', 'highlight', 'products']} showTools onSave={onSave} onDelete={onDelete} onAdd={() => console.log('add')}/>
        </Card>
      </Widget>
    </>
  )
}
export const getServerSideProps:GetServerSideProps = async(ctx) => {
  const verify = await verifyUser(ctx)
  if(verify !== null) {
    const categories = await fetch(`${process.env.BACKEND}/api/categories/?populate[0]=products&populate[1]=products.variants&sort=order:asc`, {
      method: 'GET',
      headers: {
        'Authorization': 'Bearer ' + verify.jwt
      }
    }).then(res => res.json().then())
    return {
      props: {
        categories: categories.data,
        user: {
          jwt: verify.jwt,
          ...verify.user
        }
      }
    }
  }
  return {
    props:{}
  }
}
export default ItemPage

`

For some reason it works completely fine for this page:
`

import type { GetServerSideProps } from 'next'
import Head from 'next/head'
import { Card, Portal, Widget } from '@layout'
import React from 'react'
import { ApiType, Order, User } from '@types'
import { useRouter } from 'next/router'

import { translate, verifyUser } from '@functions'
import Datatable from '@components/datatable/Datatable'

type ActiveOrderPageType = {
  activeOrders: ApiType<Order>[]
  user: User
}
const ActiveOrderPage = ({ activeOrders, user }:ActiveOrderPageType) => {
  return (
    <>

        <title>Wolke7 - {translate('activeOrders')}</title>
        <meta name="description" content="Active Order Page" />
        <link rel="icon" href="/cascade_favicon.png" />

      <Portal location={'headerTitle'}>
        {translate('ActiveOrders')}
      </Portal>
      <Widget width={'full'} height={'maxHeight'}>
        <Card>
          <Datatable list={activeOrders} attributes={['orderNumber', 'createdAt', 'orderPositions', 'total']} onAdd={() => console.log('add')}/>
        </Card>
      </Widget>
    </>
  )
}
export const getServerSideProps:GetServerSideProps = async(ctx) => {
  const verify = await verifyUser(ctx, true)
  if(verify !== null) {
    const activeOrders = await fetch(`${process.env.BACKEND}/api/active-orders/?populate[0]=orderPositions&sort=createdAt:desc`, {
      method: 'GET',
      headers: {
        'Authorization': 'Bearer ' + verify.jwt
      }
    }).then(res => res.json())
    return { props:{
      activeOrders: activeOrders.data,
      user: {
        jwt: verify.jwt,
        ...verify.user
      }
    } }
  }
  return {
    props: {}
  }
}
export default ActiveOrderPage

`

In Production, everything works fine and content is fetched as it should.
Only the categories page does not trigger getServerSideProps in dev mode for some reason.

I expected that getServerSideProps gets triggered on any page called by Next/Link in dev mode

The link component is exactly the same for both pages


问:
The range of similarity in openAI text-embeddings is not [0, 1]
I am using openAI Ada to create text-embeddings. When i calculate the similarity between these embeddings my answer is in the range [0.7, 0.9] approximately. In the rest of my project I would need these to be in [0.0, 1.0], and I want to find a way to normalize the values. Could I just normalize them based on the range [0.7, 0.9] or would that seem too risky as there is no real prove that that is actual the range?

I understand that just keeping them as they are might be the best way, but I would really benefit from having the very distanced sentences to be 0 and the really close one 1


问:
How to do Signup, Login, Logout from front end in React?
TLDR: In front end, what do I do with the access token I receive when signing up and logging in, if I’m not using refresh tokens?

I started building my first full stack web application. So far, I’ve built simple log in and sign up APIs (which returns a JWT access token). I do not want to implement refresh tokens here because I want this to be really simple.

I’m stuck on implementing the sign in and sign out functionalities from the front end with react. I’ve built user interfaces for them but from there I can’t figure out how to proceed. Almost every resource I’ve looked at seem to be either too simple (shows single login page and that’s it) or too complex (implements sessions, refresh tokens, etc.)

Basically my project has several pages, and three user roles. The content of the pages are dynamically rendered according to the role. So I want to access the current logged in user’s details through the application.

One way I thought of doing was get the access token from login response, store it in local storage and decode it to see the user role whenever I need. Please tell me if that’s a good way of doing that, and either way how do I implement the logout function? Should I just remove the access token from local storage?

Also, if you can recommend me a good resource to learn this, it’s also fine. TYIA.


问:
Best practices for git maintenance?
I'm looking at the git-maintenance manual and is unclear for me how the actual maintenance tasks are performed. To my understanding, once I execute git maintenance run --auto, several tasks are executed in the background. For example, if I perform a git pull, any related maintenance tasks should be executed automatically.

The part I cannot properly comprehend is if these tasks need to be scheduled by myself prior, or the --auto switch does that for me. My goal is to have the following maintenance tasks executed at specified timeline:

gc: weekly, default disabled

commit-graph: hourly

prefetch: hourly

loose-objects: daily

incremental-repack: daily

I would like to know what are the proper git maintenance commands to properly schedule the above tasks and also to get your input of recommended timelines for each task, they are taken from the manual, except gc, which is disabled by default.

Current ./.git structure, prior running any git maintenance commands:

# git --version
git version 2.30.2

# ls -lah .git
total 303K
drwxr-xr-x  8 root root   13 Dec 27 17:18 .
drwxr-xr-x 11 root root   19 Dec 27 17:18 ..
-rw-r--r--  1 root root   21 Dec 27 17:18 HEAD
drwxr-xr-x  2 root root    2 Dec 27 17:17 branches
-rw-r--r--  1 root root  252 Dec 27 17:18 config
-rw-r--r--  1 root root   73 Dec 27 17:17 description
drwxr-xr-x  2 root root   15 Dec 27 17:17 hooks
-rw-r--r--  1 root root 553K Dec 27 17:18 index
drwxr-xr-x  2 root root    3 Dec 27 17:17 info
drwxr-xr-x  3 root root    4 Dec 27 17:18 logs
drwxr-xr-x  4 root root    4 Dec 27 17:17 objects
-rw-r--r--  1 root root  112 Dec 27 17:18 packed-refs
drwxr-xr-x  5 root root    5 Dec 27 17:18 refs
```
<p><code>./git/config</code> <code>[maintenance]</code> section:</p>
```[maintenance]
    auto = false
    strategy = incremental
```

I expected running git maintenance run --auto command to set auto = true, but it is not. Thank you for taking the time to provide an example, how to properly configure the repo maintenance.

Title: Best practices for git maintenance?

Body:
I'm looking at the git-maintenance manual and is unclear for me how the actual maintenance tasks are performed. To my understanding, once I execute git maintenance run --auto, several tasks are executed in the background. For example, if I perform a git pull, any related maintenance tasks should be executed automatically.

The part I cannot properly comprehend is if these tasks need to be scheduled by myself prior, or the --auto switch does that for me. My goal is to have the following maintenance tasks executed at specified timeline:

gc: weekly, default disabled

commit-graph: hourly

prefetch: hourly

loose-objects: daily

incremental-repack: daily

I would like to know what are the proper git maintenance commands to properly schedule the above tasks and also to get your input of recommended timelines for each task, they are taken from the manual, except gc, which is disabled by default.

Current ./.git structure, prior running any git maintenance commands:

# git --version
git version 2.30.2

# ls -lah .git
total 303K
drwxr-xr-x  8 root root   13 Dec 27 17:18 .
drwxr-xr-x 11 root root   19 Dec 27 17:18 ..
-rw-r--r--  1 root root   21 Dec 27 17:18 HEAD
drwxr-xr-x  2 root root    2 Dec 27 17:17 branches
-rw-r--r--  1 root root  252 Dec 27 17:18 config
-rw-r--r--  1 root root   73 Dec 27 17:17 description
drwxr-xr-x  2 root root   15 Dec 27 17:17 hooks
-rw-r--r--  1 root root 553K Dec 27 17:18 index
drwxr-xr-x  2 root root    3 Dec 27 17:17 info
drwxr-xr-x  3 root root    4 Dec 27 17:18 logs
drwxr-xr-x  4 root root    4 Dec 27 17:17 objects
-rw-r--r--  1 root root  112 Dec 27 17:18 packed-refs
drwxr-xr-x  5 root root    5 Dec 27 17:18 refs

./git/config [maintenance] section:

[maintenance]
    auto = false
    strategy = incremental

I expected running git maintenance run --auto command to set auto = true, but it is not. Thank you for taking the time to provide an example, how to properly configure the repo maintenance.


问:
How do I scatterplot LD1 vs LD2 in lda analysis?
I'm very very new to R, so thanks in advance for the help
I did the lda analysis on my dataset (tme.lda), in the console I get all my results with LD1, LD2, LD3, LD4, LD5 and LD6 but when I try to plot it I tried a lot of different methods but I get every kind of error: Error LD1 object not found -  Error in fortify - Error in as.data.frame just to say a few.

This is my dataset:

dput(head(tme.lda))
structure(list(Word = structure(1:6, levels = c("bene", "bile",
"casa", "come", "posso", "tutto", "vero"), class = "factor"),
   f0min = c(184L, 193L, 189L, 199L, 175L, 144L), f0max = c(229L,
   226L, 198L, 225L, 192L, 188L), F1 = c(600L, 347L, 980L, 531L,
   550L, 432L), F2 = c(2406L, 2695L, 1759L, 997L, 996L, 1901L
   ), F4 = c(4125L, 4403L, 3837L, 3988L, 3909L, 4171L), max_F0 = c(143L,
   130L, 124L, 133L, 123L, 120L)), row.names = c(NA, 6L), class = "data.frame")
```
<p>And this is the code I wrote, how can I get from here the scatterplot LD1 vs LD2?</p>
<pre class="lang-r prettyprint-override"><code>View(tme.lda)
#lDFA analysis with "WORD" as grouping factor
tme.lda<-cbind(tme[,5],tme.lda[,1:6])
names(tme.lda)
#> [1] "tme[, 5]" "f0min"    "f0max"    "F1"       "F2"       "F4"       "max_F0"
names(tme.lda)=c("Word","f0min","f0max","F1","F2","F4","max_F0")
names(tme.lda)
#> [1] "Word"   "f0min"  "f0max"  "F1"     "F2"     "F4"     "max_F0"
library(MASS)
lda(Word~f0min+f0max+F1+F2+F4+max_F0,data = tme.lda)
</code>```

I tried this:

plot(Word, panel = tme.lda, abbrev = FALSE, xlab = "LD1", ylab = "LD2")
plot(x, panel = panel.lda, cex = 0.7, dimen=2, abbrev = FALSE, xlab = "LD1", ylab = "LD2")
ggplot(Word, panel = tme.lda, cex = 0.7, dimen=2, xlab = "LD1", ylab = "LD2")
ggplot2::aes(LD1,LD2) (Word, panel = tme.lda, cex = 0.7, dimen=2, xlab = "LD1", ylab = "LD2")
plot.lda<-lda(Word~f0min+f0max+F1+F2+F4+max_F0,data = tme.lda)

ggp <- ggplot(plot.lda, aes(x = LD1, y=LD2)) +
  geom_point(mapping = aes(colour=Word)) +
  ggtitle("LD1 Vs. LD2")

ggp <- ggplot(plot.lda, aes(x = LD1, y=LD2))
```

Just to say a few things I tried

Body:
I'm very very new to R, so thanks in advance for the help
I did the lda analysis on my dataset (tme.lda), in the console I get all my results with LD1, LD2, LD3, LD4, LD5 and LD6 but when I try to plot it I tried a lot of different methods but I get every kind of error: Error LD1 object not found -  Error in fortify - Error in as.data.frame just to say a few.

This is my dataset:

dput(head(tme.lda))
structure(list(Word = structure(1:6, levels = c("bene", "bile",
"casa", "come", "posso", "tutto", "vero"), class = "factor"),
   f0min = c(184L, 193L, 189L, 199L, 175L, 144L), f0max = c(229L,
   226L, 198L, 225L, 192L, 188L), F1 = c(600L, 347L, 980L, 531L,
   550L, 432L), F2 = c(2406L, 2695L, 1759L, 997L, 996L, 1901L
   ), F4 = c(4125L, 4403L, 3837L, 3988L, 3909L, 4171L), max_F0 = c(143L,
   130L, 124L, 133L, 123L, 120L)), row.names = c(NA, 6L), class = "data.frame")

And this is the code I wrote, how can I get from here the scatterplot LD1 vs LD2?

View(tme.lda)
#lDFA analysis with "WORD" as grouping factor
tme.lda<-cbind(tme[,5],tme.lda[,1:6])
names(tme.lda)
#> [1] "tme[, 5]" "f0min"    "f0max"    "F1"       "F2"       "F4"       "max_F0"
names(tme.lda)=c("Word","f0min","f0max","F1","F2","F4","max_F0")
names(tme.lda)
#> [1] "Word"   "f0min"  "f0max"  "F1"     "F2"     "F4"     "max_F0"
library(MASS)
lda(Word~f0min+f0max+F1+F2+F4+max_F0,data = tme.lda)

I tried this:

plot(Word, panel = tme.lda, abbrev = FALSE, xlab = "LD1", ylab = "LD2")
plot(x, panel = panel.lda, cex = 0.7, dimen=2, abbrev = FALSE, xlab = "LD1", ylab = "LD2")
ggplot(Word, panel = tme.lda, cex = 0.7, dimen=2, xlab = "LD1", ylab = "LD2")
ggplot2::aes(LD1,LD2) (Word, panel = tme.lda, cex = 0.7, dimen=2, xlab = "LD1", ylab = "LD2")
plot.lda<-lda(Word~f0min+f0max+F1+F2+F4+max_F0,data = tme.lda)

ggp <- ggplot(plot.lda, aes(x = LD1, y=LD2)) +
  geom_point(mapping = aes(colour=Word)) +
  ggtitle("LD1 Vs. LD2")

ggp <- ggplot(plot.lda, aes(x = LD1, y=LD2))

Just to say a few things I tried


问:
Rmarkdown flexdashboard: how to adjust fillpage css for desktop view height
I have a flexdashboard created with Rmarkdown that has a custom span added to the navbar, resulting in the map I have below not being sized problem due to the extra height of the navbar.

The fix in the html is known to me: change the height of the dashboard container by replacing

$("html,body,#dashboard").css("height", "100%");
```
<p>with</p>
<pre class="lang-js prettyprint-override"><code>$("html,body,#dashboard").css("height", "calc(100% - 30px)");
</code>```

However, I have been unable to change the generating Rmarkdown/css code to affect this line in the html document.

The line in context is:

if (_options.resize_reload) {
      $(window).on('resize', function() {
        if (_options.isMobile !== isMobilePhone() ||
            _options.isPortrait !== isPortrait()) {
          window.location.reload();
        }
      });
    } else {
      // if in desktop mode and resizing to mobile, make sure the heights are 100%
      // This enforces what `fillpage.css` does for "wider" pages.
      // Since we are not reloading once the page becomes small, we need to force the height to 100%
      // This is a new situation introduced when `_options.resize_reload` is `false`
      if (! _options.isMobile) {
        // only add if `fillpage.css` was added in the first place
        if (_options.fillPage) {
          // fillpage.css
          $("html,body,#dashboard").css("height", "100%");
        }
      }
    }
```
<p>The referenced fillpage.css in its entirety is:</p>
<pre class="lang-css prettyprint-override"><code>@media only screen and (min-width: 768px) {
html, body {
  height: 100%;
}

#dashboard-container {
  height: 100%;
}
}
</code>```

I have tried the following:

Adding the above fillpage.css code (with the modified height: calc(100% - 30px) to the Rmarkdown document in the css chunk (other css in this chunk is working).

Adding a modified fillpage.css to the css yaml.

In both cases, the generated html referenced above is unaffected.

How can I implement this change in my code so I don't need to manually edit the html document each time I knit?

Body:
I have a flexdashboard created with Rmarkdown that has a custom span added to the navbar, resulting in the map I have below not being sized problem due to the extra height of the navbar.

The fix in the html is known to me: change the height of the dashboard container by replacing

$("html,body,#dashboard").css("height", "100%");

with

$("html,body,#dashboard").css("height", "calc(100% - 30px)");

However, I have been unable to change the generating Rmarkdown/css code to affect this line in the html document.

The line in context is:

if (_options.resize_reload) {
      $(window).on('resize', function() {
        if (_options.isMobile !== isMobilePhone() ||
            _options.isPortrait !== isPortrait()) {
          window.location.reload();
        }
      });
    } else {
      // if in desktop mode and resizing to mobile, make sure the heights are 100%
      // This enforces what `fillpage.css` does for "wider" pages.
      // Since we are not reloading once the page becomes small, we need to force the height to 100%
      // This is a new situation introduced when `_options.resize_reload` is `false`
      if (! _options.isMobile) {
        // only add if `fillpage.css` was added in the first place
        if (_options.fillPage) {
          // fillpage.css
          $("html,body,#dashboard").css("height", "100%");
        }
      }
    }

The referenced fillpage.css in its entirety is:

@media only screen and (min-width: 768px) {
html, body {
  height: 100%;
}

#dashboard-container {
  height: 100%;
}
}

I have tried the following:

Adding the above fillpage.css code (with the modified height: calc(100% - 30px) to the Rmarkdown document in the css chunk (other css in this chunk is working).

Adding a modified fillpage.css to the css yaml.

In both cases, the generated html referenced above is unaffected.

How can I implement this change in my code so I don't need to manually edit the html document each time I knit?


问:
Swagger error in Office 365/Outlook step in Logic App
this seems really weird and I'm not sure how to fix. Any tips would be appreciated.

I have an Office 365 Outlook step called Send An Email (V2). When I add this directly to the logic app, it works fine. When I export the template and deploy from visual studio, I get this error from that step:

Error in Swagger definition SyntaxError: The object is not a valid Swagger API definition

Does anyone know why this would be? All the other steps I'm deploying like this work fine.

Also, an alternative for sending email would be fine.


问:
Cargo - adjust stacked page height
I'm designing a page for my mobile menu using stacked pages for the 4 pages I'm linking to - how can I make each of these pages 25% so that the coloured blocks fill up the whole page? :)

As you can see right now they are taking up a small percentage of the screen so there's a lot of white space

I'm afraid nothing as I'm new to building sites...

Title: Cargo - adjust stacked page height


问:
How can i generate random images with random clouds(pixels) from the original image?
for example this is the original image :

original image

This is the code i'm using to find clouds in image.
i want to take the original image above find the clouds and generate from it for exmaple more 30 images with diffrenet clouds sizes colors amount but it must be inside the circle radius.

the goal to generate random radar with clouds images.

```<code>private void FindPoints()
        {
            Bitmap bmptest;
            GraphicsPath gp = new GraphicsPath();
            int x, y, p, j, wdthHght;
            int bytes;
            byte[] rgbValuesWithClouds;
            byte[] rgbValuesWithoutClouds;
            IntPtr ptr;
            Rectangle rect;
            BitmapData bitmap_Data;

            Bitmap bmpWithClouds; //No memory is allocated
            Bitmap bmpWithoutClouds; //No memory is allocated

            gp.AddEllipse(new RectangleF(73, 72, 367, 367));

            //using the using statement, bmpWithClouds bitmap is automatically disposed at the end of statement. No memory leaks :)
            using (bmpWithClouds = new Bitmap(mymem))
            {
                rect = new Rectangle(0, 0, bmpWithClouds.Width, bmpWithClouds.Height);
                wdthHght = bmpWithClouds.Width;

                //Lock bitmap to copy its color information fast
                bitmap_Data = bmpWithClouds.LockBits(rect, ImageLockMode.ReadWrite, bmpWithClouds.PixelFormat);
                ptr = bitmap_Data.Scan0;
                bytes = bitmap_Data.Stride * bmpWithClouds.Height;

                rgbValuesWithClouds = new byte[bytes];

                //copy color information to rgbValues array
                System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValuesWithClouds, 0, bytes);
                //we are done copying so unlock bitmap. We dont need it anymore
                bmpWithClouds.UnlockBits(bitmap_Data);
            }

            //using the using statement, bmpWithClouds bitmap is automatically disposed at the end of statement. No memory leaks :)
            using (bmpWithoutClouds = new Bitmap(@"F:\Drive Backup\Samsung Galaxy S9\Danny Backup\Recovered data 02-10 18_32_36\1  (D) NTFS\C-Sharp\Weather Radar\WithoutClouds.bmp")) //24 bit bitmap
            {
                rect = new Rectangle(0, 0, bmpWithoutClouds.Width, bmpWithoutClouds.Height);

                //Lock bitmap to copy its color information fast
                bitmap_Data = bmpWithoutClouds.LockBits(rect, ImageLockMode.ReadWrite, bmpWithoutClouds.PixelFormat);
                ptr = bitmap_Data.Scan0;
                bytes = bitmap_Data.Stride * bmpWithoutClouds.Height;

                rgbValuesWithoutClouds = new byte[bytes];

                //copy color information to rgbValues array
                System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValuesWithoutClouds, 0, bytes);
                //we are done copying so unlock bitmap. We dont need it anymore
                bmpWithoutClouds.UnlockBits(bitmap_Data);
            }

            // Each position in these arrays, rgbValuesWithoutClouds and rgbValuesWithClouds, corresponds a color. eg
            // First pixel   Second pixel   Third pixel   Forth pixel .... // bitmaps
            //    B G R          B G R         B G R         B G R    .... // rgbValues arrays
            bmptest = new Bitmap(512, 512);
            cloudPoints = new List<Point>();

            for (y = 0; y < wdthHght; y++)
            {
                j = 0;
                for (x = 0; x < wdthHght; x++)
                {
                    p = y * wdthHght * 3 + j;

                    if (rgbValuesWithClouds[p] != rgbValuesWithoutClouds[p])
                    {
                        cloudPoints.Add(new Point(x, y));
                        bmptest.SetPixel(x, y, Color.Red);
                    }

                    j += 3;
                }
            }
            bmptest.Save(@"d:\bmptest1.bmp");
        }
</code>```

The result of finding the clouds :

detected clouds

Optional : This image is with the ruler on the right that show the possible clouds colors when generating random clouds the colors should be taken from the ruler on the right side. this ruler set the possible clouds rain amount.

image with the ruler on the right side

Body:
for example this is the original image :

original image

This is the code i'm using to find clouds in image.
i want to take the original image above find the clouds and generate from it for exmaple more 30 images with diffrenet clouds sizes colors amount but it must be inside the circle radius.

the goal to generate random radar with clouds images.

private void FindPoints()
        {
            Bitmap bmptest;
            GraphicsPath gp = new GraphicsPath();
            int x, y, p, j, wdthHght;
            int bytes;
            byte[] rgbValuesWithClouds;
            byte[] rgbValuesWithoutClouds;
            IntPtr ptr;
            Rectangle rect;
            BitmapData bitmap_Data;

            Bitmap bmpWithClouds; //No memory is allocated
            Bitmap bmpWithoutClouds; //No memory is allocated

            gp.AddEllipse(new RectangleF(73, 72, 367, 367));

            //using the using statement, bmpWithClouds bitmap is automatically disposed at the end of statement. No memory leaks :)
            using (bmpWithClouds = new Bitmap(mymem))
            {
                rect = new Rectangle(0, 0, bmpWithClouds.Width, bmpWithClouds.Height);
                wdthHght = bmpWithClouds.Width;

                //Lock bitmap to copy its color information fast
                bitmap_Data = bmpWithClouds.LockBits(rect, ImageLockMode.ReadWrite, bmpWithClouds.PixelFormat);
                ptr = bitmap_Data.Scan0;
                bytes = bitmap_Data.Stride * bmpWithClouds.Height;

                rgbValuesWithClouds = new byte[bytes];

                //copy color information to rgbValues array
                System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValuesWithClouds, 0, bytes);
                //we are done copying so unlock bitmap. We dont need it anymore
                bmpWithClouds.UnlockBits(bitmap_Data);
            }

            //using the using statement, bmpWithClouds bitmap is automatically disposed at the end of statement. No memory leaks :)
            using (bmpWithoutClouds = new Bitmap(@"F:\Drive Backup\Samsung Galaxy S9\Danny Backup\Recovered data 02-10 18_32_36\1  (D) NTFS\C-Sharp\Weather Radar\WithoutClouds.bmp")) //24 bit bitmap
            {
                rect = new Rectangle(0, 0, bmpWithoutClouds.Width, bmpWithoutClouds.Height);

                //Lock bitmap to copy its color information fast
                bitmap_Data = bmpWithoutClouds.LockBits(rect, ImageLockMode.ReadWrite, bmpWithoutClouds.PixelFormat);
                ptr = bitmap_Data.Scan0;
                bytes = bitmap_Data.Stride * bmpWithoutClouds.Height;

                rgbValuesWithoutClouds = new byte[bytes];

                //copy color information to rgbValues array
                System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValuesWithoutClouds, 0, bytes);
                //we are done copying so unlock bitmap. We dont need it anymore
                bmpWithoutClouds.UnlockBits(bitmap_Data);
            }

            // Each position in these arrays, rgbValuesWithoutClouds and rgbValuesWithClouds, corresponds a color. eg
            // First pixel   Second pixel   Third pixel   Forth pixel .... // bitmaps
            //    B G R          B G R         B G R         B G R    .... // rgbValues arrays
            bmptest = new Bitmap(512, 512);
            cloudPoints = new List<Point>();

            for (y = 0; y < wdthHght; y++)
            {
                j = 0;
                for (x = 0; x < wdthHght; x++)
                {
                    p = y * wdthHght * 3 + j;

                    if (rgbValuesWithClouds[p] != rgbValuesWithoutClouds[p])
                    {
                        cloudPoints.Add(new Point(x, y));
                        bmptest.SetPixel(x, y, Color.Red);
                    }

                    j += 3;
                }
            }
            bmptest.Save(@"d:\bmptest1.bmp");
        }

The result of finding the clouds :

detected clouds

Optional : This image is with the ruler on the right that show the possible clouds colors when generating random clouds the colors should be taken from the ruler on the right side. this ruler set the possible clouds rain amount.

image with the ruler on the right side


问:
Kubernetes > Possible to set same deployment container node matching the Loadbalancer external IP node (music / realtime)
Has anyone else encountered a problem with a delay being doubled when using a realtime audio server application in a container with K3s? The issue I am experiencing is that the Loadbalancer is located on a different node from the node where my container is located, and this is causing a delay of twice the normal amount for inputs and outputs. I should mention that I am behind a NAT rule for a specific port and private IP dedicated to this app, but this is not the cause of the issue. Is there any way to resolve this issue?"</p>


问:
Issue with special character like 'é' in database
When I try to fetch and display some data from a database, the specials characters like 'é' don't appear properly.

Watch it : 'problème' word with an issue of display

I have set the table as it is shown here :
table settings

And, here is the code I use to fetch 'problème' :

```<code>    <?php

    $dbServername = "XXX";
    $dbUsername = "XXX";
    $dbPassword = "XXX";
    $dbDatabase = "XXX";

    //connexion
    $mysqli = new mysqli($dbServername, $dbUsername, $dbPassword, $dbDatabase);

    //select the right table
    $resultUser = mysqli_query($mysqli, "SELECT * FROM user");

    $i = 0;
    $dbTableUsers = [];

    //making a table to save the data in
    while($ru = mysqli_fetch_array($resultUser)){
        $dbTableUsers[0][$i] = $ru['firstName'];
        $i++;
    }

    //display the first firstname
    echo $dbTableUsers[0][0];

    //déconnexion
    mysqli_close($mysqli);
?>
</code>```

Body:
When I try to fetch and display some data from a database, the specials characters like 'é' don't appear properly.

Watch it : 'problème' word with an issue of display

I have set the table as it is shown here :
table settings

And, here is the code I use to fetch 'problème' :

    <?php

    $dbServername = "XXX";
    $dbUsername = "XXX";
    $dbPassword = "XXX";
    $dbDatabase = "XXX";

    //connexion
    $mysqli = new mysqli($dbServername, $dbUsername, $dbPassword, $dbDatabase);

    //select the right table
    $resultUser = mysqli_query($mysqli, "SELECT * FROM user");

    $i = 0;
    $dbTableUsers = [];

    //making a table to save the data in
    while($ru = mysqli_fetch_array($resultUser)){
        $dbTableUsers[0][$i] = $ru['firstName'];
        $i++;
    }

    //display the first firstname
    echo $dbTableUsers[0][0];

    //déconnexion
    mysqli_close($mysqli);
?>


问:
How to manage users status (online/offline) in node js using socket.io
hi I am writing a cross platform chat application (mostly focus as a windows app)
I use express on server-side along side mongoDB and i also use socket.io to handle websocket connections.
In frontend i use react electron (a electron app that serve react project's output).
I need to update users status (online/offline) in real time according to their activity
So i used socket to handle users state here is the complete socket configuration

server-side code:

```<code>const http = require("http");
const io = require("socket.io");

const app = require("./app");
const User = require("./models/user");

// initializing a server manually
const httpServer = http.createServer(app);

// creating a socket using the http server
const webSocket = io(httpServer, {
    cors: {
        origin: "http://localhost:3000",
    },
});

global.onlineUsers = new Map();
webSocket.on("connection", (socket) => {
    global.chatSocket = socket;
    let id;
    socket.on("add-user", (userId) => {
        onlineUsers.set(userId, socket.id);
        id = userId;
        User.updateOne({ _id: userId }, { active: true }, (error, user) => {
            if (error) {
                console.error(error);
            } else {
                webSocket.emit("userStatusUpdate", { userId, active: true });
            }
        });
    });

    socket.on("send-msg", (data) => {
        const sendUserSocket = onlineUsers.get(data.to);
        if (sendUserSocket) {
            socket.to(sendUserSocket).emit("msg-receive", data.msg, data.time);
        }
    });

    socket.on("logout", (userId) => {
        User.updateOne(
            { _id: userId },
            { active: false, lastActive: Date.now() },
            (error, user) => {
                if (error) {
                    console.error(error);
                } else {
                    webSocket.emit("userStatusUpdate", {
                        userId,
                        active: false,
                        lastActive: Date.now(),
                    });
                }
            }
        );
    });
    socket.on("disconnect", () => {
        User.updateOne(
            { _id: id },
            { active: false, lastActive: Date.now() },
            (error, user) => {
                if (error) {
                    console.error(error);
                } else {
                    webSocket.emit("userStatusUpdate", {
                        userId: id,
                        active: false,
                        lastActive: Date.now(),
                    });
                }
            }
        );
    });
});

module.exports = httpServer;
</code>```

client side code:

```<code>useEffect(() => {
        if (user) {
            socket.current = io(process.env.REACT_APP_HOST);
            socket.current.emit("add-user", user._id);

            socket.current.on("userStatusUpdate", (data) => {
                setStatus({ ...status, [data.userId]: data.active });
                // console.log(data);
            });

            return () => {
                socket.current.disconnect();
            };
        }
        // console.log(status);
    }, [user, status]);
</code>```

this is doing it but i have some promlems with that sometimes it shows user is offline when he is actually online and sometimes it is glitching
in the console this error allaways shoing constantly

```<code>websocket.js:143 WebSocket connection to 'ws://localhost:3000/socket.io/?EIO=4&transport=websocket&sid=BBcykFQzlFJNJ7sCAGm_' failed: WebSocket is closed before the connection is established.
</code>```

Body:
hi I am writing a cross platform chat application (mostly focus as a windows app)
I use express on server-side along side mongoDB and i also use socket.io to handle websocket connections.
In frontend i use react electron (a electron app that serve react project's output).
I need to update users status (online/offline) in real time according to their activity
So i used socket to handle users state here is the complete socket configuration

server-side code:

const http = require("http");
const io = require("socket.io");

const app = require("./app");
const User = require("./models/user");

// initializing a server manually
const httpServer = http.createServer(app);

// creating a socket using the http server
const webSocket = io(httpServer, {
    cors: {
        origin: "http://localhost:3000",
    },
});

global.onlineUsers = new Map();
webSocket.on("connection", (socket) => {
    global.chatSocket = socket;
    let id;
    socket.on("add-user", (userId) => {
        onlineUsers.set(userId, socket.id);
        id = userId;
        User.updateOne({ _id: userId }, { active: true }, (error, user) => {
            if (error) {
                console.error(error);
            } else {
                webSocket.emit("userStatusUpdate", { userId, active: true });
            }
        });
    });

    socket.on("send-msg", (data) => {
        const sendUserSocket = onlineUsers.get(data.to);
        if (sendUserSocket) {
            socket.to(sendUserSocket).emit("msg-receive", data.msg, data.time);
        }
    });

    socket.on("logout", (userId) => {
        User.updateOne(
            { _id: userId },
            { active: false, lastActive: Date.now() },
            (error, user) => {
                if (error) {
                    console.error(error);
                } else {
                    webSocket.emit("userStatusUpdate", {
                        userId,
                        active: false,
                        lastActive: Date.now(),
                    });
                }
            }
        );
    });
    socket.on("disconnect", () => {
        User.updateOne(
            { _id: id },
            { active: false, lastActive: Date.now() },
            (error, user) => {
                if (error) {
                    console.error(error);
                } else {
                    webSocket.emit("userStatusUpdate", {
                        userId: id,
                        active: false,
                        lastActive: Date.now(),
                    });
                }
            }
        );
    });
});

module.exports = httpServer;

client side code:

useEffect(() => {
        if (user) {
            socket.current = io(process.env.REACT_APP_HOST);
            socket.current.emit("add-user", user._id);

            socket.current.on("userStatusUpdate", (data) => {
                setStatus({ ...status, [data.userId]: data.active });
                // console.log(data);
            });

            return () => {
                socket.current.disconnect();
            };
        }
        // console.log(status);
    }, [user, status]);

this is doing it but i have some promlems with that sometimes it shows user is offline when he is actually online and sometimes it is glitching
in the console this error allaways shoing constantly

websocket.js:143 WebSocket connection to 'ws://localhost:3000/socket.io/?EIO=4&transport=websocket&sid=BBcykFQzlFJNJ7sCAGm_' failed: WebSocket is closed before the connection is established.


问:
How do I check if email in trash or inbox or spam in .net core?
I have this code ?

```<code> MimeMessage message = new MimeMessage();
            MailboxAddress from = new MailboxAddress("Admin",
            "mohammad.jouhari33@gmail.com");
            message.From.Add(from);
            MailboxAddress to = new MailboxAddress("mohammad.jouhari@gmail.com",
            "mohammad.jouhari@gmail.com");
            message.To.Add(to);
            message.Subject = "This is email subject";
            BodyBuilder bodyBuilder = new BodyBuilder();
            bodyBuilder.HtmlBody = "<h1>Hello World!</h1>";
            bodyBuilder.TextBody = "Hello World!";
            message.Body = bodyBuilder.ToMessageBody();
            SmtpClient client = new SmtpClient();
            client.Connect("smtp.gmail.com", 465, true);
            client.Authenticate("mohammad.jouhari33@gmail.com", "pptybpfunwthdgno");
            client.Send(message);
            client.MessageSent += OnMessageSent;
            var s = "";
            client.Disconnect(true);
            client.Dispose();
</code>```

How do I check if email in trash or inbox or spam in .net core ?

Body:
I have this code ?

 MimeMessage message = new MimeMessage();
            MailboxAddress from = new MailboxAddress("Admin",
            "mohammad.jouhari33@gmail.com");
            message.From.Add(from);
            MailboxAddress to = new MailboxAddress("mohammad.jouhari@gmail.com",
            "mohammad.jouhari@gmail.com");
            message.To.Add(to);
            message.Subject = "This is email subject";
            BodyBuilder bodyBuilder = new BodyBuilder();
            bodyBuilder.HtmlBody = "
Hello World!
";
            bodyBuilder.TextBody = "Hello World!";
            message.Body = bodyBuilder.ToMessageBody();
            SmtpClient client = new SmtpClient();
            client.Connect("smtp.gmail.com", 465, true);
            client.Authenticate("mohammad.jouhari33@gmail.com", "pptybpfunwthdgno");
            client.Send(message);
            client.MessageSent += OnMessageSent;
            var s = "";
            client.Disconnect(true);
            client.Dispose();

How do I check if email in trash or inbox or spam in .net core ?


问:
Create fake project in gradle for doing java-platform maven bom generation
Im like gradle java-platform plugin, It allows me to easily create a maven bom for my multi-module library

Everything is fine, but to use it, I need the project to not have a java plugin applied.

```<code>The "java-platform" plugin cannot be applied together with the "java" (or "java-library") plugin. A project is either a platform or a library but cannot be both at the same time.
</code>```

This creates some difficulty, and also does not look pretty, since I have to create a sub project, just to create new maven publication with bom. (from(components["javaPlatform"]))

Is it possible somehow to create a fake project in order to apply this plugin to it, as well as prescribe the settings I need?

PS: I do not want to create a real module for this case, because I want to move this functionality into a plugin later

Body:
Im like gradle java-platform plugin, It allows me to easily create a maven bom for my multi-module library

Everything is fine, but to use it, I need the project to not have a java plugin applied.

The "java-platform" plugin cannot be applied together with the "java" (or "java-library") plugin. A project is either a platform or a library but cannot be both at the same time.

This creates some difficulty, and also does not look pretty, since I have to create a sub project, just to create new maven publication with bom. (from(components["javaPlatform"]))

Is it possible somehow to create a fake project in order to apply this plugin to it, as well as prescribe the settings I need?

PS: I do not want to create a real module for this case, because I want to move this functionality into a plugin later


问:
Fatal Python Error with SQLAlchemy connect_engine
I'm trying to use Pandas to pull data from a remote DB2 database on an M1 Mac. My script works on a Windows 10 system, but I get a fatal error when I run from my Mac. I've never experienced fatal errors before so I'm not sure how to proceed with troubleshooting. Here's my code:

```<code>import pandas as pd
from sqlalchemy import create_engine
import ibm_db
import ibm_db_sa
import os

dsn_database = "mydb"
dsn_hostname = "prod.site.com"
dsn_port = "50001"
dsn_uid = "..."
dsn_pwd = "..."
ssl_trust_store_location = "ROOT.cer"
ssl_trust_password = "..."
credentials = {"host":dsn_hostname,"port":dsn_port,"db":dsn_database,"user":dsn_uid,"pw":dsn_pwd}

mydb_eng = create_engine("db2+ibm_db://{0}:{1}@{2}:{3}/{4};SECURITY=ssl;SSLServerCertificate={5};".format(credentials['user'],credentials['pw'],credentials['host'],str(credentials['port']),credentials['db'],ssl_trust_store_location))

mydb_conn = mydb_eng.connect()

df = pd.read_sql_query('SELECT * FROM TABLE LIMIT 100;', mydb_conn)
</code>```

When I run within a virtual environment in Spyder, I get the following error:

```<code>Fatal Python error: Aborted

Main thread:
Current thread 0x00000002034682c0 (most recent call first):
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/ibm_db_dbi.py", line 629 in connect
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 598 in connect
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/engine/create.py", line 578 in connect
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 680 in __connect
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 386 in __init__
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 271 in _create_connection
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/impl.py", line 143 in _do_get
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 491 in checkout
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 888 in _checkout
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 325 in connect
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 3361 in _wrap_pool_connect
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 3394 in raw_connection
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 96 in __init__
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 3315 in connect
  File "/Users/lwd/Documents/Projects/mydb_Test/sqlalchemy_test.py", line 18 in <module>
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/spyder_kernels/py3compat.py", line 356 in compat_exec
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/spyder_kernels/customize/spydercustomize.py", line 469 in exec_code
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/spyder_kernels/customize/spydercustomize.py", line 611 in _exec_file
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/spyder_kernels/customize/spydercustomize.py", line 524 in runfile
  File "/var/folders/3w/h_s63nl14p75qzww71xm_3fw0000gn/T/ipykernel_14510/3309860273.py", line 1 in <cell line: 1>

Restarting kernel...
</code>```

Line 18 of sqlalchemy_test.py is mydb_conn = mydb_eng.connect(). I don't know what to do with this info. So far I've tried:

Running the code directly within Terminal.

Running the code within Jupyter.

Updating all of my packages.

Using bad username or password to see if I could prompt a different error message.

No progress yet, I get the same outcome regardless. Can anyone help decipher what Python is trying to tell me?

Body:
I'm trying to use Pandas to pull data from a remote DB2 database on an M1 Mac. My script works on a Windows 10 system, but I get a fatal error when I run from my Mac. I've never experienced fatal errors before so I'm not sure how to proceed with troubleshooting. Here's my code:

import pandas as pd
from sqlalchemy import create_engine
import ibm_db
import ibm_db_sa
import os

dsn_database = "mydb"
dsn_hostname = "prod.site.com"
dsn_port = "50001"
dsn_uid = "..."
dsn_pwd = "..."
ssl_trust_store_location = "ROOT.cer"
ssl_trust_password = "..."
credentials = {"host":dsn_hostname,"port":dsn_port,"db":dsn_database,"user":dsn_uid,"pw":dsn_pwd}

mydb_eng = create_engine("db2+ibm_db://{0}:{1}@{2}:{3}/{4};SECURITY=ssl;SSLServerCertificate={5};".format(credentials['user'],credentials['pw'],credentials['host'],str(credentials['port']),credentials['db'],ssl_trust_store_location))

mydb_conn = mydb_eng.connect()

df = pd.read_sql_query('SELECT * FROM TABLE LIMIT 100;', mydb_conn)

When I run within a virtual environment in Spyder, I get the following error:

Fatal Python error: Aborted

Main thread:
Current thread 0x00000002034682c0 (most recent call first):
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/ibm_db_dbi.py", line 629 in connect
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 598 in connect
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/engine/create.py", line 578 in connect
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 680 in __connect
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 386 in __init__
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 271 in _create_connection
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/impl.py", line 143 in _do_get
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 491 in checkout
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 888 in _checkout
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 325 in connect
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 3361 in _wrap_pool_connect
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 3394 in raw_connection
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 96 in __init__
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 3315 in connect
  File "/Users/lwd/Documents/Projects/mydb_Test/sqlalchemy_test.py", line 18 in <module>
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/spyder_kernels/py3compat.py", line 356 in compat_exec
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/spyder_kernels/customize/spydercustomize.py", line 469 in exec_code
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/spyder_kernels/customize/spydercustomize.py", line 611 in _exec_file
  File "/Users/lwd/opt/anaconda3/envs/py39/lib/python3.9/site-packages/spyder_kernels/customize/spydercustomize.py", line 524 in runfile
  File "/var/folders/3w/h_s63nl14p75qzww71xm_3fw0000gn/T/ipykernel_14510/3309860273.py", line 1 in <cell line: 1>

Restarting kernel...

Line 18 of sqlalchemy_test.py is mydb_conn = mydb_eng.connect(). I don't know what to do with this info. So far I've tried:

Running the code directly within Terminal.

Running the code within Jupyter.

Updating all of my packages.

Using bad username or password to see if I could prompt a different error message.

No progress yet, I get the same outcome regardless. Can anyone help decipher what Python is trying to tell me?


问:
TypeError: Cannot read properties of undefined
Im trying open a modal in my principal component, but i have this problem when a try to call function abrirModal():

TypeError: Cannot read properties of undefined (reading 'abrirModal')

button in my principal component:
cotacaooffline.component.html:

<button type="submit" class="btn btn-primary btn-blue btn-block"
                (click)="openModalEbao()">
               Text
</button>
```
<p>TS <code>cotaçãooffline.component:</code></p>
```import {ModalAlterarEbaoComponent} from 'src/app/components/modals/modal-alterar-ebao/modal-alterar-ebao.component'

export class CotacaoofflineComponent implements OnInit, AfterViewInit {

  @ViewChild(ModalAlterarEbaoComponent) modalAlterarEbaoComponent: ModalAlterarEbaoComponent;

  ...others @ViewChild }

    openModalEbao(){
    this.modalAlterarEbaoComponent.abrirModal();
  }
```
<p><code>ModalAlterarEbaoComponent:</code></p>
```import { ModalDirective } from 'ngx-bootstrap/modal';
@ViewChild('modalEbao', {static: false})
  modalEbao: ModalDirective;

  abrirModal() {
    this.modalEbao.show();
  }
```
<p><code>ModaDirective</code> File:</p>
```import { ComponentRef, ElementRef, EventEmitter, OnDestroy, OnInit, Renderer2, ViewContainerRef } from '@angular/core';
import { ModalBackdropComponent } from './modal-backdrop.component';
import { ModalOptions } from './modal-options.class';
import { ComponentLoaderFactory } from 'ngx-bootstrap/component-loader';
/** Mark any code with directive to show it's content in modal */
import * as ɵngcc0 from '@angular/core';
export declare class ModalDirective implements OnDestroy, OnInit {
    private _element;
    private _renderer;
    /** allows to set modal configuration via element property */
    set config(conf: ModalOptions);
    get config(): ModalOptions;
    /** This event fires immediately when the `show` instance method is called. */
    onShow: EventEmitter<ModalDirective>;
    /** This event is fired when the modal has been made visible to the user
     * (will wait for CSS transitions to complete)
     */
    onShown: EventEmitter<ModalDirective>;
    /** This event is fired immediately when
     * the hide instance method has been called.
     */
    onHide: EventEmitter<ModalDirective>;
    /** This event is fired when the modal has finished being
     * hidden from the user (will wait for CSS transitions to complete).
     */
    onHidden: EventEmitter<ModalDirective>;
    /** This field contains last dismiss reason.
     * Possible values: `backdrop-click`, `esc` and `id: number`
     * (if modal was closed by direct call of `.hide()`).
     */
    dismissReason: string;
    get isShown(): boolean;
    protected _config: ModalOptions;
    protected _isShown: boolean;
    protected isBodyOverflowing: boolean;
    protected originalBodyPadding: number;
    protected scrollbarWidth: number;
    protected timerHideModal: number;
    protected timerRmBackDrop: number;
    protected backdrop: ComponentRef<ModalBackdropComponent>;
    private _backdrop;
    private isNested;
    private clickStartedInContent;
    constructor(_element: ElementRef, _viewContainerRef: ViewContainerRef, _renderer: Renderer2, clf: ComponentLoaderFactory, modalDefaultOption: ModalOptions);
    onClickStarted(event: MouseEvent): void;
    onClickStop(event: MouseEvent): void;
    onEsc(event: KeyboardEvent): void;
    ngOnDestroy(): void;
    ngOnInit(): void;
    /** Allows to manually toggle modal visibility */
    toggle(): void;
    /** Allows to manually open modal */
    show(): void;
    /** Allows to manually close modal */
    hide(event?: Event): void;
    /** Private methods @internal */
    protected getConfig(config?: ModalOptions): ModalOptions;
    /**
     *  Show dialog
     *  @internal
     */
    protected showElement(): void;
    /** @internal */
    protected hideModal(): void;
    /** @internal */
    protected showBackdrop(callback?: Function): void;
    /** @internal */
    protected removeBackdrop(): void;
    /** Events tricks */
    protected focusOtherModal(): void;
    /** @internal */
    protected resetAdjustments(): void;
    /** Scroll bar tricks */
    /** @internal */
    protected checkScrollbar(): void;
    protected setScrollbar(): void;
    protected resetScrollbar(): void;
    protected getScrollbarWidth(): number;
    static ɵfac: ɵngcc0.ɵɵFactoryDeclaration<ModalDirective, [null, null, null, null, { optional: true; }]>;
    static ɵdir: ɵngcc0.ɵɵDirectiveDeclaration<ModalDirective, "[bsModal]", ["bs-modal"], { "config": "config"; }, { "onShow": "onShow"; "onShown": "onShown"; "onHide": "onHide"; "onHidden": "onHidden"; }, never>;
}

//# sourceMappingURL=modal.directive.d.ts.map
```

Any help is welcome :) tks!

Body:
Im trying open a modal in my principal component, but i have this problem when a try to call function abrirModal():

TypeError: Cannot read properties of undefined (reading 'abrirModal')

button in my principal component:
cotacaooffline.component.html:

<button type="submit" class="btn btn-primary btn-blue btn-block"
                (click)="openModalEbao()">
               Text
</button>

TS cotaçãooffline.component:

import {ModalAlterarEbaoComponent} from 'src/app/components/modals/modal-alterar-ebao/modal-alterar-ebao.component'

export class CotacaoofflineComponent implements OnInit, AfterViewInit {

  @ViewChild(ModalAlterarEbaoComponent) modalAlterarEbaoComponent: ModalAlterarEbaoComponent;

  ...others @ViewChild }

    openModalEbao(){
    this.modalAlterarEbaoComponent.abrirModal();
  }

ModalAlterarEbaoComponent:

import { ModalDirective } from 'ngx-bootstrap/modal';
@ViewChild('modalEbao', {static: false})
  modalEbao: ModalDirective;

  abrirModal() {
    this.modalEbao.show();
  }

ModaDirective File:

import { ComponentRef, ElementRef, EventEmitter, OnDestroy, OnInit, Renderer2, ViewContainerRef } from '@angular/core';
import { ModalBackdropComponent } from './modal-backdrop.component';
import { ModalOptions } from './modal-options.class';
import { ComponentLoaderFactory } from 'ngx-bootstrap/component-loader';
/** Mark any code with directive to show it's content in modal */
import * as ɵngcc0 from '@angular/core';
export declare class ModalDirective implements OnDestroy, OnInit {
    private _element;
    private _renderer;
    /** allows to set modal configuration via element property */
    set config(conf: ModalOptions);
    get config(): ModalOptions;
    /** This event fires immediately when the `show` instance method is called. */
    onShow: EventEmitter<ModalDirective>;
    /** This event is fired when the modal has been made visible to the user
     * (will wait for CSS transitions to complete)
     */
    onShown: EventEmitter<ModalDirective>;
    /** This event is fired immediately when
     * the hide instance method has been called.
     */
    onHide: EventEmitter<ModalDirective>;
    /** This event is fired when the modal has finished being
     * hidden from the user (will wait for CSS transitions to complete).
     */
    onHidden: EventEmitter<ModalDirective>;
    /** This field contains last dismiss reason.
     * Possible values: `backdrop-click`, `esc` and `id: number`
     * (if modal was closed by direct call of `.hide()`).
     */
    dismissReason: string;
    get isShown(): boolean;
    protected _config: ModalOptions;
    protected _isShown: boolean;
    protected isBodyOverflowing: boolean;
    protected originalBodyPadding: number;
    protected scrollbarWidth: number;
    protected timerHideModal: number;
    protected timerRmBackDrop: number;
    protected backdrop: ComponentRef<ModalBackdropComponent>;
    private _backdrop;
    private isNested;
    private clickStartedInContent;
    constructor(_element: ElementRef, _viewContainerRef: ViewContainerRef, _renderer: Renderer2, clf: ComponentLoaderFactory, modalDefaultOption: ModalOptions);
    onClickStarted(event: MouseEvent): void;
    onClickStop(event: MouseEvent): void;
    onEsc(event: KeyboardEvent): void;
    ngOnDestroy(): void;
    ngOnInit(): void;
    /** Allows to manually toggle modal visibility */
    toggle(): void;
    /** Allows to manually open modal */
    show(): void;
    /** Allows to manually close modal */
    hide(event?: Event): void;
    /** Private methods @internal */
    protected getConfig(config?: ModalOptions): ModalOptions;
    /**
     *  Show dialog
     *  @internal
     */
    protected showElement(): void;
    /** @internal */
    protected hideModal(): void;
    /** @internal */
    protected showBackdrop(callback?: Function): void;
    /** @internal */
    protected removeBackdrop(): void;
    /** Events tricks */
    protected focusOtherModal(): void;
    /** @internal */
    protected resetAdjustments(): void;
    /** Scroll bar tricks */
    /** @internal */
    protected checkScrollbar(): void;
    protected setScrollbar(): void;
    protected resetScrollbar(): void;
    protected getScrollbarWidth(): number;
    static ɵfac: ɵngcc0.ɵɵFactoryDeclaration<ModalDirective, [null, null, null, null, { optional: true; }]>;
    static ɵdir: ɵngcc0.ɵɵDirectiveDeclaration<ModalDirective, "[bsModal]", ["bs-modal"], { "config": "config"; }, { "onShow": "onShow"; "onShown": "onShown"; "onHide": "onHide"; "onHidden": "onHidden"; }, never>;
}

//# sourceMappingURL=modal.directive.d.ts.map

Any help is welcome :) tks!