问:
How to pass data to an action using redux-toolkit in react js?
I'm trying to display a list of categories from mongodb. Each user can see only his own categories.
I'm using Reactjs and redux-toolkit in the frontend and NodeJs in the backend.

The issue is that when I get the data, fetchAll returns all categories. What I want is only the categories that belongs to the connected user.

catergoryController.js

```<code>// Retrieve and return all categories.
exports.findAll = async (req, res) => {
  const { pageIndex, pageSize, sort, query, userId } = req.body;
  const { order, key } = sort;

  // query the Category model and filter by user
  Category.find({ User: userId }, (err, categories) => {
    if (err) {
      return res.status(500).send(err);
    }

    let data = categories;
    let total = categories.length;

    // sort data if necessary
    if ((key === 'name' || key === 'description') && order) {
      data.sort(datatable.sortBy(key, order === 'desc', (a) => a.toUpperCase()));
    } else {
      data.sort(datatable.sortBy(key, order === 'desc', parseInt));
    }

    // apply wildcard search if necessary
    if (query) {
      data = datatable.wildCardSearch(data, query);
      total = data.length;
    }
    data = datatable.paginate(data, pageSize, pageIndex);

    // return response
    res.send({
      data: data,
      total: total
    });
  });
}
</code>```

Route:

```<code>router.post("/list", categoryController.findAll);
</code>```

React component:

```<code>import React, { useEffect, useMemo } from 'react'
import { DataTable } from 'components/shared'
import { HiOutlinePencil, HiOutlineTrash } from 'react-icons/hi'
import { useDispatch, useSelector } from 'react-redux'
import { getCategories, setTableData } from '../store/dataSlice'
import { setSortedColumn, setSelectedCategory } from '../store/stateSlice'
import { toggleDeleteConfirmation } from '../store/stateSlice'
import useThemeClass from 'utils/hooks/useThemeClass'
import CategoryDeleteConfirmation from './CategoryDeleteConfirmation'
import { useNavigate } from 'react-router-dom'
import cloneDeep from 'lodash/cloneDeep'

const ActionColumn = ({ row }) => {
  const dispatch = useDispatch()
  const { textTheme } = useThemeClass()
  const navigate = useNavigate()

  const onEdit = () => {
    navigate(`/events/category/edit/${row.id}`)
  }

  const onDelete = () => {
    dispatch(toggleDeleteConfirmation(true))
    dispatch(setSelectedCategory(row.id))
  }

  return (
    <div className="flex justify-end text-lg">
      <span
        className={`cursor-pointer p-2 hover:${textTheme}`}
        onClick={onEdit}
      >
        <HiOutlinePencil />
      </span>
      <span
        className="cursor-pointer p-2 hover:text-red-500"
        onClick={onDelete}
      >
        <HiOutlineTrash />
      </span>
    </div>
  )
}

const CategoryTable = () => {
  const dispatch = useDispatch()

  const { pageIndex, pageSize, sort, query, total } = useSelector(
    (state) => state.GategoriesList.data.tableData,
  )
   const userInfo = useSelector((state) => state.auth.user)
  const filterData = useSelector(
    (state) => state.GategoriesList.data.filterData,
  )
  const loading = useSelector((state) => state.GategoriesList.data.loading)
  const data = useSelector((state) => state.GategoriesList.data.GategoriesList)

  const fetchData = () => {

    dispatch(getCategories({ pageIndex, pageSize, sort, query, filterData, userId:userInfo._id }))
 // console.log({pageIndex, pageSize, sort, query, filterData, userId:userInfo._id})
  }

  useEffect(() => {
    fetchData()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageIndex, pageSize, sort])

  const tableData = useMemo(
    () => ({ pageIndex, pageSize, sort, query, total }),
    [pageIndex, pageSize, sort, query, total],
  )

  const columns = useMemo(
    () => [
      {
        Header: 'Category',
        accessor: 'name',
        sortable: true,
        Cell: (props) => {
          const row = props.row.original
          return <span className="capitalize">{row.name}</span>
        },
      },
      {
        Header: 'Description',
        accessor: 'description',
        sortable: true,
        Cell: (props) => {
          const row = props.row.original
          return <span className="capitalize">{row.description}</span>
        },
      },
      {
        Header: '',
        id: 'action',
        accessor: (row) => row,
        Cell: (props) => <ActionColumn row={props.row.original} />,
      },
    ],
    [],
  )

  const onPaginationChange = (page) => {
    const newTableData = cloneDeep(tableData)
    newTableData.pageIndex = page
    dispatch(setTableData(newTableData))
  }

  const onSelectChange = (value) => {
    const newTableData = cloneDeep(tableData)
    newTableData.pageSize = Number(value)
    newTableData.pageIndex = 1
    dispatch(setTableData(newTableData))
  }

  const onSort = (sort, sortingColumn) => {
    const newTableData = cloneDeep(tableData)
    newTableData.sort = sort
    dispatch(setTableData(newTableData))
    dispatch(setSortedColumn(sortingColumn))
  }
  return (
    <>

      <DataTable
        columns={columns}
        data={data}
        skeletonAvatarColumns={[0]}
        skeletonAvatarProps={{ className: 'rounded-md' }}
        loading={loading}
        pagingData={tableData}
        onPaginationChange={onPaginationChange}
        onSelectChange={onSelectChange}
        onSort={onSort}
      />
      <CategoryDeleteConfirmation />
    </>
  )
}

export default CategoryTable

</code>```

dataSlice:

```<code>import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { apiGetCategories, apiDeleteCategory } from 'services/CategoriesService'

export const getCategories = createAsyncThunk('categories/data/getCategories',async (data) => {
    const response = await apiGetCategories(data)
    return response.data
})

export const deleteCategory = async (data) => {
    const response = await apiDeleteCategory(data)
    return response.data
}

export const initialTableData = {
    userId: '',
    total: 0,
    pageIndex: 1,
    pageSize: 10,
    query: '',
    sort: {
        order: '',
        key: ''
    }
}

export const initialFilterData = {
    name: '',
    category: ['name', 'description'],
    status: [0, 1, 2],
    CatgoriesStatus: 0,
}

const dataSlice = createSlice({
    name: 'categories/data',
    initialState: {
        loading: false,
        GategoriesList: [],
        tableData: initialTableData,
        filterData: initialFilterData,
    },
    reducers: {
        updateCategoryList: (state, action) => {
            state.GategoriesList = action.payload
        },
        setTableData: (state, action) => {
            state.tableData = action.payload
        },
        setFilterData: (state, action) => {
            state.filterData = action.payload
        },
    },
    extraReducers: {
        [getCategories.fulfilled]: (state, action) => {
            state.GategoriesList = action.payload.data
            state.tableData.total = action.payload.total
            state.loading = false
        },
        [getCategories.pending]: (state) => {
            state.loading = true
        },
    }
})

export const { updateCategoryList, setTableData,  setFilterData, setSortedColumn } = dataSlice.actions

export default dataSlice.reducer

</code>```
```<code></code>```

Body:
I'm trying to display a list of categories from mongodb. Each user can see only his own categories.
I'm using Reactjs and redux-toolkit in the frontend and NodeJs in the backend.

The issue is that when I get the data, fetchAll returns all categories. What I want is only the categories that belongs to the connected user.

catergoryController.js

// Retrieve and return all categories.
exports.findAll = async (req, res) => {
  const { pageIndex, pageSize, sort, query, userId } = req.body;
  const { order, key } = sort;

  // query the Category model and filter by user
  Category.find({ User: userId }, (err, categories) => {
    if (err) {
      return res.status(500).send(err);
    }

    let data = categories;
    let total = categories.length;

    // sort data if necessary
    if ((key === 'name' || key === 'description') && order) {
      data.sort(datatable.sortBy(key, order === 'desc', (a) => a.toUpperCase()));
    } else {
      data.sort(datatable.sortBy(key, order === 'desc', parseInt));
    }

    // apply wildcard search if necessary
    if (query) {
      data = datatable.wildCardSearch(data, query);
      total = data.length;
    }
    data = datatable.paginate(data, pageSize, pageIndex);

    // return response
    res.send({
      data: data,
      total: total
    });
  });
}

Route:

router.post("/list", categoryController.findAll);

React component:

import React, { useEffect, useMemo } from 'react'
import { DataTable } from 'components/shared'
import { HiOutlinePencil, HiOutlineTrash } from 'react-icons/hi'
import { useDispatch, useSelector } from 'react-redux'
import { getCategories, setTableData } from '../store/dataSlice'
import { setSortedColumn, setSelectedCategory } from '../store/stateSlice'
import { toggleDeleteConfirmation } from '../store/stateSlice'
import useThemeClass from 'utils/hooks/useThemeClass'
import CategoryDeleteConfirmation from './CategoryDeleteConfirmation'
import { useNavigate } from 'react-router-dom'
import cloneDeep from 'lodash/cloneDeep'

const ActionColumn = ({ row }) => {
  const dispatch = useDispatch()
  const { textTheme } = useThemeClass()
  const navigate = useNavigate()

  const onEdit = () => {
    navigate(`/events/category/edit/${row.id}`)
  }

  const onDelete = () => {
    dispatch(toggleDeleteConfirmation(true))
    dispatch(setSelectedCategory(row.id))
  }

  return (

      <span
        className={`cursor-pointer p-2 hover:${textTheme}`}
        onClick={onEdit}
      >
        <HiOutlinePencil />

        <HiOutlineTrash />

  )
}

const CategoryTable = () => {
  const dispatch = useDispatch()

  const { pageIndex, pageSize, sort, query, total } = useSelector(
    (state) => state.GategoriesList.data.tableData,
  )
   const userInfo = useSelector((state) => state.auth.user)
  const filterData = useSelector(
    (state) => state.GategoriesList.data.filterData,
  )
  const loading = useSelector((state) => state.GategoriesList.data.loading)
  const data = useSelector((state) => state.GategoriesList.data.GategoriesList)

  const fetchData = () => {

    dispatch(getCategories({ pageIndex, pageSize, sort, query, filterData, userId:userInfo._id }))
 // console.log({pageIndex, pageSize, sort, query, filterData, userId:userInfo._id})
  }

  useEffect(() => {
    fetchData()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageIndex, pageSize, sort])

  const tableData = useMemo(
    () => ({ pageIndex, pageSize, sort, query, total }),
    [pageIndex, pageSize, sort, query, total],
  )

  const columns = useMemo(
    () => [
      {
        Header: 'Category',
        accessor: 'name',
        sortable: true,
        Cell: (props) => {
          const row = props.row.original
          return {row.name}
        },
      },
      {
        Header: 'Description',
        accessor: 'description',
        sortable: true,
        Cell: (props) => {
          const row = props.row.original
          return {row.description}
        },
      },
      {
        Header: '',
        id: 'action',
        accessor: (row) => row,
        Cell: (props) => <ActionColumn row={props.row.original} />,
      },
    ],
    [],
  )

  const onPaginationChange = (page) => {
    const newTableData = cloneDeep(tableData)
    newTableData.pageIndex = page
    dispatch(setTableData(newTableData))
  }

  const onSelectChange = (value) => {
    const newTableData = cloneDeep(tableData)
    newTableData.pageSize = Number(value)
    newTableData.pageIndex = 1
    dispatch(setTableData(newTableData))
  }

  const onSort = (sort, sortingColumn) => {
    const newTableData = cloneDeep(tableData)
    newTableData.sort = sort
    dispatch(setTableData(newTableData))
    dispatch(setSortedColumn(sortingColumn))
  }
  return (
    <>

      <DataTable
        columns={columns}
        data={data}
        skeletonAvatarColumns={[0]}
        skeletonAvatarProps={{ className: 'rounded-md' }}
        loading={loading}
        pagingData={tableData}
        onPaginationChange={onPaginationChange}
        onSelectChange={onSelectChange}
        onSort={onSort}
      />
      <CategoryDeleteConfirmation />
    </>
  )
}

export default CategoryTable

dataSlice:

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { apiGetCategories, apiDeleteCategory } from 'services/CategoriesService'

export const getCategories = createAsyncThunk('categories/data/getCategories',async (data) => {
    const response = await apiGetCategories(data)
    return response.data
})

export const deleteCategory = async (data) => {
    const response = await apiDeleteCategory(data)
    return response.data
}

export const initialTableData = {
    userId: '',
    total: 0,
    pageIndex: 1,
    pageSize: 10,
    query: '',
    sort: {
        order: '',
        key: ''
    }
}

export const initialFilterData = {
    name: '',
    category: ['name', 'description'],
    status: [0, 1, 2],
    CatgoriesStatus: 0,
}

const dataSlice = createSlice({
    name: 'categories/data',
    initialState: {
        loading: false,
        GategoriesList: [],
        tableData: initialTableData,
        filterData: initialFilterData,
    },
    reducers: {
        updateCategoryList: (state, action) => {
            state.GategoriesList = action.payload
        },
        setTableData: (state, action) => {
            state.tableData = action.payload
        },
        setFilterData: (state, action) => {
            state.filterData = action.payload
        },
    },
    extraReducers: {
        [getCategories.fulfilled]: (state, action) => {
            state.GategoriesList = action.payload.data
            state.tableData.total = action.payload.total
            state.loading = false
        },
        [getCategories.pending]: (state) => {
            state.loading = true
        },
    }
})

export const { updateCategoryList, setTableData,  setFilterData, setSortedColumn } = dataSlice.actions

export default dataSlice.reducer


来源: stackexchange

问:
Add CSV field with values from other table
I have this data:

Table A

```<code>pk name
1  Peter
2  Jon
</code>```

Table B

```<code>pk trait    fk_A
1  funny    1
2  generous 1
3  rude     2
</code>```

I want to get this result set:

```<code>pk name traits
1  Peter funny,generous
2  Jon   rude
</code>```

How can I aggregate the trait column of table B and attach it as a CSV field 'traits' to table A?

ContentLicense: CC BY-SA 4.0

Body:
I have this data:

Table A

pk name
1  Peter
2  Jon

Table B

pk trait    fk_A
1  funny    1
2  generous 1
3  rude     2

I want to get this result set:

pk name traits
1  Peter funny,generous
2  Jon   rude

How can I aggregate the trait column of table B and attach it as a CSV field 'traits' to table A?


问:
How to polymorphically serialize a Kotlin enum that implements a sealed interface?
I have the following sealed interface (simplified example):

sealed interface Validation { val result: Int }
```
<p>...which is implemented by several enums - each one for a particular application. For example:</p>
<pre class="lang-kotlin prettyprint-override"><code>@Serializable(with = BoxedSerializer) // one of my attempts, see below
enum class AccountValidation(override val result: Int): Validation {
  UNKNOWN(10),
  BLOCKED(20),
  OK(30)
}

@Serializable(with = BoxedSerializer) // one of my attempts, see below
enum class PasswordValidation(override val result: Int): Validation {
  SHORT(10),
  WEAK(20),
  OK(30)
}

</code>```

I want to use this enum polymorphically in serializable API types, like so:

@Serializable
data class ValidationResult(
  val userName: String,
  val validation: Validation
)
```
<p>I am using Kotlin 1.7.21 with kotlin serialization 1.4.1 on the JVM. Out-of-the-box, this setup does not work, because enums are serialized as primitive types, without a <code>type</code> field for polymorphic serialization. I tried several other attempts:</p>
<ul>
<li>Serialization via a surrogate class, as described in the official documentation, does not seem to work for enums - I end up with a stack overflow, probably from an erroneous recursion.</li>
<li>Custom serialization as described here leads to an internal compiler error.</li>
<li>Surrogate serialization in a generic wrapper class (see example code below): This also fails with an internal compiler error.</li>
</ul>
<pre class="lang-kotlin prettyprint-override"><code>@Serializable
@SerialName("Validation")
data class ValidationBox<T : Validation>(val code: T)

class BoxedSerializer<T : Validation>(private val validationSerializer: KSerializer<T>) : KSerializer<T> {
    private val boxSerializer = ValidationBox.serializer(validationSerializer)
    override val descriptor: SerialDescriptor = boxSerializer.descriptor

    override fun serialize(encoder: Encoder, value: T) {
        val boxed = ValidationBox(value)
        encoder.encodeSerializableValue(boxSerializer, boxed)
    }

    override fun deserialize(decoder: Decoder): T {
        val boxed: ValidationBox<T> = decoder.decodeSerializableValue(boxSerializer)
        return boxed.code
    }
}

@Test
fun `polymorphically serialize and deserialize`() {
    val validation: Validation = AccountValidation.BLOCKED
    val validationJson = Json.encodeToString(validation)
    val validationDeserialized = Json.decodeFromString<Validation>(validationJson)
    assertEquals(validation, validationDeserialized)
}

</code>```

What I would like to get as output (JSON example):

{
  "userName": "myUserName",
  "validation": {"PasswordValidation": "WEAK"}
}
```
<p>or (closer to the standard)</p>
<pre class="lang-json prettyprint-override"><code>{
  "userName": "myUserName",
  "validation": {
      "type": "PasswordValidation",
      "value": "WEAK"
    }
}
</code>```

How would a semi-custom or (if necessary) full-custom serializer look like?

Thanks for your help!

Body:
I have the following sealed interface (simplified example):

sealed interface Validation { val result: Int }

...which is implemented by several enums - each one for a particular application. For example:

@Serializable(with = BoxedSerializer) // one of my attempts, see below
enum class AccountValidation(override val result: Int): Validation {
  UNKNOWN(10),
  BLOCKED(20),
  OK(30)
}

@Serializable(with = BoxedSerializer) // one of my attempts, see below
enum class PasswordValidation(override val result: Int): Validation {
  SHORT(10),
  WEAK(20),
  OK(30)
}

I want to use this enum polymorphically in serializable API types, like so:

@Serializable
data class ValidationResult(
  val userName: String,
  val validation: Validation
)

I am using Kotlin 1.7.21 with kotlin serialization 1.4.1 on the JVM. Out-of-the-box, this setup does not work, because enums are serialized as primitive types, without a type field for polymorphic serialization. I tried several other attempts:

Serialization via a surrogate class, as described in the official documentation, does not seem to work for enums - I end up with a stack overflow, probably from an erroneous recursion.

Custom serialization as described here leads to an internal compiler error.

Surrogate serialization in a generic wrapper class (see example code below): This also fails with an internal compiler error.

@Serializable
@SerialName("Validation")
data class ValidationBox<T : Validation>(val code: T)

class BoxedSerializer<T : Validation>(private val validationSerializer: KSerializer<T>) : KSerializer<T> {
    private val boxSerializer = ValidationBox.serializer(validationSerializer)
    override val descriptor: SerialDescriptor = boxSerializer.descriptor

    override fun serialize(encoder: Encoder, value: T) {
        val boxed = ValidationBox(value)
        encoder.encodeSerializableValue(boxSerializer, boxed)
    }

    override fun deserialize(decoder: Decoder): T {
        val boxed: ValidationBox<T> = decoder.decodeSerializableValue(boxSerializer)
        return boxed.code
    }
}

@Test
fun `polymorphically serialize and deserialize`() {
    val validation: Validation = AccountValidation.BLOCKED
    val validationJson = Json.encodeToString(validation)
    val validationDeserialized = Json.decodeFromString<Validation>(validationJson)
    assertEquals(validation, validationDeserialized)
}

What I would like to get as output (JSON example):

{
  "userName": "myUserName",
  "validation": {"PasswordValidation": "WEAK"}
}

or (closer to the standard)

{
  "userName": "myUserName",
  "validation": {
      "type": "PasswordValidation",
      "value": "WEAK"
    }
}

How would a semi-custom or (if necessary) full-custom serializer look like?

Thanks for your help!


问:
Trying to connect to "ELlight" branded light strip via python to change colors
So I have been tasked with connecting to a strand of lights bought off amazon. These lights can be discovered by bluetooth and are controlled by an app available on the play store and app store. Upon further discovery I found out it's using a sp110e controller using a ble driver. I have this code to get characteristics:

`

```<code>import asyncio
from bleak import BleakClient

async def run(address, loop):
    async with BleakClient(address, loop=loop) as client:
        # Get a list of all the services and characteristics exposed by the BLE device
        services = await client.get_services()
        for service in services:
            print("Service: {0} ({1})".format(service.uuid, service.description))
            for characteristic in service.characteristics:
                print("Characteristic: {0} ({1})".format(characteristic.uuid, characteristic.description))

loop = asyncio.get_event_loop()
loop.run_until_complete(run("75:57:08:05:95:E3", loop))
</code>```

`

and get this result :

```<code>Service: 00001800-0000-1000-8000-00805f9b34fb (Generic Access Profile)
Characteristic: 00002a00-0000-1000-8000-00805f9b34fb (Device Name)
Characteristic: 00002a01-0000-1000-8000-00805f9b34fb (Appearance)
Characteristic: 00002a02-0000-1000-8000-00805f9b34fb (Peripheral Privacy Flag)
Characteristic: 00002a04-0000-1000-8000-00805f9b34fb (Peripheral Preferred Connection Parameters)
Service: 00001801-0000-1000-8000-00805f9b34fb (Generic Attribute Profile)
Service: 0000ffe0-0000-1000-8000-00805f9b34fb (Vendor specific)
Characteristic: 0000ffe1-0000-1000-8000-00805f9b34fb (Vendor specific
</code>```

This was the script to change colors:

`

```<code>import asyncio
from bleak import BleakClient

async def run(address, loop):
    async with BleakClient(address, loop=loop) as client:
        # Convert the RGB color (255, 0, 0) to hexadecimal (FF0000)
        r = 0
        g = 255
        b = 0
        #hex_color = "{:02X}{:02X}{:02X}".format(r, g, b)
        hex_color = "00FF00"
        # Convert the hexadecimal color to bytes
        color_bytes = bytes.fromhex(hex_color)

        # Set the color of the lights
        await client.write_gatt_char("0000ffe1-0000-1000-8000-00805f9b34fb", color_bytes)

loop = asyncio.get_event_loop()
loop.run_until_complete(run("75:57:08:05:95:E3", loop))

This was the error I got
</code>```
```<code>Traceback (most recent call last):
  File "C:\Python311\Lib\site-packages\bleak\backends\winrt\client.py", line 402, in connect
    _, pending = await asyncio.wait(
  File "C:\Python311\Lib\asyncio\tasks.py", line 418, in wait
    return await _wait(fs, timeout, return_when, loop)
  File "C:\Python311\Lib\asyncio\tasks.py", line 525, in _wait
    await waiter
asyncio.exceptions.CancelledError
</code>```

During handling of the above exception, another exception occured:

```<code>   Traceback (most recent call last):
  File "C:/Users/gdelgado/Documents/Testing to change the color to red.py", line 19, in <module>
    loop.run_until_complete(run("75:57:08:05:95:E3", loop))
  File "C:\Python311\Lib\asyncio\base_events.py", line 650, in run_until_complete
    return future.result()
  File "C:/Users/gdelgado/Documents/Testing to change the color to red.py", line 5, in run
    async with BleakClient(address, loop=loop) as client:
  File "C:\Python311\Lib\site-packages\bleak\__init__.py", line 433, in __aenter__
    await self.connect()
  File "C:\Python311\Lib\site-packages\bleak\__init__.py", line 471, in connect
    return await self._backend.connect(**kwargs)
  File "C:\Python311\Lib\site-packages\bleak\backends\winrt\client.py", line 389, in connect
    async with async_timeout.timeout(timeout):
  File "C:\Python311\Lib\site-packages\async_timeout\__init__.py", line 129, in __aexit__
    self._do_exit(exc_type)
  File "C:\Python311\Lib\site-packages\async_timeout\__init__.py", line 212, in _do_exit
    raise asyncio.TimeoutError
TimeoutError

</code>```

I ran the above color changing but seem to have hit a wall. The code was suppose to turn the lights green

Body:
So I have been tasked with connecting to a strand of lights bought off amazon. These lights can be discovered by bluetooth and are controlled by an app available on the play store and app store. Upon further discovery I found out it's using a sp110e controller using a ble driver. I have this code to get characteristics:

`

import asyncio
from bleak import BleakClient

async def run(address, loop):
    async with BleakClient(address, loop=loop) as client:
        # Get a list of all the services and characteristics exposed by the BLE device
        services = await client.get_services()
        for service in services:
            print("Service: {0} ({1})".format(service.uuid, service.description))
            for characteristic in service.characteristics:
                print("Characteristic: {0} ({1})".format(characteristic.uuid, characteristic.description))

loop = asyncio.get_event_loop()
loop.run_until_complete(run("75:57:08:05:95:E3", loop))

`

and get this result :

Service: 00001800-0000-1000-8000-00805f9b34fb (Generic Access Profile)
Characteristic: 00002a00-0000-1000-8000-00805f9b34fb (Device Name)
Characteristic: 00002a01-0000-1000-8000-00805f9b34fb (Appearance)
Characteristic: 00002a02-0000-1000-8000-00805f9b34fb (Peripheral Privacy Flag)
Characteristic: 00002a04-0000-1000-8000-00805f9b34fb (Peripheral Preferred Connection Parameters)
Service: 00001801-0000-1000-8000-00805f9b34fb (Generic Attribute Profile)
Service: 0000ffe0-0000-1000-8000-00805f9b34fb (Vendor specific)
Characteristic: 0000ffe1-0000-1000-8000-00805f9b34fb (Vendor specific

This was the script to change colors:

`

import asyncio
from bleak import BleakClient

async def run(address, loop):
    async with BleakClient(address, loop=loop) as client:
        # Convert the RGB color (255, 0, 0) to hexadecimal (FF0000)
        r = 0
        g = 255
        b = 0
        #hex_color = "{:02X}{:02X}{:02X}".format(r, g, b)
        hex_color = "00FF00"
        # Convert the hexadecimal color to bytes
        color_bytes = bytes.fromhex(hex_color)

        # Set the color of the lights
        await client.write_gatt_char("0000ffe1-0000-1000-8000-00805f9b34fb", color_bytes)

loop = asyncio.get_event_loop()
loop.run_until_complete(run("75:57:08:05:95:E3", loop))

This was the error I got

Traceback (most recent call last):
  File "C:\Python311\Lib\site-packages\bleak\backends\winrt\client.py", line 402, in connect
    _, pending = await asyncio.wait(
  File "C:\Python311\Lib\asyncio\tasks.py", line 418, in wait
    return await _wait(fs, timeout, return_when, loop)
  File "C:\Python311\Lib\asyncio\tasks.py", line 525, in _wait
    await waiter
asyncio.exceptions.CancelledError

During handling of the above exception, another exception occured:

   Traceback (most recent call last):
  File "C:/Users/gdelgado/Documents/Testing to change the color to red.py", line 19, in <module>
    loop.run_until_complete(run("75:57:08:05:95:E3", loop))
  File "C:\Python311\Lib\asyncio\base_events.py", line 650, in run_until_complete
    return future.result()
  File "C:/Users/gdelgado/Documents/Testing to change the color to red.py", line 5, in run
    async with BleakClient(address, loop=loop) as client:
  File "C:\Python311\Lib\site-packages\bleak\__init__.py", line 433, in __aenter__
    await self.connect()
  File "C:\Python311\Lib\site-packages\bleak\__init__.py", line 471, in connect
    return await self._backend.connect(**kwargs)
  File "C:\Python311\Lib\site-packages\bleak\backends\winrt\client.py", line 389, in connect
    async with async_timeout.timeout(timeout):
  File "C:\Python311\Lib\site-packages\async_timeout\__init__.py", line 129, in __aexit__
    self._do_exit(exc_type)
  File "C:\Python311\Lib\site-packages\async_timeout\__init__.py", line 212, in _do_exit
    raise asyncio.TimeoutError
TimeoutError

I ran the above color changing but seem to have hit a wall. The code was suppose to turn the lights green


问:
Question about relating participants to a MessageThread
I am trying to implement a messaging system. I am trying to include all the Users(recipients) into a MessageThread as UserID as shown in the picture. While it seems to work, I figured out that the UserID in MessageThread (as a foreign key) can only relate to specific User in the Users table. I am trying to see if I can include all the Users at once when a new MessageThread is started instead of inserting MessageThread with same MessageThreadID for multiple times(think of it like there are 100 participants...). I am thinking of replacing UserID with array of UserID but do not know if it is a common way to do it.

ERD of Messaging System

MessageThread has a MessageThreadID as Primary key and UserID as a foreign key relating to Users table. When I join the MessageThread table and Users table, I should be able to get detail User info of a participated User like UserName, FirstName, etc .

Updated:

I followed this guide as recommended. I created table type called ThreadParticipantsTableType with UserID as attribute and a stored procedure called up_insert_MessageThread to insert Threads.

For the last step of this guide, it told me to declare a variable  and inserting data into the table(to be insert into up_insert_MessageThread procedure). Since data to be insert is UserID(recipient) and it is to be entered by sender, so I created another procedure called addThreadParticipants to add UserIDs to the table and to execute up_insert_MessageThread to insert a thread. After execution, nothing changed to the MessageThread table. I wonder if there is something I did wrong?

```<code>Create type ThreadParticipantsTableType as table
(
    UserID int
);
GO

ALTER PROCEDURE [dbo].[up_insert_MessageThread]
(
    @TVP ThreadParticipantsTableType READONLY
)

AS

INSERT INTO dbo.MessageThread
select * from @TVP

return

Alter procedure dbo.addThreadParticipants
(
    @UserID int
)
AS

DECLARE @ThreadParticipantsTVP AS ThreadParticipantsTableType;

INSERT INTO @ThreadParticipantsTVP (UserID)
   values (@UserID)

/** for sample execution **/
EXEC dbo.addThreadParticipants @UserID=111111;

EXEC dbo.up_insert_MessageThread @ThreadParticipantsTVP;

return
</code>```

Body:
I am trying to implement a messaging system. I am trying to include all the Users(recipients) into a MessageThread as UserID as shown in the picture. While it seems to work, I figured out that the UserID in MessageThread (as a foreign key) can only relate to specific User in the Users table. I am trying to see if I can include all the Users at once when a new MessageThread is started instead of inserting MessageThread with same MessageThreadID for multiple times(think of it like there are 100 participants...). I am thinking of replacing UserID with array of UserID but do not know if it is a common way to do it.

ERD of Messaging System

MessageThread has a MessageThreadID as Primary key and UserID as a foreign key relating to Users table. When I join the MessageThread table and Users table, I should be able to get detail User info of a participated User like UserName, FirstName, etc .

Updated:

I followed this guide as recommended. I created table type called ThreadParticipantsTableType with UserID as attribute and a stored procedure called up_insert_MessageThread to insert Threads.

For the last step of this guide, it told me to declare a variable  and inserting data into the table(to be insert into up_insert_MessageThread procedure). Since data to be insert is UserID(recipient) and it is to be entered by sender, so I created another procedure called addThreadParticipants to add UserIDs to the table and to execute up_insert_MessageThread to insert a thread. After execution, nothing changed to the MessageThread table. I wonder if there is something I did wrong?

Create type ThreadParticipantsTableType as table
(
    UserID int
);
GO

ALTER PROCEDURE [dbo].[up_insert_MessageThread]
(
    @TVP ThreadParticipantsTableType READONLY
)

AS

INSERT INTO dbo.MessageThread
select * from @TVP

return

Alter procedure dbo.addThreadParticipants
(
    @UserID int
)
AS

DECLARE @ThreadParticipantsTVP AS ThreadParticipantsTableType;

INSERT INTO @ThreadParticipantsTVP (UserID)
   values (@UserID)

/** for sample execution **/
EXEC dbo.addThreadParticipants @UserID=111111;

EXEC dbo.up_insert_MessageThread @ThreadParticipantsTVP;

return


问:
Why is Graphics2D drrawing diferrent sized images with the same code in different environments
I have a requirement for generating images from the pages of pdf files so it can be processed by a legacy application that will send them to a very specific printer.

I have written some code to convert the pages in the .pdf file to .png files using a mix of pdfbox and awt. Below is the code adapted for publishing here:

```<code>import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

public class ImageConverter {

    public static void main(String[] args) throws IOException {
        String pdfFilePath = "input_folder";
        String imageFilePath = "output_folder";
        int width = 1540;
        int height = 2200;
        float dpi = (float) 299.3;
        PDDocument document = PDDocument.load(new File(pdfFilePath));
        convertPdftoPng(document, imageFilePath, width, height, dpi);
    }

    private static void convertPdftoPng(PDDocument document, String imageFilePath, int width, int height, float dpi)
            throws IOException {
        PDFRenderer pdfRenderer = new PDFRenderer(document);

        for (int page = 0; page < document.getNumberOfPages(); page++)
        {
            BufferedImage outputImage = pdfRenderer.renderImageWithDPI(page, dpi, ImageType.RGB);
            ImageIO.write(outputImage, "png", new java.io.File(imageFilePath + "00" + (page + 1) + ".png"));
        }
        document.close();
    }
}

</code>```

Now, while testing the code, I found an odd behaviour, where depending on the environment the code runs, the output file has a different resolution (x and y pixels), based on the DPI.

When running on my windows machine, with DPI 299.3, the output is 1540 x 2204, which is close to the intended result, whilst to achieve a similar resolution in our KaaS environment, DPI needs to be 186, to achieve a resolution of 1537x 2197.

Now, on my machine, I'm running this with eclipse bundled JVM (Java 19), and the project is configured to run on Java 11.

On the server, which is running inside a Kubernetes pod with tomcat, where we're running the code for testing purposes, the JVM is running Java 11 (OpenJDK).

edit. Additionally, this code is to be run on the backend. There is a file listener for the input_folder, that will start the pdf processing (as soon as another system uploads the file through sftp) and output the images. There is no user interaction for this.

Any suggestions on what might be causing the difference on the resolution and how I can address it?

Body:
I have a requirement for generating images from the pages of pdf files so it can be processed by a legacy application that will send them to a very specific printer.

I have written some code to convert the pages in the .pdf file to .png files using a mix of pdfbox and awt. Below is the code adapted for publishing here:

import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

public class ImageConverter {

    public static void main(String[] args) throws IOException {
        String pdfFilePath = "input_folder";
        String imageFilePath = "output_folder";
        int width = 1540;
        int height = 2200;
        float dpi = (float) 299.3;
        PDDocument document = PDDocument.load(new File(pdfFilePath));
        convertPdftoPng(document, imageFilePath, width, height, dpi);
    }

    private static void convertPdftoPng(PDDocument document, String imageFilePath, int width, int height, float dpi)
            throws IOException {
        PDFRenderer pdfRenderer = new PDFRenderer(document);

        for (int page = 0; page < document.getNumberOfPages(); page++)
        {
            BufferedImage outputImage = pdfRenderer.renderImageWithDPI(page, dpi, ImageType.RGB);
            ImageIO.write(outputImage, "png", new java.io.File(imageFilePath + "00" + (page + 1) + ".png"));
        }
        document.close();
    }
}

Now, while testing the code, I found an odd behaviour, where depending on the environment the code runs, the output file has a different resolution (x and y pixels), based on the DPI.

When running on my windows machine, with DPI 299.3, the output is 1540 x 2204, which is close to the intended result, whilst to achieve a similar resolution in our KaaS environment, DPI needs to be 186, to achieve a resolution of 1537x 2197.

Now, on my machine, I'm running this with eclipse bundled JVM (Java 19), and the project is configured to run on Java 11.

On the server, which is running inside a Kubernetes pod with tomcat, where we're running the code for testing purposes, the JVM is running Java 11 (OpenJDK).

edit. Additionally, this code is to be run on the backend. There is a file listener for the input_folder, that will start the pdf processing (as soon as another system uploads the file through sftp) and output the images. There is no user interaction for this.

Any suggestions on what might be causing the difference on the resolution and how I can address it?


问:
ClassHelper expand existing function to be virtual
I am using Delphi 10.4 (untested for D11).

I am trying to extend a function in an existing class with a ClassHelper so that the function becomes a virtual function.
The compilation works partially.

```<code>  TMetaTable = class
  public
    function Clone: TMetaTable;
  end;

  TMetaTableHelper = Class helper for TMetaTable
  public
    function Clone: TMetaTable; virtual;
  End;

identifierName = class|record helper [(ancestor list)] for TypeIdentifierName
// [(ancestor list)] can I do some magic here like add additional support for
//TVirtualInterface or IInterface?
 memberList
end;
</code>```

The error message is:

```<code>[dcc32 Error] MbfXData.MetaTable.pas(73): E2291 Missing implementation of interface method IInterface.QueryInterface
[dcc32 Error] MbfXData.MetaTable.pas(73): E2291 Missing implementation of interface method IInterface._AddRef
[dcc32 Error] MbfXData.MetaTable.pas(73): E2291 Missing implementation of interface method IInterface._Release
</code>```

Does anyone know how to create a virtual method in a ClassHelper? Do I need to include a definition of TVirtualInterface in the ClassHelper?

I can't find any documentation on how to use multiple ancestors. And I found some (perhaps older Delphi versions) answers stating its impossible. But to me it looks just like I am missing to add the Virtual Managing Elements.

If it's impossible: can you guide me to a followup read so I can understand how to look at Delphi's build in RTTI funtions to determine it's impossible.

Body:
I am using Delphi 10.4 (untested for D11).

I am trying to extend a function in an existing class with a ClassHelper so that the function becomes a virtual function.
The compilation works partially.

  TMetaTable = class
  public
    function Clone: TMetaTable;
  end;

  TMetaTableHelper = Class helper for TMetaTable
  public
    function Clone: TMetaTable; virtual;
  End;

identifierName = class|record helper [(ancestor list)] for TypeIdentifierName
// [(ancestor list)] can I do some magic here like add additional support for
//TVirtualInterface or IInterface?
 memberList
end;

The error message is:

[dcc32 Error] MbfXData.MetaTable.pas(73): E2291 Missing implementation of interface method IInterface.QueryInterface
[dcc32 Error] MbfXData.MetaTable.pas(73): E2291 Missing implementation of interface method IInterface._AddRef
[dcc32 Error] MbfXData.MetaTable.pas(73): E2291 Missing implementation of interface method IInterface._Release

Does anyone know how to create a virtual method in a ClassHelper? Do I need to include a definition of TVirtualInterface in the ClassHelper?

I can't find any documentation on how to use multiple ancestors. And I found some (perhaps older Delphi versions) answers stating its impossible. But to me it looks just like I am missing to add the Virtual Managing Elements.

If it's impossible: can you guide me to a followup read so I can understand how to look at Delphi's build in RTTI funtions to determine it's impossible.


问:
No module named 'conda' when trying to install graphviz
I am using spyder 5.4.0 with python 3.9.14 64-bit and miniconda 3.

While executing

```<code>conda create -n spyder-env -y
conda activate spyder-env
conda install spyder-kernels python-graphviz -y
</code>```

in the terminal I get the following error

```<code>Sohams-MacBook-Pro:miniconda3 amaterasu$ conda create -n spyder-env -y
Traceback (most recent call last):
  File "/Users/amaterasu/opt/miniconda3/bin/conda", line 12, in <module>
    from conda.cli import main
ModuleNotFoundError: No module named 'conda'
Sohams-MacBook-Pro:miniconda3 amaterasu$ conda activate spyder-env
Traceback (most recent call last):
  File "/Users/amaterasu/opt/miniconda3/bin/conda", line 12, in <module>
    from conda.cli import main
ModuleNotFoundError: No module named 'conda'
Sohams-MacBook-Pro:miniconda3 amaterasu$ conda install spyder-kernels python-graphviz -y
</code>```

Body:
I am using spyder 5.4.0 with python 3.9.14 64-bit and miniconda 3.

While executing

conda create -n spyder-env -y
conda activate spyder-env
conda install spyder-kernels python-graphviz -y

in the terminal I get the following error

Sohams-MacBook-Pro:miniconda3 amaterasu$ conda create -n spyder-env -y
Traceback (most recent call last):
  File "/Users/amaterasu/opt/miniconda3/bin/conda", line 12, in <module>
    from conda.cli import main
ModuleNotFoundError: No module named 'conda'
Sohams-MacBook-Pro:miniconda3 amaterasu$ conda activate spyder-env
Traceback (most recent call last):
  File "/Users/amaterasu/opt/miniconda3/bin/conda", line 12, in <module>
    from conda.cli import main
ModuleNotFoundError: No module named 'conda'
Sohams-MacBook-Pro:miniconda3 amaterasu$ conda install spyder-kernels python-graphviz -y


问:
ChartJS set axis scale to a cubic root
I'm trying to figure out how to set the x-axis scale in a ChartJS to a cubed root (or similar like a square root). Here is an example photo using a square root but the idea is the same for cubed root scale:

I found this doc for making a custom scale in ChartJS but I don't see how to define the relationship anywhere in the documentation.

Coming from a python/matplotlib background, it would be done like this:

```<code>def power(x, n=3) -> np.array:
    return np.power(x, n)

def inv_power(x, n=3) -> np.array:
    return np.power(x, 1 / n)

ax.set_xscale("function", functions=(inv_power, power))

</code>```

Title: ChartJS set axis scale to a cubic root

Body:
I'm trying to figure out how to set the x-axis scale in a ChartJS to a cubed root (or similar like a square root). Here is an example photo using a square root but the idea is the same for cubed root scale:

I found this doc for making a custom scale in ChartJS but I don't see how to define the relationship anywhere in the documentation.

Coming from a python/matplotlib background, it would be done like this:

def power(x, n=3) -> np.array:
    return np.power(x, n)

def inv_power(x, n=3) -> np.array:
    return np.power(x, 1 / n)

ax.set_xscale("function", functions=(inv_power, power))


问:
Run ruby-on-rails from expect
I need to run a list of operations inside rails for each line of an input file.
So I thought to use expect but I'm stuck, cannot even see what rails does.
I tried just to start it and stop it and with ps I can see rails is running but there's no reaction. I see the output only when I kill rails' process

This is what I am doing:

```<code>#!/usr/bin/expect -f

set output [exec bundle exec rails c]
puts $output

spawn exit
exit
</code>```

Any help would be appreciated

Title: Run ruby-on-rails from expect

Body:
I need to run a list of operations inside rails for each line of an input file.
So I thought to use expect but I'm stuck, cannot even see what rails does.
I tried just to start it and stop it and with ps I can see rails is running but there's no reaction. I see the output only when I kill rails' process

This is what I am doing:

#!/usr/bin/expect -f

set output [exec bundle exec rails c]
puts $output

spawn exit
exit

Any help would be appreciated


问:
RISC-V toolchain: lds file may make some irrelevant instructions
I want to use risc-v toolchain to compile a simple c code to test my processor. And I refer to PicoRV32's firmware file for my own test.lds :

```<code>SECTIONS {
    .memory : {
        . = 0x000000;
        *(.init);
        *(.text);
        *(*);
        . = ALIGN(4);
        end = .;
    }
}
</code>```

and then test.S

```<code>.section .init
.global main

lui sp, %hi(16*1024)
addi sp, sp, %lo(16*1024)

jal ra, main

ebreak
</code>```

and this is my test c prog test.c

```<code>void main()
{
  volatile int x = 1;
  volatile int y;
  volatile int z = 1;
  volatile int a = 1;
  volatile int b = 1;
  volatile int c = 1;
  volatile int d = 1;
  volatile int e = 1;
  volatile int f = 1;
  asm volatile(
    "addi a1, zero, 250;"
    "addi a2, zero, 6  ;"
    "sw   a1,     0(sp);"
    "lw   a3,     0(sp);"
    "mul  a4,   a2,  a3;"
    "add  a5,   a3,  a2;"
    "ebreak            ;");
}
</code>```

finally the parameter I use in my compile process:

```<code>riscv32-unknown-elf-gcc -mno-relax -march=rv32im -Os -ffreestanding -nostdlib \
        -o test.elf test.S test.c -static \
        -Wl,-T,test.lds,-Map,test.map,--strip-debug -lgcc
    riscv32-unknown-elf-objcopy -j .text -O binary test.elf test.bin
    riscv32-unknown-elf-objdump -d -M no-aliases test.elf > result.txt
</code>```

then the result.txt is:

```<code>
test.elf:     file format elf32-littleriscv

Disassembly of section .memory:

00000000 <main-0x30>:
   0:   00004137            lui sp,0x4
   4:   00010113            addi    sp,sp,0 # 4000 <end+0x3f50>
   8:   028000ef            jal ra,30 <main>
   c:   00100073            ebreak
  10:   1e41                    c.addi  t3,-16
  12:   0000                    c.unimp
  14:   7200                    c.flw   fs0,32(a2)
  16:   7369                    c.lui   t1,0xffffa
  18:   01007663            bgeu    zero,a6,24 <main-0xc>
  1c:   0014                    .2byte  0x14
  1e:   0000                    c.unimp
  20:   7205                    c.lui   tp,0xfffe1
  22:   3376                    c.fldsp ft6,376(sp)
  24:   6932                    c.flwsp fs2,12(sp)
  26:   7032                    c.flwsp ft0,44(sp)
  28:   5f30                    c.lw    a2,120(a4)
  2a:   326d                    c.jal   fffff9d4 <end+0xfffff924>
  2c:   3070                    c.fld   fa2,224(s0)
    ...

00000030 <main>:
  30:   fe010113            addi    sp,sp,-32
  34:   00100793            addi    a5,zero,1
  38:   00f12023            sw  a5,0(sp)
  3c:   00f12223            sw  a5,4(sp)
  40:   00f12423            sw  a5,8(sp)
  44:   00f12623            sw  a5,12(sp)
  48:   00f12823            sw  a5,16(sp)
  4c:   00f12a23            sw  a5,20(sp)
  50:   00f12c23            sw  a5,24(sp)
  54:   00f12e23            sw  a5,28(sp)
  58:   0fa00593            addi    a1,zero,250
  5c:   00600613            addi    a2,zero,6
  60:   00b12023            sw  a1,0(sp)
  64:   00012683            lw  a3,0(sp)
  68:   02d60733            mul a4,a2,a3
  6c:   00c687b3            add a5,a3,a2
  70:   00100073            ebreak
  74:   02010113            addi    sp,sp,32
  78:   00008067            jalr    zero,0(ra)
  7c:   3a434347            fmsub.d ft6,ft6,ft4,ft7,rmm
  80:   2820                    c.fld   fs0,80(s0)
  82:   31202967            .4byte  0x31202967
  86:   2e32                    c.fldsp ft8,264(sp)
  88:   2e32                    c.fldsp ft8,264(sp)
  8a:   0030                    c.addi4spn  a2,sp,8
  8c:   2041                    c.jal   10c <end+0x5c>
  8e:   0000                    c.unimp
  90:   7200                    c.flw   fs0,32(a2)
  92:   7369                    c.lui   t1,0xffffa
  94:   01007663            bgeu    zero,a6,a0 <main+0x70>
  98:   0016                    c.slli  zero,0x5
  9a:   0000                    c.unimp
  9c:   1004                    c.addi4spn  s1,sp,32
  9e:   7205                    c.lui   tp,0xfffe1
  a0:   3376                    c.fldsp ft6,376(sp)
  a2:   6932                    c.flwsp fs2,12(sp)
  a4:   7032                    c.flwsp ft0,44(sp)
  a6:   5f30                    c.lw    a2,120(a4)
  a8:   326d                    c.jal   fffffa52 <end+0xfffff9a2>
  aa:   3070                    c.fld   fa2,224(s0)
  ac:   0000                    c.unimp
    ...
</code>```

Note that I've named the -march=rv32im, but I still compile out some compressed instructions. I found these compressed instructions are useless in the final output test.elf which the prog will never jump onto those instruction, and if I delete the segment *(*) in lds file they are all disappear, left only my own program. But I can't figure out why these segments in lds file *(*) will make some irrelevant instructions? I found *(.comment) will make .4byte or .2byte words, and *(.riscv.attributes) will make the rest of the compressed instruction which is only for gcc ( llvm will display <unknown>
To summerize upon questions:

Is it necessary to use .lds file just to test the functionality of a processor?

Why some lds segments will cause those strange and seems useless instructions?

Is it for OS runtime or something?

Body:
I want to use risc-v toolchain to compile a simple c code to test my processor. And I refer to PicoRV32's firmware file for my own test.lds :

SECTIONS {
    .memory : {
        . = 0x000000;
        *(.init);
        *(.text);
        *(*);
        . = ALIGN(4);
        end = .;
    }
}

and then test.S

.section .init
.global main

lui sp, %hi(16*1024)
addi sp, sp, %lo(16*1024)

jal ra, main

ebreak

and this is my test c prog test.c

void main()
{
  volatile int x = 1;
  volatile int y;
  volatile int z = 1;
  volatile int a = 1;
  volatile int b = 1;
  volatile int c = 1;
  volatile int d = 1;
  volatile int e = 1;
  volatile int f = 1;
  asm volatile(
    "addi a1, zero, 250;"
    "addi a2, zero, 6  ;"
    "sw   a1,     0(sp);"
    "lw   a3,     0(sp);"
    "mul  a4,   a2,  a3;"
    "add  a5,   a3,  a2;"
    "ebreak            ;");
}

finally the parameter I use in my compile process:

riscv32-unknown-elf-gcc -mno-relax -march=rv32im -Os -ffreestanding -nostdlib \
        -o test.elf test.S test.c -static \
        -Wl,-T,test.lds,-Map,test.map,--strip-debug -lgcc
    riscv32-unknown-elf-objcopy -j .text -O binary test.elf test.bin
    riscv32-unknown-elf-objdump -d -M no-aliases test.elf > result.txt

then the result.txt is:

test.elf:     file format elf32-littleriscv

Disassembly of section .memory:

00000000 :
   0:   00004137            lui sp,0x4
   4:   00010113            addi    sp,sp,0 # 4000 <end+0x3f50>
   8:   028000ef            jal ra,30
   c:   00100073            ebreak
  10:   1e41                    c.addi  t3,-16
  12:   0000                    c.unimp
  14:   7200                    c.flw   fs0,32(a2)
  16:   7369                    c.lui   t1,0xffffa
  18:   01007663            bgeu    zero,a6,24
  1c:   0014                    .2byte  0x14
  1e:   0000                    c.unimp
  20:   7205                    c.lui   tp,0xfffe1
  22:   3376                    c.fldsp ft6,376(sp)
  24:   6932                    c.flwsp fs2,12(sp)
  26:   7032                    c.flwsp ft0,44(sp)
  28:   5f30                    c.lw    a2,120(a4)
  2a:   326d                    c.jal   fffff9d4 <end+0xfffff924>
  2c:   3070                    c.fld   fa2,224(s0)
    ...

00000030 :
  30:   fe010113            addi    sp,sp,-32
  34:   00100793            addi    a5,zero,1
  38:   00f12023            sw  a5,0(sp)
  3c:   00f12223            sw  a5,4(sp)
  40:   00f12423            sw  a5,8(sp)
  44:   00f12623            sw  a5,12(sp)
  48:   00f12823            sw  a5,16(sp)
  4c:   00f12a23            sw  a5,20(sp)
  50:   00f12c23            sw  a5,24(sp)
  54:   00f12e23            sw  a5,28(sp)
  58:   0fa00593            addi    a1,zero,250
  5c:   00600613            addi    a2,zero,6
  60:   00b12023            sw  a1,0(sp)
  64:   00012683            lw  a3,0(sp)
  68:   02d60733            mul a4,a2,a3
  6c:   00c687b3            add a5,a3,a2
  70:   00100073            ebreak
  74:   02010113            addi    sp,sp,32
  78:   00008067            jalr    zero,0(ra)
  7c:   3a434347            fmsub.d ft6,ft6,ft4,ft7,rmm
  80:   2820                    c.fld   fs0,80(s0)
  82:   31202967            .4byte  0x31202967
  86:   2e32                    c.fldsp ft8,264(sp)
  88:   2e32                    c.fldsp ft8,264(sp)
  8a:   0030                    c.addi4spn  a2,sp,8
  8c:   2041                    c.jal   10c <end+0x5c>
  8e:   0000                    c.unimp
  90:   7200                    c.flw   fs0,32(a2)
  92:   7369                    c.lui   t1,0xffffa
  94:   01007663            bgeu    zero,a6,a0
  98:   0016                    c.slli  zero,0x5
  9a:   0000                    c.unimp
  9c:   1004                    c.addi4spn  s1,sp,32
  9e:   7205                    c.lui   tp,0xfffe1
  a0:   3376                    c.fldsp ft6,376(sp)
  a2:   6932                    c.flwsp fs2,12(sp)
  a4:   7032                    c.flwsp ft0,44(sp)
  a6:   5f30                    c.lw    a2,120(a4)
  a8:   326d                    c.jal   fffffa52 <end+0xfffff9a2>
  aa:   3070                    c.fld   fa2,224(s0)
  ac:   0000                    c.unimp
    ...

Note that I've named the -march=rv32im, but I still compile out some compressed instructions. I found these compressed instructions are useless in the final output test.elf which the prog will never jump onto those instruction, and if I delete the segment *(*) in lds file they are all disappear, left only my own program. But I can't figure out why these segments in lds file *(*) will make some irrelevant instructions? I found *(.comment) will make .4byte or .2byte words, and *(.riscv.attributes) will make the rest of the compressed instruction which is only for gcc ( llvm will display <unknown>
To summerize upon questions:

Is it necessary to use .lds file just to test the functionality of a processor?

Why some lds segments will cause those strange and seems useless instructions?

Is it for OS runtime or something?


问:
Android Studio Gray Screen when testing app
I'm trying to build an Android TV app, but when I go to test it, I just get a gray screen. The app only has a main activity with a single image for now, but it doesn't even show when I go to test the app on a virtual Android Device.

What do I do?

Details of the version and OS I'm using:

```<code>Android Studio Dolphin | 2021.3.1 Patch 1
Build #AI-213.7172.25.2113.9123335, built on September 30, 2022
Runtime version: 11.0.13+0-b1751.21-8125866 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.
Linux 5.15.0-56-generic
GC: G1 Young Generation, G1 Old Generation
Memory: 2048M
Cores: 12
Registry:
    external.system.auto.import.disabled=true
    ide.text.editor.with.preview.show.floating.toolbar=false

Current Desktop: XFCE
</code>```

If it helps, I'm also trying to use the Leanback library. Here's the code for the main activity:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <!-- fragment
        android:id="@+id/main_fragment"
        class="com.example.example.MainFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" / -->

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:contentDescription="@string/todo"
        android:src="@drawable/test"
        tools:ignore="ImageContrastCheck"
        tools:src="@drawable/test" />

</LinearLayout>
</code>```

There doesn't seem to be much I could try, I'm fairly new to Android Studio. I've looked everywhere for a solution, but can't find the same problem I'm having.

Body:
I'm trying to build an Android TV app, but when I go to test it, I just get a gray screen. The app only has a main activity with a single image for now, but it doesn't even show when I go to test the app on a virtual Android Device.

What do I do?

Details of the version and OS I'm using:

Android Studio Dolphin | 2021.3.1 Patch 1
Build #AI-213.7172.25.2113.9123335, built on September 30, 2022
Runtime version: 11.0.13+0-b1751.21-8125866 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.
Linux 5.15.0-56-generic
GC: G1 Young Generation, G1 Old Generation
Memory: 2048M
Cores: 12
Registry:
    external.system.auto.import.disabled=true
    ide.text.editor.with.preview.show.floating.toolbar=false

Current Desktop: XFCE

If it helps, I'm also trying to use the Leanback library. Here's the code for the main activity:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:contentDescription="@string/todo"
        android:src="@drawable/test"
        tools:ignore="ImageContrastCheck"
        tools:src="@drawable/test" />

</LinearLayout>

There doesn't seem to be much I could try, I'm fairly new to Android Studio. I've looked everywhere for a solution, but can't find the same problem I'm having.


问:
Using pandas to convert easting and northing to lat and lon given multiple epsg codes
I've gathered information from many separate excel files into a dataframe that contains East and North data given in 10 different coordinate systems (EPSG codes). I can use pyproj to convert one given data point with (epgs_code, east, north) into (lat, lon) for plotting in plotly express, for example.

To add the latitud and longitud data to my dataframe I created a function convert_to_lonlat(epsg, east, north) and I am attempting to apply it to the dataframe to get the new columns, as shown in the code below.

I created a function that takes in the epsg code, east and north, and returns lon and lat values:

```<code>def convert_to_lonlat(epsg, east, north):
    import pyproj
    # Define the projection
    epsg_proj = pyproj.CRS.from_epsg(int(epsg))

    # Create a transformation function using the projection
    transform = pyproj.Transformer.from_crs(epsg_proj, 'epsg:4326', always_xy=True)

    # Transform the coordinates
    lon, lat = transform.transform(north, east)

    return lon, lat
</code>```

A simple test dataframe would be:

```<code>geo = pd.DataFrame({'East':[1e6], 'North':[1e6], 'EPSG':[3116]})
</code>```

I'm trying to use the .apply() method to create two columns in a dataframe that contains data in many epsg codes, as:

```<code>geo[['lat','lon']] = geo.apply(
    lambda row: convert_to_lonlat(
        row['EPSG'],
        row['East'],
        row['North'],
        axis=1,
        result_type='expand',
        )
)
</code>```

which incidentally was suggested by ChatGPT.

However, when I run the code on my dfataframe I get a KeyError:'EPSG' message. Any suggestions as of how this could be fixed? Thank you in advance!

For reference, the full answer from ChatGPT to the query: "use .apply() in pandas using a function that takes 3 arguments and returns two values to create two new columns" was:

```<code>import pandas as pd

# Define the function that takes three arguments and returns two values
def my_function(arg1, arg2, arg3):
    result1 = arg1 + arg2 + arg3
    result2 = arg1 * arg2 * arg3
    return result1, result2

# Create a sample dataframe
df = pd.DataFrame({'arg1': [1, 2, 3, 4, 5],
                   'arg2': [10, 20, 30, 40, 50],
                   'arg3': [100, 200, 300, 400, 500]})

# Use the apply() function to create two new columns using the my_function
df[['result1', 'result2']] = df.apply(lambda row: my_function(row['arg1'], row['arg2'], row['arg3']), axis=1, result_type='expand')

# Print the resulting dataframe
print(df)

</code>```

which works, printing out:

```<code>   arg1  arg2  arg3  result1  result2
0     1    10   100      111     1000
1     2    20   200      222     8000
2     3    30   300      333    27000
3     4    40   400      444    64000
4     5    50   500      555   125000

</code>```

Body:
I've gathered information from many separate excel files into a dataframe that contains East and North data given in 10 different coordinate systems (EPSG codes). I can use pyproj to convert one given data point with (epgs_code, east, north) into (lat, lon) for plotting in plotly express, for example.

To add the latitud and longitud data to my dataframe I created a function convert_to_lonlat(epsg, east, north) and I am attempting to apply it to the dataframe to get the new columns, as shown in the code below.

I created a function that takes in the epsg code, east and north, and returns lon and lat values:

def convert_to_lonlat(epsg, east, north):
    import pyproj
    # Define the projection
    epsg_proj = pyproj.CRS.from_epsg(int(epsg))

    # Create a transformation function using the projection
    transform = pyproj.Transformer.from_crs(epsg_proj, 'epsg:4326', always_xy=True)

    # Transform the coordinates
    lon, lat = transform.transform(north, east)

    return lon, lat

A simple test dataframe would be:

geo = pd.DataFrame({'East':[1e6], 'North':[1e6], 'EPSG':[3116]})

I'm trying to use the .apply() method to create two columns in a dataframe that contains data in many epsg codes, as:

geo[['lat','lon']] = geo.apply(
    lambda row: convert_to_lonlat(
        row['EPSG'],
        row['East'],
        row['North'],
        axis=1,
        result_type='expand',
        )
)

which incidentally was suggested by ChatGPT.

However, when I run the code on my dfataframe I get a KeyError:'EPSG' message. Any suggestions as of how this could be fixed? Thank you in advance!

For reference, the full answer from ChatGPT to the query: "use .apply() in pandas using a function that takes 3 arguments and returns two values to create two new columns" was:

import pandas as pd

# Define the function that takes three arguments and returns two values
def my_function(arg1, arg2, arg3):
    result1 = arg1 + arg2 + arg3
    result2 = arg1 * arg2 * arg3
    return result1, result2

# Create a sample dataframe
df = pd.DataFrame({'arg1': [1, 2, 3, 4, 5],
                   'arg2': [10, 20, 30, 40, 50],
                   'arg3': [100, 200, 300, 400, 500]})

# Use the apply() function to create two new columns using the my_function
df[['result1', 'result2']] = df.apply(lambda row: my_function(row['arg1'], row['arg2'], row['arg3']), axis=1, result_type='expand')

# Print the resulting dataframe
print(df)

which works, printing out:

   arg1  arg2  arg3  result1  result2
0     1    10   100      111     1000
1     2    20   200      222     8000
2     3    30   300      333    27000
3     4    40   400      444    64000
4     5    50   500      555   125000


问:
Using c code in the backend with electron JS
Hello I have a code in C that continuously retrieves data via UDP protocol with a specific port. I would like to insert this code in the backend with electron JS to be able to display its data on the already created GUI. I understand that this may be possible but I don't know exactly how to do it?

Regards,


问:
Letter d treated as hex sign
I try to put polish word 'pieniędzy' on site I work on. It's placed in pseudo element :after in property content. Text is displayed incorrectly.

I tried to do it in various ways but it doesn't work as expected.

content in css file
result on page
content in browser
comment

pieniędzy

pieni\119 dzy
space between letters 'ę' and 'd'

pieni\EBdzy

pieni\EBDzy
strange scharacter istead of 'ę' and 'd'

pieni\EB\64z

pieni\EB dzy
ë instead of ę and space after this letter

\EB - code of character 'ę'

\64 - code of character 'd'

It looks like character 'd' is treated as part of hex code. Is is possible to escape this character?

Title: Letter d treated as hex sign


问:
cronjob failing to send email in production server, works on localhost
I'm working on a project in which a reminder email has to be sent whenever the scheduled time is met.

For example, if the reminder date and time is set to Dec17, 6am. Then the email has to be sent automatically on Dec17, 6am.

This works fine in my local host without any issue, but when I deploy it in the production environment the automatic email is not sent.

my code snippet:

```<code>def my_scheduled_job():
    try:
        if settings.RUN_SCHEDULER:
            utc = pytz.utc
            ist = pytz.timezone('Asia/Calcutta')
            json_data = {}
            tickets = Ticket.objects.filter(is_active = True).exclude(state_history__state__item = 'Completed')
            for rem in tickets:
                for dt in rem.reminder.all():
                    ind_utc = datetime.today() + timedelta(hours=5, minutes=30)
                    remainder_date  = dt.date_time
                    d1 = datetime.strptime(remainder_date.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')
                    d2 = datetime.strptime(ind_utc.strftime('%Y-%m-%d %H:%M'), '%Y-%m-%d %H:%M')
                    if d1 == d2:
                        to_addr, obj_cnt = [], rem.reminder.count()
                        filt_cnt = rem.reminder.filter(id__gte = dt.id).count()
                        if obj_cnt == filt_cnt:
                            if rem.users.all():
                                    for user in rem.users.all():
                                        user_name = User.objects.values_list('username',flat=True).get(id=user.id)
                                        to_addr.append(user_name)
                            else:
                                for group in rem.groups.all():
                                    users = User.objects.filter(groups__id=group.id)
                                    for user in users:
                                        to_addr.append(user.username)
                            to_addr = list(set(to_addr))
                            json_data['tickets'] = rem
                            # json_data['urlObject'] = base.HOSTNAME
                            html = render_to_string('email/cronjob.html', json_data)
                            mail = mail_function('sending mail from FMS', to_addr, html)
                            cron_logger.info("-------Scheduled mail sent to assigned user-----")
                        elif (obj_cnt-1) == filt_cnt:
                            if rem.users.all():
                                for user in rem.users.all():
                                    user_name = User.objects.values_list('username',flat=True).get(id=user.id)
                                    to_addr.append(user_name)
                            else:
                                for group in rem.groups.all():
                                    users = User.objects.filter(groups__id=group.id)
                                    for user in users:
                                        to_addr.append(user.username)
                            for user in rem.activity_loop.all():
                                user_name = User.objects.values_list('username',flat=True).get(id=user.id)
                            to_addr.append(user_name)
                            to_addr = list(set(to_addr))
                            json_data['tickets'] = rem
                            # json_data['urlObject'] = base.HOSTNAME
                            html = render_to_string('email/activity_reminder1.html', json_data)
                            mail = mail_function('sending mail from FMS', to_addr, html)
                            cron_logger.info("-------Scheduled mail sent to assigned user and activity loop-----")
                        else:
                            if rem.users.all():
                                for user in rem.users.all():
                                    user_name = User.objects.values_list('username',flat=True).get(id=user.id)
                                    to_addr.append(user_name)
                            else:
                                for group in rem.groups.all():
                                    users = User.objects.filter(groups__id=group.id)
                                    for user in users:
                                        to_addr.append(user.username)
                            for user in rem.activity_loop.all():
                                user_name = User.objects.values_list('username',flat=True).get(id=user.id)
                                to_addr.append(user_name)
                            for user in rem.approver.all():
                                user_name = User.objects.values_list('username',flat=True).get(id=user.id)
                                to_addr.append(user_name)
User.objects.values_list('username',flat=True).get(id=user.id)
                            cfo_group = Group.objects.get(name='CFO')
                            cfo_addr = [ cfo.username for cfo in User.objects.filter(is_active = True,groups__id=cfo_group.id) ]
                            to_addr.extend(cfo_addr)
                            to_addr = list(set(to_addr))
                            json_data['tickets'] = rem
                            # json_data['urlObject'] = base.HOSTNAME
                            json_data['test'] = 'ELSE'
                            html = render_to_string('email/activity_reminder2.html', json_data)
                            mail = mail_function('sending mail from FMS', to_addr, html)
                            cron_logger.info("-------Scheduled mail sent to assigned user,approvers,activity loop and CFO-----")
            else:
                cron_logger.info("-------RUN_SCHEDULER is NOT ACTIVE-----")
    except Exception as e:
        cron_logger.info("-------RUN_SCHEDULER is NOT ACTIVE-----")
</code>```

settings.py has the following lines:

```<code>RUN_SCHEDULER = True
CRONJOBS = [
    ('* * * * *', 'tickets.cron.my_scheduled_job'),
    ('* * * * *', 'tickets.cron.due_date_remainder')
]
</code>```

In the deployment environment, the Output of crontab show command results of

```<code>fab2f6df81d6c9c6e517c2aaaaa353ef -> ('* * * * *', 'tickets.cron.my_scheduled_job')
15b21bd07923d0bde77a304dfb962603 -> ('* * * * *', 'tickets.cron.due_date_remainder')
</code>```

Body:
I'm working on a project in which a reminder email has to be sent whenever the scheduled time is met.

For example, if the reminder date and time is set to Dec17, 6am. Then the email has to be sent automatically on Dec17, 6am.

This works fine in my local host without any issue, but when I deploy it in the production environment the automatic email is not sent.

my code snippet:

def my_scheduled_job():
    try:
        if settings.RUN_SCHEDULER:
            utc = pytz.utc
            ist = pytz.timezone('Asia/Calcutta')
            json_data = {}
            tickets = Ticket.objects.filter(is_active = True).exclude(state_history__state__item = 'Completed')
            for rem in tickets:
                for dt in rem.reminder.all():
                    ind_utc = datetime.today() + timedelta(hours=5, minutes=30)
                    remainder_date  = dt.date_time
                    d1 = datetime.strptime(remainder_date.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')
                    d2 = datetime.strptime(ind_utc.strftime('%Y-%m-%d %H:%M'), '%Y-%m-%d %H:%M')
                    if d1 == d2:
                        to_addr, obj_cnt = [], rem.reminder.count()
                        filt_cnt = rem.reminder.filter(id__gte = dt.id).count()
                        if obj_cnt == filt_cnt:
                            if rem.users.all():
                                    for user in rem.users.all():
                                        user_name = User.objects.values_list('username',flat=True).get(id=user.id)
                                        to_addr.append(user_name)
                            else:
                                for group in rem.groups.all():
                                    users = User.objects.filter(groups__id=group.id)
                                    for user in users:
                                        to_addr.append(user.username)
                            to_addr = list(set(to_addr))
                            json_data['tickets'] = rem
                            # json_data['urlObject'] = base.HOSTNAME
                            html = render_to_string('email/cronjob.html', json_data)
                            mail = mail_function('sending mail from FMS', to_addr, html)
                            cron_logger.info("-------Scheduled mail sent to assigned user-----")
                        elif (obj_cnt-1) == filt_cnt:
                            if rem.users.all():
                                for user in rem.users.all():
                                    user_name = User.objects.values_list('username',flat=True).get(id=user.id)
                                    to_addr.append(user_name)
                            else:
                                for group in rem.groups.all():
                                    users = User.objects.filter(groups__id=group.id)
                                    for user in users:
                                        to_addr.append(user.username)
                            for user in rem.activity_loop.all():
                                user_name = User.objects.values_list('username',flat=True).get(id=user.id)
                            to_addr.append(user_name)
                            to_addr = list(set(to_addr))
                            json_data['tickets'] = rem
                            # json_data['urlObject'] = base.HOSTNAME
                            html = render_to_string('email/activity_reminder1.html', json_data)
                            mail = mail_function('sending mail from FMS', to_addr, html)
                            cron_logger.info("-------Scheduled mail sent to assigned user and activity loop-----")
                        else:
                            if rem.users.all():
                                for user in rem.users.all():
                                    user_name = User.objects.values_list('username',flat=True).get(id=user.id)
                                    to_addr.append(user_name)
                            else:
                                for group in rem.groups.all():
                                    users = User.objects.filter(groups__id=group.id)
                                    for user in users:
                                        to_addr.append(user.username)
                            for user in rem.activity_loop.all():
                                user_name = User.objects.values_list('username',flat=True).get(id=user.id)
                                to_addr.append(user_name)
                            for user in rem.approver.all():
                                user_name = User.objects.values_list('username',flat=True).get(id=user.id)
                                to_addr.append(user_name)
User.objects.values_list('username',flat=True).get(id=user.id)
                            cfo_group = Group.objects.get(name='CFO')
                            cfo_addr = [ cfo.username for cfo in User.objects.filter(is_active = True,groups__id=cfo_group.id) ]
                            to_addr.extend(cfo_addr)
                            to_addr = list(set(to_addr))
                            json_data['tickets'] = rem
                            # json_data['urlObject'] = base.HOSTNAME
                            json_data['test'] = 'ELSE'
                            html = render_to_string('email/activity_reminder2.html', json_data)
                            mail = mail_function('sending mail from FMS', to_addr, html)
                            cron_logger.info("-------Scheduled mail sent to assigned user,approvers,activity loop and CFO-----")
            else:
                cron_logger.info("-------RUN_SCHEDULER is NOT ACTIVE-----")
    except Exception as e:
        cron_logger.info("-------RUN_SCHEDULER is NOT ACTIVE-----")

settings.py has the following lines:

RUN_SCHEDULER = True
CRONJOBS = [
    ('* * * * *', 'tickets.cron.my_scheduled_job'),
    ('* * * * *', 'tickets.cron.due_date_remainder')
]

In the deployment environment, the Output of crontab show command results of

fab2f6df81d6c9c6e517c2aaaaa353ef -> ('* * * * *', 'tickets.cron.my_scheduled_job')
15b21bd07923d0bde77a304dfb962603 -> ('* * * * *', 'tickets.cron.due_date_remainder')


问:
How to use postcss RTL in nuxt 3 except of tailwindcss
i use nuxt 3.0.0 with tailwindcss ^3.2.4

i have element-plus also, now i want use postcss-rtl just for element-plus and no for tailwindd or any other css files.

help please.

nuxt.config.ts:

```<code>import { defineNuxtConfig } from 'nuxt/config'

// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({

    postcss: {
        plugins: {
            tailwindcss: {},
            autoprefixer: {},
        },
    },

    css: [
        '~/assets/css/tailwind.scss',
        '@/assets/css/fonts/font-awesome/fontawesome.css',
        '@/assets/css/fonts/font-awesome/duotone.css'
    ],

    plugins: [
        '@/plugins/element-plus'
    ]

})

</code>```

plugins/element-plus.js:

```<code>import ElementPlus from 'element-plus';

import fa from 'element-plus/dist/locale/fa.mjs';
import 'dayjs/locale/fa';

import 'element-plus/dist/index.css';
import '@/assets/css/element-plus.scss';

export default defineNuxtPlugin((nuxtApp) => {
    nuxtApp.vueApp.use(ElementPlus, {
        locale: fa
    })
});

</code>```

element-plus.scss:

```<code>$colors: (
        'primary': (
                'base': #fe7aac,
        )
);

@forward "element-plus/theme-chalk/src/common/var.scss" with (
// do not use same name, it will override.
$colors: $colors
);

@use "element-plus/theme-chalk/src/index.scss" as *;

</code>```

i want to use rtl postcss just for element-plus

Body:
i use nuxt 3.0.0 with tailwindcss ^3.2.4

i have element-plus also, now i want use postcss-rtl just for element-plus and no for tailwindd or any other css files.

help please.

nuxt.config.ts:

import { defineNuxtConfig } from 'nuxt/config'

// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({

    postcss: {
        plugins: {
            tailwindcss: {},
            autoprefixer: {},
        },
    },

    css: [
        '~/assets/css/tailwind.scss',
        '@/assets/css/fonts/font-awesome/fontawesome.css',
        '@/assets/css/fonts/font-awesome/duotone.css'
    ],

    plugins: [
        '@/plugins/element-plus'
    ]

})

plugins/element-plus.js:

import ElementPlus from 'element-plus';

import fa from 'element-plus/dist/locale/fa.mjs';
import 'dayjs/locale/fa';

import 'element-plus/dist/index.css';
import '@/assets/css/element-plus.scss';

export default defineNuxtPlugin((nuxtApp) => {
    nuxtApp.vueApp.use(ElementPlus, {
        locale: fa
    })
});

element-plus.scss:

$colors: (
        'primary': (
                'base': #fe7aac,
        )
);

@forward "element-plus/theme-chalk/src/common/var.scss" with (
// do not use same name, it will override.
$colors: $colors
);

@use "element-plus/theme-chalk/src/index.scss" as *;

i want to use rtl postcss just for element-plus


问:
How does one access the options for a GoogleCharts chart in the browser console?
I have been looking at the Google Charts documentation and I'm confused at where I am supposed to specify certain options. For example candlestick.fallingColor.stroke.

With other libraries, even huge ones like Babylon.js, I have been able to comb through objects in the console and see where settings live. But, after a long time searching, I can't actually find the chart I have made, and thus the options that are available in the browser console.

I found a section called window.google.visualization.CandlestickChart, which matches the chart type I am using, but this appears to just be something like a prototype, as there are no key value pairs in there, but a bunch of unreadable references: ƒ gvjs_tQ(a){gvjs_iL.call(this,a);this.cc(gvjs_d,gvjs_Ft,gvjs_S)}

Does anyone know how I can get to my chart in the console and start poking through options?

Edit: A random chart can be found HERE if that helps


问:
How to avoid the flicker when Picture in Picture stops if AVPictureInPictureController is initialized with contentSource?
In my project I'm using a customized player instead of AVPlayer, so I have to call init(contentSource: AVPictureInPictureController.ContentSource) to initialize an AVPictureInPictureController instance to enable PiP. Now I call startPictureInPicture() when my app goes to background, and stopPictureInPicture() when it returns to foreground.

However, when I try to stop PiP, the PiP small window will first restore to the original video size, then suddenly disappear for a few milliseconds, and finally become back to normal. Meanwhile, the audio is always working fine.

I find a demo here, which is quite similar to my case. The core logic is:

```<code>// videoProvider is a customized video player, and bufferDisplayLayer is a AVSampleBufferDisplayLayer instance
let bufferDisplayLayer = videoProvider.bufferDisplayLayer
bufferDisplayLayer.frame = videoContainerView.bounds
bufferDisplayLayer.videoGravity = .resizeAspect
// videoContainerView is a UIView instance
videoContainerView.layer.addSublayer(bufferDisplayLayer)

videoProvider.start()

let contentSource = AVPictureInPictureController.ContentSource(sampleBufferDisplayLayer: videoProvider.bufferDisplayLayer, playbackDelegate: self)

pipController = AVPictureInPictureController(contentSource: contentSource)
pipController.delegate = self
</code>```

You can see the flicker in this video.

If I instead use init?(playerLayer: AVPlayerLayer) to initialize AVPictureInPictureController, everything works fine. So I want to know if there's a solution to this issue.

Body:
In my project I'm using a customized player instead of AVPlayer, so I have to call init(contentSource: AVPictureInPictureController.ContentSource) to initialize an AVPictureInPictureController instance to enable PiP. Now I call startPictureInPicture() when my app goes to background, and stopPictureInPicture() when it returns to foreground.

However, when I try to stop PiP, the PiP small window will first restore to the original video size, then suddenly disappear for a few milliseconds, and finally become back to normal. Meanwhile, the audio is always working fine.

I find a demo here, which is quite similar to my case. The core logic is:

// videoProvider is a customized video player, and bufferDisplayLayer is a AVSampleBufferDisplayLayer instance
let bufferDisplayLayer = videoProvider.bufferDisplayLayer
bufferDisplayLayer.frame = videoContainerView.bounds
bufferDisplayLayer.videoGravity = .resizeAspect
// videoContainerView is a UIView instance
videoContainerView.layer.addSublayer(bufferDisplayLayer)

videoProvider.start()

let contentSource = AVPictureInPictureController.ContentSource(sampleBufferDisplayLayer: videoProvider.bufferDisplayLayer, playbackDelegate: self)

pipController = AVPictureInPictureController(contentSource: contentSource)
pipController.delegate = self

You can see the flicker in this video.

If I instead use init?(playerLayer: AVPlayerLayer) to initialize AVPictureInPictureController, everything works fine. So I want to know if there's a solution to this issue.


问:
Automapper recursive HierarchyModel
I want to make a clone of an ObservableCollection (so recursive)

I was doing it with automapper with this simple configuration

```<code>var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<HierarchyNodeModel, HierarchyNodeModel>()
            });
</code>```

and my object:

```<code>MyObj = mapper.Map<ObservableCollection<HierarchyNodeModel>, ObservableCollection<HierarchyNodeModel>>(xx);
</code>```

i upgraded automapper and now it goes on stackoverflow error...

what can i do in alternative to clone my collection?

Title: Automapper recursive HierarchyModel

Body:
I want to make a clone of an ObservableCollection (so recursive)

I was doing it with automapper with this simple configuration

var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<HierarchyNodeModel, HierarchyNodeModel>()
            });

and my object:

MyObj = mapper.Map<ObservableCollection<HierarchyNodeModel>, ObservableCollection<HierarchyNodeModel>>(xx);

i upgraded automapper and now it goes on stackoverflow error...

what can i do in alternative to clone my collection?


问:
Artifacts in the photo when removing noise using pywt
I have a code that denoise image using pywt, but when I put colored image, on denoised image gets artifacts.
Code:

```<code>import pywt
import numpy as np
import matplotlib.pyplot as plt
import cv2

def inputter(img_path, wavelet, coeficient, lvl=None):
    #2.1
    im = cv2.imread(img_path)
    im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
    r,g,b = cv2.split(im)

    plt.figure()
    plt.imshow(im)
    plt.axis('off')
    plt.title('Original')

    w = wavelet #'bior1.3'
    n = lvl
    koef = coeficient/100

    def rgb_transform(image):
        C = pywt.wavedec2(image, wavelet=w, mode='periodization', level=n)
        coeff_array, coeff_slices = pywt.coeffs_to_array(C)
        #2.2
        Csort = np.sort(abs(coeff_array.reshape(-1)))  #sortiranje u rastucem poretku

        for x in [koef]:  # x - koliko se koeficijenata zadrzava

            # t - vrednost na poziciji poslednjek koeficijenta koji se odbacuje
            t = Csort[int(np.floor((1-x)*len(Csort)))]
            # maska sa 0 i 1; 1 - koeficijent je veci od definisanog praga
            m = abs(coeff_array)>t
            coeff_filt = coeff_array*m

            #2.3
            Cfilt = pywt.array_to_coeffs(coeff_filt, coeff_slices, output_format='wavedec2')
            im_r = pywt.waverec2(Cfilt, wavelet=w, mode='periodization')
            return np.uint8(im_r)

    r = rgb_transform(r)
    g = rgb_transform(g)
    b = rgb_transform(b)
    image_merge = cv2.merge([r,g,b])

    plt.figure()
    plt.imshow(image_merge)
    plt.axis('off')
    plt.show()

inputter('test.jpg', 'bior1.3', coeficient=10)
</code>```

What could be the mistake?

I tried to use other wavelets, increase the coefficient and level, nothing fits.

Body:
I have a code that denoise image using pywt, but when I put colored image, on denoised image gets artifacts.
Code:

import pywt
import numpy as np
import matplotlib.pyplot as plt
import cv2

def inputter(img_path, wavelet, coeficient, lvl=None):
    #2.1
    im = cv2.imread(img_path)
    im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
    r,g,b = cv2.split(im)

    plt.figure()
    plt.imshow(im)
    plt.axis('off')
    plt.title('Original')

    w = wavelet #'bior1.3'
    n = lvl
    koef = coeficient/100

    def rgb_transform(image):
        C = pywt.wavedec2(image, wavelet=w, mode='periodization', level=n)
        coeff_array, coeff_slices = pywt.coeffs_to_array(C)
        #2.2
        Csort = np.sort(abs(coeff_array.reshape(-1)))  #sortiranje u rastucem poretku

        for x in [koef]:  # x - koliko se koeficijenata zadrzava

            # t - vrednost na poziciji poslednjek koeficijenta koji se odbacuje
            t = Csort[int(np.floor((1-x)*len(Csort)))]
            # maska sa 0 i 1; 1 - koeficijent je veci od definisanog praga
            m = abs(coeff_array)>t
            coeff_filt = coeff_array*m

            #2.3
            Cfilt = pywt.array_to_coeffs(coeff_filt, coeff_slices, output_format='wavedec2')
            im_r = pywt.waverec2(Cfilt, wavelet=w, mode='periodization')
            return np.uint8(im_r)

    r = rgb_transform(r)
    g = rgb_transform(g)
    b = rgb_transform(b)
    image_merge = cv2.merge([r,g,b])

    plt.figure()
    plt.imshow(image_merge)
    plt.axis('off')
    plt.show()

inputter('test.jpg', 'bior1.3', coeficient=10)

What could be the mistake?

I tried to use other wavelets, increase the coefficient and level, nothing fits.


问:
Configuring Vanilla TS Vite project to keep CSS files separated
I am trying to set up a basic (css) library with vanilla TS and Vite 4.

I want to have a main js and css file at the top level so you can import the whole thing in one go. I also want to have component level imports where you can chose to just import the components js + css. The combined css and JS files are working fine; and the individual component JS file is working fine too.

Currently I'm running into the problem where I can't seem to keep an isolated version of the CSS files next to the JS files after bundling. My build is currently creating :

I've gone over the docs of both Vite and Rollup but I can't seem to figure out how to do the same to my CSS as I'm doing to my JS.

```<code>dist
--components
----button
------button.js
--main.css
--main.js

My preferred output would be:

dist
--components
----button
------button.js
------button.css
--main.css
--main.js

In my `main.ts` I'm importing:
</code>```
```<code>import './style.scss'
import './tokens.scss'
import './components/button/button.scss'
</code>```
```<code>
vite.config.js
</code>```
```<code>import { defineConfig } from 'vite'
import { resolve } from 'path'

export default defineConfig({
  build: {
    cssCodeSplit: false,
      manifest: true,
    rollupOptions: {
      output: {
        assetFileNames: () => 'main[extname]',
      }
    },
    lib: {
      formats: ['es'],
      entry: {
        main: resolve(__dirname, 'src/main.ts'),
        button: resolve(__dirname, 'src/components/button/button.ts')
      },
      name: 'CSSFramework',
      fileName: (_, fileName) => fileName === 'main' ? '[name].js' : 'components/[name]/[name].js',
    },
  },
});
</code>```

Thanks in advance !

Body:
I am trying to set up a basic (css) library with vanilla TS and Vite 4.

I want to have a main js and css file at the top level so you can import the whole thing in one go. I also want to have component level imports where you can chose to just import the components js + css. The combined css and JS files are working fine; and the individual component JS file is working fine too.

Currently I'm running into the problem where I can't seem to keep an isolated version of the CSS files next to the JS files after bundling. My build is currently creating :

I've gone over the docs of both Vite and Rollup but I can't seem to figure out how to do the same to my CSS as I'm doing to my JS.

dist
--components
----button
------button.js
--main.css
--main.js

My preferred output would be:

dist
--components
----button
------button.js
------button.css
--main.css
--main.js

In my `main.ts` I'm importing:

import './style.scss'
import './tokens.scss'
import './components/button/button.scss'

vite.config.js

import { defineConfig } from 'vite'
import { resolve } from 'path'

export default defineConfig({
  build: {
    cssCodeSplit: false,
      manifest: true,
    rollupOptions: {
      output: {
        assetFileNames: () => 'main[extname]',
      }
    },
    lib: {
      formats: ['es'],
      entry: {
        main: resolve(__dirname, 'src/main.ts'),
        button: resolve(__dirname, 'src/components/button/button.ts')
      },
      name: 'CSSFramework',
      fileName: (_, fileName) => fileName === 'main' ? '[name].js' : 'components/[name]/[name].js',
    },
  },
});

Thanks in advance !


问:
Dash_Table in Python: style_data_conditional loop between columns
I want to format some cells of my dash table: backgroundColor of values in column T1 to green if the value in column T1 is equal to the value of column P1 for each row.

It works fine with the following code:

```<code>            {
            'if': {
                'filter_query': '{T1}={P1},
                'column_id': 'T1'
            },
            'backgroundColor': 'green',
            'color': 'white'
</code>```

But I need to format in the same way columns T2, T3, ..., T18 if they are equal to P2, P3, ..., P18. I have tried:

```<code>            {
            'if': {
                'filter_query': "'{T"+str(x)+"}={P"+str(x)+"}'",
                'column_id': "'T"+str(x)+"'"
            },
            'backgroundColor': 'green',
            'color': 'white'
            } for x in range(1, 19)
</code>```

when I run my code, there is no error displayed but the cells are not formatted at all.

Any ideas of what I'm doing wrong? Thanks for any help.

I have tried several ways to concatenate without success.

Body:
I want to format some cells of my dash table: backgroundColor of values in column T1 to green if the value in column T1 is equal to the value of column P1 for each row.

It works fine with the following code:

            {
            'if': {
                'filter_query': '{T1}={P1},
                'column_id': 'T1'
            },
            'backgroundColor': 'green',
            'color': 'white'

But I need to format in the same way columns T2, T3, ..., T18 if they are equal to P2, P3, ..., P18. I have tried:

            {
            'if': {
                'filter_query': "'{T"+str(x)+"}={P"+str(x)+"}'",
                'column_id': "'T"+str(x)+"'"
            },
            'backgroundColor': 'green',
            'color': 'white'
            } for x in range(1, 19)

when I run my code, there is no error displayed but the cells are not formatted at all.

Any ideas of what I'm doing wrong? Thanks for any help.

I have tried several ways to concatenate without success.


问:
List append or insert in jupyter notebook creating duplicate elements
When I try to do a list append in a jupyter notebook it creates a duplicate element.

It doesn't happen when I try on console

Same thing with 'insert' or 'extend'

```<code>test = []
test.append('a')
print(test)
['a', 'a']
</code>```

Screenshot:

Body:
When I try to do a list append in a jupyter notebook it creates a duplicate element.

It doesn't happen when I try on console

Same thing with 'insert' or 'extend'

test = []
test.append('a')
print(test)
['a', 'a']

Screenshot:


问:
Uncaught (in promise) ReferenceError: store_lables is not defined vue3
```<code>this is i want to
const nestedMenuitems = ref([

    {
        label: 'Shipments',
        icon: 'pi pi-fw pi-envelope',
        items: [
            {
                label: 'store1',
                icon: 'pi pi-fw pi-compass'
            },
            {
                label: 'store2',
                icon: 'pi pi-fw pi-compass'
            },

        ]
    },

]);
</code>```
```<code>const nestedMenuitems = ref([

    {
        label: 'Shipments',
        icon: 'pi pi-fw pi-envelope',
        items: [
            {
                label: store_lables,
                icon: 'pi pi-fw pi-compass'
            },

        ]
    },

]);
onMounted(() => {
    ApiService.getStores().then((data) => {
        stores.value = data;
       stores.value.forEach((store_lables) => (store_lables));

    //    console.log( stores.value.forEach((store_lables) => ({
    //     label: store_lables.shop,
    //     icon: 'pi pi-fw pi-compass'
    //    })));

    });

});
</code>```

Here I get Api to data ApiService.getStores() this working fine.pass title values to ?(label: store_lables)
i get a error.

how to pass datas to  items: [    {label: store_lables,icon: 'pi pi-fw pi-compass' }, ]

Body:
this is i want to
const nestedMenuitems = ref([

    {
        label: 'Shipments',
        icon: 'pi pi-fw pi-envelope',
        items: [
            {
                label: 'store1',
                icon: 'pi pi-fw pi-compass'
            },
            {
                label: 'store2',
                icon: 'pi pi-fw pi-compass'
            },

        ]
    },

]);

const nestedMenuitems = ref([

    {
        label: 'Shipments',
        icon: 'pi pi-fw pi-envelope',
        items: [
            {
                label: store_lables,
                icon: 'pi pi-fw pi-compass'
            },

        ]
    },

]);
onMounted(() => {
    ApiService.getStores().then((data) => {
        stores.value = data;
       stores.value.forEach((store_lables) => (store_lables));

    //    console.log( stores.value.forEach((store_lables) => ({
    //     label: store_lables.shop,
    //     icon: 'pi pi-fw pi-compass'
    //    })));

    });

});

Here I get Api to data ApiService.getStores() this working fine.pass title values to ?(label: store_lables)
i get a error.

how to pass datas to  items: [    {label: store_lables,icon: 'pi pi-fw pi-compass' }, ]