问:
Blazebit: java.math.BigDecimal cannot be cast to class java.lang.Long
I am using Blazebit and Deltaspike in a jakarta ee project.
The database is oracle.

```<code>https://github.com/joedayz/curso-java-sbs/tree/main/comparabienangular/concentrador-oracle
</code>```

In it repo, my problem is in the class ConsultaProductoServiceImpl and method "consulta". I receive the data from a frontend web application but when execute the findAll with specification, I got it error:

```<code>[2022-12-18T18:04:13.470-0500] [Payara 5.2021.4] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=117 _ThreadName=http-thread-pool::http-listener-1(2)] [timeMillis: 1671404653470] [levelValue: 900] [[
  StandardWrapperValve[pe.farmaciasperuanas.concentrador.controller.ConcentradorRestApplication]: Servlet.service() for servlet pe.farmaciasperuanas.concentrador.controller.ConcentradorRestApplication threw exception
java.lang.ClassCastException: class java.math.BigDecimal cannot be cast to class java.lang.Long (java.math.BigDecimal and java.lang.Long are in module java.base of loader 'bootstrap')
    at com.blazebit.persistence.impl.PaginatedTypedQueryImpl.getResultList(PaginatedTypedQueryImpl.java:441)
    at com.blazebit.persistence.impl.PaginatedTypedQueryImpl.getResultList(PaginatedTypedQueryImpl.java:218)
    at com.blazebit.persistence.impl.PaginatedTypedQueryImpl.getResultList(PaginatedTypedQueryImpl.java:58)
    at com.blazebit.persistence.deltaspike.data.base.handler.AbstractEntityViewAwareRepositoryHandler.findAll(AbstractEntityViewAwareRepositoryHandler.java:322)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at com.blazebit.persistence.deltaspike.data.impl.builder.EntityViewDelegateQueryBuilder.invoke(EntityViewDelegateQueryBuilder.java:113)
    at com.blazebit.persistence.deltaspike.data.impl.builder.EntityViewDelegateQueryBuilder.execute(EntityViewDelegateQueryBuilder.java:61)
    at com.blazebit.persistence.deltaspike.data.impl.builder.EntityViewQueryBuilder.executeQuery(EntityViewQueryBuilder.java:37)
    at com.blazebit.persistence.deltaspike.data.impl.builder.EntityViewDelegateQueryBuilder$Proxy$_$$_WeldClientProxy.executeQuery(Unknown Source)
    at com.blazebit.persistence.deltaspike.data.impl.handler.TransactionalEntityViewQueryRunner.executeNonTransactional(TransactionalEntityViewQueryRunner.java:58)
    at com.blazebit.persistence.deltaspike.data.impl.handler.TransactionalEntityViewQueryRunner.executeQuery(TransactionalEntityViewQueryRunner.java:54)
    at com.blazebit.persistence.deltaspike.data.impl.handler.TransactionalEntityViewQueryRunner$Proxy$_$$_WeldClientProxy.executeQuery(Unknown Source)
    at com.blazebit.persistence.deltaspike.data.impl.handler.EntityViewAwareQueryHandler.process(EntityViewAwareQueryHandler.java:101)
    at org.apache.deltaspike.data.impl.handler.QueryHandler.invoke(QueryHandler.java:130)
    at com.blazebit.persistence.deltaspike.data.impl.handler.EntityViewAwareQueryHandler$Proxy$_$$_WeldClientProxy.invoke(Unknown Source)
    at org.apache.deltaspike.proxy.spi.invocation.DeltaSpikeProxyInvocationHandler.proceed(DeltaSpikeProxyInvocationHandler.java:97)
    at org.apache.deltaspike.proxy.spi.invocation.DeltaSpikeProxyInvocationHandler.invoke(DeltaSpikeProxyInvocationHandler.java:78)
    at org.apache.deltaspike.proxy.spi.invocation.DeltaSpikeProxyInvocationHandler$Proxy$_$$_WeldClientProxy.invoke(Unknown Source)
    at pe.farmaciasperuanas.concentrador.repository.ConsultaEntidadProductoRepository$$DSPartialBeanProxy.findAll(Unknown Source)
    at pe.farmaciasperuanas.concentrador.service.impl.ConsultaProductoServiceImpl.consulta(ConsultaProductoServiceImpl.java:45)
    at pe.farmaciasperuanas.concentrador.controller.ConsultaEntidadProductoController.consulta(ConsultaEntidadProductoController.java:30)
    at pe.farmaciasperuanas.concentrador.controller.ConsultaEntidadProductoController$Proxy$_$$_WeldClientProxy.consulta(Unknown Source)
</code>```

In the Database the structure of the table is:

```<code>create table DETALLEPRODUCTOFINANCIERO
(
    DETALLEPRODUCTOFINANCIEROID NUMBER(19) generated as identity
        primary key,
    PRODUCTOFINANCIEROID        NUMBER(19)
        constraint FK_DETALLEPRODUCTOFINANCIERO_PRODUCTOFINANCIEROID
            references PRODUCTOFINANCIERO,
    TIPOMONEDAID                NUMBER,
    INGRESOPERMITIDO            NUMBER,
    MONTOMINIMOPRESTAMO         NUMBER,
    MONTOMAXIMOPRESTAMO         NUMBER,
    MONTOMINIMODEPOSITO         NUMBER,
    MONTOMAXIMODEPOSITO         NUMBER
)
/
</code>```

and

```<code>create table PRODUCTOFINANCIERO
(
    PRODUCTOFINANCIEROID NUMBER(19) generated as identity
        primary key,
    TIPOPRODUCTOID       NUMBER(4),
    ENTIDADFINANCIERAID  NUMBER(19)
        constraint FK_PRODUCTOFINANCIERO_ENTIDADFINANCIERAID
            references ENTIDADFINANCIERA,
    NOMBRE               VARCHAR2(100),
    DESCRIPCION          VARCHAR2(200),
    PORCENTAJETEA        NUMBER(10, 2),
    PORCENTAJECOMISION   NUMBER(10, 2),
    PORCENTAJESEGURO     NUMBER(10, 2),
    OBSERVACION          VARCHAR2(500),
    PLAZOMINIMOMES       NUMBER,
    PLAZOMAXIMOMES       NUMBER,
    PLAZOMINIMODIA       NUMBER,
    PLAZOMAXIMODIA       NUMBER,
    TIENEFONDOSEGURO     CHAR,
    USUARIOREGISTRO      VARCHAR2(100),
    FECHAREGISTRO        TIMESTAMP(6),
    USUARIOMODIFICA      VARCHAR2(100),
    FECHAMODIFICACION    TIMESTAMP(6),
    ACTIVO               CHAR
)
</code>```

I don't know, what is the error. Any idea?

Body:
I am using Blazebit and Deltaspike in a jakarta ee project.
The database is oracle.

https://github.com/joedayz/curso-java-sbs/tree/main/comparabienangular/concentrador-oracle

In it repo, my problem is in the class ConsultaProductoServiceImpl and method "consulta". I receive the data from a frontend web application but when execute the findAll with specification, I got it error:

[2022-12-18T18:04:13.470-0500] [Payara 5.2021.4] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=117 _ThreadName=http-thread-pool::http-listener-1(2)] [timeMillis: 1671404653470] [levelValue: 900] [[
  StandardWrapperValve[pe.farmaciasperuanas.concentrador.controller.ConcentradorRestApplication]: Servlet.service() for servlet pe.farmaciasperuanas.concentrador.controller.ConcentradorRestApplication threw exception
java.lang.ClassCastException: class java.math.BigDecimal cannot be cast to class java.lang.Long (java.math.BigDecimal and java.lang.Long are in module java.base of loader 'bootstrap')
    at com.blazebit.persistence.impl.PaginatedTypedQueryImpl.getResultList(PaginatedTypedQueryImpl.java:441)
    at com.blazebit.persistence.impl.PaginatedTypedQueryImpl.getResultList(PaginatedTypedQueryImpl.java:218)
    at com.blazebit.persistence.impl.PaginatedTypedQueryImpl.getResultList(PaginatedTypedQueryImpl.java:58)
    at com.blazebit.persistence.deltaspike.data.base.handler.AbstractEntityViewAwareRepositoryHandler.findAll(AbstractEntityViewAwareRepositoryHandler.java:322)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at com.blazebit.persistence.deltaspike.data.impl.builder.EntityViewDelegateQueryBuilder.invoke(EntityViewDelegateQueryBuilder.java:113)
    at com.blazebit.persistence.deltaspike.data.impl.builder.EntityViewDelegateQueryBuilder.execute(EntityViewDelegateQueryBuilder.java:61)
    at com.blazebit.persistence.deltaspike.data.impl.builder.EntityViewQueryBuilder.executeQuery(EntityViewQueryBuilder.java:37)
    at com.blazebit.persistence.deltaspike.data.impl.builder.EntityViewDelegateQueryBuilder$Proxy$_$$_WeldClientProxy.executeQuery(Unknown Source)
    at com.blazebit.persistence.deltaspike.data.impl.handler.TransactionalEntityViewQueryRunner.executeNonTransactional(TransactionalEntityViewQueryRunner.java:58)
    at com.blazebit.persistence.deltaspike.data.impl.handler.TransactionalEntityViewQueryRunner.executeQuery(TransactionalEntityViewQueryRunner.java:54)
    at com.blazebit.persistence.deltaspike.data.impl.handler.TransactionalEntityViewQueryRunner$Proxy$_$$_WeldClientProxy.executeQuery(Unknown Source)
    at com.blazebit.persistence.deltaspike.data.impl.handler.EntityViewAwareQueryHandler.process(EntityViewAwareQueryHandler.java:101)
    at org.apache.deltaspike.data.impl.handler.QueryHandler.invoke(QueryHandler.java:130)
    at com.blazebit.persistence.deltaspike.data.impl.handler.EntityViewAwareQueryHandler$Proxy$_$$_WeldClientProxy.invoke(Unknown Source)
    at org.apache.deltaspike.proxy.spi.invocation.DeltaSpikeProxyInvocationHandler.proceed(DeltaSpikeProxyInvocationHandler.java:97)
    at org.apache.deltaspike.proxy.spi.invocation.DeltaSpikeProxyInvocationHandler.invoke(DeltaSpikeProxyInvocationHandler.java:78)
    at org.apache.deltaspike.proxy.spi.invocation.DeltaSpikeProxyInvocationHandler$Proxy$_$$_WeldClientProxy.invoke(Unknown Source)
    at pe.farmaciasperuanas.concentrador.repository.ConsultaEntidadProductoRepository$$DSPartialBeanProxy.findAll(Unknown Source)
    at pe.farmaciasperuanas.concentrador.service.impl.ConsultaProductoServiceImpl.consulta(ConsultaProductoServiceImpl.java:45)
    at pe.farmaciasperuanas.concentrador.controller.ConsultaEntidadProductoController.consulta(ConsultaEntidadProductoController.java:30)
    at pe.farmaciasperuanas.concentrador.controller.ConsultaEntidadProductoController$Proxy$_$$_WeldClientProxy.consulta(Unknown Source)

In the Database the structure of the table is:

create table DETALLEPRODUCTOFINANCIERO
(
    DETALLEPRODUCTOFINANCIEROID NUMBER(19) generated as identity
        primary key,
    PRODUCTOFINANCIEROID        NUMBER(19)
        constraint FK_DETALLEPRODUCTOFINANCIERO_PRODUCTOFINANCIEROID
            references PRODUCTOFINANCIERO,
    TIPOMONEDAID                NUMBER,
    INGRESOPERMITIDO            NUMBER,
    MONTOMINIMOPRESTAMO         NUMBER,
    MONTOMAXIMOPRESTAMO         NUMBER,
    MONTOMINIMODEPOSITO         NUMBER,
    MONTOMAXIMODEPOSITO         NUMBER
)
/

and

create table PRODUCTOFINANCIERO
(
    PRODUCTOFINANCIEROID NUMBER(19) generated as identity
        primary key,
    TIPOPRODUCTOID       NUMBER(4),
    ENTIDADFINANCIERAID  NUMBER(19)
        constraint FK_PRODUCTOFINANCIERO_ENTIDADFINANCIERAID
            references ENTIDADFINANCIERA,
    NOMBRE               VARCHAR2(100),
    DESCRIPCION          VARCHAR2(200),
    PORCENTAJETEA        NUMBER(10, 2),
    PORCENTAJECOMISION   NUMBER(10, 2),
    PORCENTAJESEGURO     NUMBER(10, 2),
    OBSERVACION          VARCHAR2(500),
    PLAZOMINIMOMES       NUMBER,
    PLAZOMAXIMOMES       NUMBER,
    PLAZOMINIMODIA       NUMBER,
    PLAZOMAXIMODIA       NUMBER,
    TIENEFONDOSEGURO     CHAR,
    USUARIOREGISTRO      VARCHAR2(100),
    FECHAREGISTRO        TIMESTAMP(6),
    USUARIOMODIFICA      VARCHAR2(100),
    FECHAMODIFICACION    TIMESTAMP(6),
    ACTIVO               CHAR
)

I don't know, what is the error. Any idea?


来源: stackexchange

问:
Token Revocation in new Spring Authorization Server is not working
After revoking token with /oauth2/revoke I can still use this token to request secured data. Actually as I see revoke endpoint does not doing revocation at all it is just removing some metadata. I thought that revocation should drop token from database or invalidate token to not allow user to make further requests with this token. Could somebody please explain what is the expected behavior of /oauth2/revoke request (should token be deleted from DB)?

I tried to use default spring token revocation endpoint and it does not work. After revoking token I can still request secured data with this token.

ContentLicense: CC BY-SA 4.0


问:
Mongoose connection using top lvl await?
I want to try to use top lvl await to connect to MongoDB with Mongoose, for example, normally I am doing it like this :

```<code>const mongoose = require('mongoose');
const PORT = process.env.PORT || 8080;

async function startServer() {
try {
      await mongoose.connect(`mongodb+srv://${process.env.DATABASE_ACCESS}`);
    } catch (err) {
      console.log(err);
    }
}
mongoose.connection.once('open', () => {
    console.log("connection ready!");
})
mongoose.connection.on('error', (err) => {
    console.error(err);
})

startServer().then(() => {
    app.listen(PORT, () => {
        console.log(`app is running on port ${PORT}...`)
    });
}).catch(err => console.log(err));
</code>```

it work fine and in the console i can see "the connection ready" message and the app is running at port... etc, however if I try to use ES2022 top lvl await like this :

```<code>import mongoose from "mongoose";
const PORT = process.env.PORT || 8080;

try {
      await mongoose.connect(`mongodb+srv://${process.env.DATABASE_ACCESS}`);
    } catch (err) {
      console.log(err);
    }
mongoose.connection.once('open', () => {
    console.log("connection ready!");
})
mongoose.connection.on('error', (err) => {
    console.error(err);
})
app.listen(PORT, () => {
            console.log(`app is running on port ${PORT}...`)
});
</code>```

I can see the app is running at port... but no "connection ready" message, I don't see any error either, so I wonder if i am doing something wrong or I cannot use top lvl await in Mongoose ?

Body:
I want to try to use top lvl await to connect to MongoDB with Mongoose, for example, normally I am doing it like this :

const mongoose = require('mongoose');
const PORT = process.env.PORT || 8080;

async function startServer() {
try {
      await mongoose.connect(`mongodb+srv://${process.env.DATABASE_ACCESS}`);
    } catch (err) {
      console.log(err);
    }
}
mongoose.connection.once('open', () => {
    console.log("connection ready!");
})
mongoose.connection.on('error', (err) => {
    console.error(err);
})

startServer().then(() => {
    app.listen(PORT, () => {
        console.log(`app is running on port ${PORT}...`)
    });
}).catch(err => console.log(err));

it work fine and in the console i can see "the connection ready" message and the app is running at port... etc, however if I try to use ES2022 top lvl await like this :

import mongoose from "mongoose";
const PORT = process.env.PORT || 8080;

try {
      await mongoose.connect(`mongodb+srv://${process.env.DATABASE_ACCESS}`);
    } catch (err) {
      console.log(err);
    }
mongoose.connection.once('open', () => {
    console.log("connection ready!");
})
mongoose.connection.on('error', (err) => {
    console.error(err);
})
app.listen(PORT, () => {
            console.log(`app is running on port ${PORT}...`)
});

I can see the app is running at port... but no "connection ready" message, I don't see any error either, so I wonder if i am doing something wrong or I cannot use top lvl await in Mongoose ?


问:
In AWS cloudformation how do I create a glue job with notebook
I'm trying to use a AWS cloudformation stack to create a glue job with Jupyter Notebook using a .ipynb file in my s3 bucket.  By any chance there is a way to achieve that?

I’ve tried to use the console to create a Jupiter Note book glue job, by looking at the json file it
Generated there is a
jobMode: NOTEBOOK_MODE
I try to read through the documentation of cloudformation it doesn’t have a placeholder for the job mode


问:
Javascript - Recursive function to create a tree diagram of connected nodes
I have got the following code,

import Graph from "graphology"
const graph = new Graph({
  multi: true,
  allowSelfLoops: false,
  type: "directed"
})

graph.addNode("1");
graph.addNode("2");
graph.addNode("3");
graph.addNode("4");
graph.addNode("5");
graph.addNode("6");
graph.addNode("7");
graph.addNode("8");
graph.addNode("9");
graph.addNode("10");

graph.addEdge("1", "2");
graph.addEdge("1", "3");
graph.addEdge("4", "5");
graph.addEdge("4", "6");
graph.addEdge("3", "7");
graph.addEdge("5", "7");
graph.addEdge("7", "8");
graph.addEdge("7", "9");
graph.addEdge("9", "10");

const buildTreeFromParents = (graph, start) => {
  try {
    const parents = graph.inboundNeighbors(start)

    if (parents.length === 0) {
      return { value: start }
    }

    return {
      value: start,
      children: parents.map((e) => buildTreeFromParents(graph, e))
    }
  } catch (error) {
    return 'Loop has been created.'
  }
}

const levels = buildTreeFromParents(graph, 10)

function Item(props) {
  return (

        {props.value}

      {props.children}

  )
}

const mapArray = (array, level) => {
  if (array.children) {
    return (

        {
          level === 1
            ? <Item key={array.value} value={array.value}>
                {mapArray(array, level+1)}
              </Item>
            : array.children.map(e => {
                return (
                  <Item key={e.value} value={e.value}>
                    {mapArray(e, level+1)}
                  </Item>
                )
              })
        }

    )
  }
}

export default function GraphPage() {
  return (
    <>
      <link rel="stylesheet" href="https://unpkg.com/treeflex/dist/css/treeflex.css" />

          { mapArray(levels, 1) }

    </>
  )
}
```
<p>which generates a path from a starting node and then prints the nodes that are its parents in a tree.
An image of the nodes and edges is below for visualisation:</p>
<p><img src="https://i.stack.imgur.com/o7AYm.png" alt="Image" /></p>
<p>The function <code>buildTreeFromParents</code> will create a variable (<code>levels</code>) from a given starting node, listing in nested arrays its parents: e.g. for the node 10 the outcome is</p>
<pre class="lang-js prettyprint-override"><code>{
    "value": 10,
    "children": [
        {
            "value": "9",
            "children": [
                {
                    "value": "7",
                    "children": [
                        {
                            "value": "3",
                            "children": [
                                {
                                    "value": "1"
                                }
                            ]
                        },
                        {
                            "value": "5",
                            "children": [
                                {
                                    "value": "4"
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}
</code>```

Following this, the function mapArray() will take levels and render out a tree displaying the nodes using the TreeFlex library.

My question is, is my recursive function set up correctly, and are there any edge cases I haven't considered? I have tested some other graph configurations but can not be 100% sure if I have covered all arrangements.

Thank you in advance.

Body:
I have got the following code,

import Graph from "graphology"
const graph = new Graph({
  multi: true,
  allowSelfLoops: false,
  type: "directed"
})

graph.addNode("1");
graph.addNode("2");
graph.addNode("3");
graph.addNode("4");
graph.addNode("5");
graph.addNode("6");
graph.addNode("7");
graph.addNode("8");
graph.addNode("9");
graph.addNode("10");

graph.addEdge("1", "2");
graph.addEdge("1", "3");
graph.addEdge("4", "5");
graph.addEdge("4", "6");
graph.addEdge("3", "7");
graph.addEdge("5", "7");
graph.addEdge("7", "8");
graph.addEdge("7", "9");
graph.addEdge("9", "10");

const buildTreeFromParents = (graph, start) => {
  try {
    const parents = graph.inboundNeighbors(start)

    if (parents.length === 0) {
      return { value: start }
    }

    return {
      value: start,
      children: parents.map((e) => buildTreeFromParents(graph, e))
    }
  } catch (error) {
    return 'Loop has been created.'
  }
}

const levels = buildTreeFromParents(graph, 10)

function Item(props) {
  return (

        {props.value}

      {props.children}

  )
}

const mapArray = (array, level) => {
  if (array.children) {
    return (

        {
          level === 1
            ? <Item key={array.value} value={array.value}>
                {mapArray(array, level+1)}
              </Item>
            : array.children.map(e => {
                return (
                  <Item key={e.value} value={e.value}>
                    {mapArray(e, level+1)}
                  </Item>
                )
              })
        }

    )
  }
}

export default function GraphPage() {
  return (
    <>
      <link rel="stylesheet" href="https://unpkg.com/treeflex/dist/css/treeflex.css" />

          { mapArray(levels, 1) }

    </>
  )
}

which generates a path from a starting node and then prints the nodes that are its parents in a tree.
An image of the nodes and edges is below for visualisation:

The function buildTreeFromParents will create a variable (levels) from a given starting node, listing in nested arrays its parents: e.g. for the node 10 the outcome is

{
    "value": 10,
    "children": [
        {
            "value": "9",
            "children": [
                {
                    "value": "7",
                    "children": [
                        {
                            "value": "3",
                            "children": [
                                {
                                    "value": "1"
                                }
                            ]
                        },
                        {
                            "value": "5",
                            "children": [
                                {
                                    "value": "4"
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

Following this, the function mapArray() will take levels and render out a tree displaying the nodes using the TreeFlex library.

My question is, is my recursive function set up correctly, and are there any edge cases I haven't considered? I have tested some other graph configurations but can not be 100% sure if I have covered all arrangements.

Thank you in advance.


问:
How to ensure all the custom function() is executed which calls for multiple columns and column manipulation?
This is my first go at writing a function. Partly successful, I do get the values in the table correct. But, the dataframe title is output as "df" instead of say calc_ACR(df = pACR_19_1, ...) giving me a table titled 'pACR_19_1'. My use of enquo seems to be fine functionally, but I have not seen it done like this anywhere. A similar issue occurs with the mmol_name where the object name just outputs "mmol_name".
`

```<code>calc_ACR  <- function(df, df1 = crude_test, uPCR, Sex, Diabetes, Hypertension, mmol_name) {
  uPCR = enquo(uPCR)
  Sex = enquo(Sex)
  Diabetes = enquo(Diabetes)
  Hypertension = enquo(Hypertension)

  df <- df1 %>%
    select(!!uPCR,!!Sex, !!Diabetes, !!Hypertension)

  df <- df %>%
    mutate(uPCR_500 = ((!!uPCR*0.01768))) %>%
    mutate(uPCR_50 = ((!!uPCR*0.1768)))

  df <- df %>%
    mutate(min_50 = (pmin(uPCR_50,1))) %>%
    mutate(min_500 = (pmin(uPCR_500,1))) %>%
    mutate(max_min_500 = (pmax(min_500,0.1))) %>%
    mutate(max_500 = (pmax(uPCR_500,1)))

  df <- df %>%
    mutate(predACR = exp(5.2659 + (0.2934 * log(min_50)) + (1.5643 * log(max_min_500)) + (1.1109 * log(max_500)) - 0.0773*!!Sex + 0.0797*!!Diabetes + 0.1265*!!Hypertension))
  #This equation provides predicted ACR in mg/g, so need to conver to mg/mmol

  df <- df %>%
    mutate(mmol_name = predACR/8.84)
  View(df)
}
</code>```

`

I have tried using ensym() around the mmol_name and df variables in the function, but this still did not work.

Body:
This is my first go at writing a function. Partly successful, I do get the values in the table correct. But, the dataframe title is output as "df" instead of say calc_ACR(df = pACR_19_1, ...) giving me a table titled 'pACR_19_1'. My use of enquo seems to be fine functionally, but I have not seen it done like this anywhere. A similar issue occurs with the mmol_name where the object name just outputs "mmol_name".
`

calc_ACR  <- function(df, df1 = crude_test, uPCR, Sex, Diabetes, Hypertension, mmol_name) {
  uPCR = enquo(uPCR)
  Sex = enquo(Sex)
  Diabetes = enquo(Diabetes)
  Hypertension = enquo(Hypertension)

  df <- df1 %>%
    select(!!uPCR,!!Sex, !!Diabetes, !!Hypertension)

  df <- df %>%
    mutate(uPCR_500 = ((!!uPCR*0.01768))) %>%
    mutate(uPCR_50 = ((!!uPCR*0.1768)))

  df <- df %>%
    mutate(min_50 = (pmin(uPCR_50,1))) %>%
    mutate(min_500 = (pmin(uPCR_500,1))) %>%
    mutate(max_min_500 = (pmax(min_500,0.1))) %>%
    mutate(max_500 = (pmax(uPCR_500,1)))

  df <- df %>%
    mutate(predACR = exp(5.2659 + (0.2934 * log(min_50)) + (1.5643 * log(max_min_500)) + (1.1109 * log(max_500)) - 0.0773*!!Sex + 0.0797*!!Diabetes + 0.1265*!!Hypertension))
  #This equation provides predicted ACR in mg/g, so need to conver to mg/mmol

  df <- df %>%
    mutate(mmol_name = predACR/8.84)
  View(df)
}

`

I have tried using ensym() around the mmol_name and df variables in the function, but this still did not work.


问:
Phoenix - Changes to socket.assigns not reflected in another channel under the same socket?
I probably have a wrong mental model of how sockets and channels work in Phoenix. This is the scenario that confuses me:

I declare two channels under the same socket:

```<code>defmodule MyAppWeb.TestSocket do
  channel("a:*", MyAppWeb.AChannel)
  channel("b:*", MyAppWeb.BChannel)
end
</code>```

I perform socket assignment in the connect function of the socket module:

```<code>  def connect(payload, socket) do
       {:ok, assign(socket, :foo, 1)}
  end
</code>```

Then in the handle_in function of channel A, I perform some further assignments:

```<code>defmodule MyAppWeb.AChannel do
  def handle_in("example_msg", payload, socket) do
      {:reply, :ok, assign(socket, :new_key, "aaa")}
  end
end
</code>```

However, when the client then tries to join channel B, channel B doesn't seem to pick up this :new_key.

```<code>defmodule MyAppWeb.BChannel do
  def join("b:" <> room_identifier, _payload, socket) do
    # Only contains :foo
    IO.inspect(socket)
    # ...
  end
end
</code>```

The socket only contains :foo, but not the :new_key assigned in channel A.

Am I doing the wrong thing by trying to let channel B access a socket modified by channel A? I thought that since the client is only connected to the server via one single socket, any modifications to its assigns should also be shared across the channels, just like how all channels see the :foo key assigned during the initial socket connection. However, this doesn't seem to be the case.

Body:
I probably have a wrong mental model of how sockets and channels work in Phoenix. This is the scenario that confuses me:

I declare two channels under the same socket:

defmodule MyAppWeb.TestSocket do
  channel("a:*", MyAppWeb.AChannel)
  channel("b:*", MyAppWeb.BChannel)
end

I perform socket assignment in the connect function of the socket module:

  def connect(payload, socket) do
       {:ok, assign(socket, :foo, 1)}
  end

Then in the handle_in function of channel A, I perform some further assignments:

defmodule MyAppWeb.AChannel do
  def handle_in("example_msg", payload, socket) do
      {:reply, :ok, assign(socket, :new_key, "aaa")}
  end
end

However, when the client then tries to join channel B, channel B doesn't seem to pick up this :new_key.

defmodule MyAppWeb.BChannel do
  def join("b:" <> room_identifier, _payload, socket) do
    # Only contains :foo
    IO.inspect(socket)
    # ...
  end
end

The socket only contains :foo, but not the :new_key assigned in channel A.

Am I doing the wrong thing by trying to let channel B access a socket modified by channel A? I thought that since the client is only connected to the server via one single socket, any modifications to its assigns should also be shared across the channels, just like how all channels see the :foo key assigned during the initial socket connection. However, this doesn't seem to be the case.


问:
Hide Docker Run Command in Docker Build Output
I'm having a problem where a password is being shown when I run a docker build command. This is because the Dockerfile contains a curl command that uses a username and password to authenticate the command, like this:

```<code>=> CACHED [stage-0  7/15] RUN curl -u "<Username>:<Password>" ...  0.0s
</code>```

I tried rerouting the output of the curl to /dev/null like this:

```<code>cmd >/dev/null 2>&1
</code>```

But that only hides output from the curl command not the actual command itself.

Body:
I'm having a problem where a password is being shown when I run a docker build command. This is because the Dockerfile contains a curl command that uses a username and password to authenticate the command, like this:

=> CACHED [stage-0  7/15] RUN curl -u "<Username>:<Password>" ...  0.0s

I tried rerouting the output of the curl to /dev/null like this:

cmd >/dev/null 2>&1

But that only hides output from the curl command not the actual command itself.


问:
How to give a rust program access (permission) to my camera?
I'm using uvc to try and get frames from my webcam. Everything is working up to the point where I try and open the webcam device.

Code:

use uvc::{Context, Frame};

fn main() {
    let ctx = Context::new().expect("Could not create context");
    let dev = ctx
        .find_device(None, None, None)
        .expect("Could not find device");

    let devh = dev.open().expect("Could not open device");
}
```

Error:

thread 'main' panicked at 'Could not open device: Access'

This is all just part of an example in the Uvc github, really I don't have any clues of what's going on. I'm using Ubuntu 22.10.

I've tried using sudo cargo run instead, but rust isn't installed for root user, so it didn't work. I'd also prefer to avoid sudo if possible.

Body:
I'm using uvc to try and get frames from my webcam. Everything is working up to the point where I try and open the webcam device.

Code:

use uvc::{Context, Frame};

fn main() {
    let ctx = Context::new().expect("Could not create context");
    let dev = ctx
        .find_device(None, None, None)
        .expect("Could not find device");

    let devh = dev.open().expect("Could not open device");
}

Error:

thread 'main' panicked at 'Could not open device: Access'

This is all just part of an example in the Uvc github, really I don't have any clues of what's going on. I'm using Ubuntu 22.10.

I've tried using sudo cargo run instead, but rust isn't installed for root user, so it didn't work. I'd also prefer to avoid sudo if possible.


问:
always the same value after certain iteration
why is the result of this code after some iterations (10e7) is always 32768? https://godbolt.org/z/GMf4Ps9cP

(x and y are single 32 bit IEEE 754 floating point)

```<code>#include <iostream>

int main(){
    float x{0.0};
    float y{0.001};

    for (int i{0}; i<10e7; i++){
        x = x + y;
    }

    std::cout << x << '\n';
    return 0;
}
</code>```

Body:
why is the result of this code after some iterations (10e7) is always 32768? https://godbolt.org/z/GMf4Ps9cP

(x and y are single 32 bit IEEE 754 floating point)

#include <iostream>

int main(){
    float x{0.0};
    float y{0.001};

    for (int i{0}; i<10e7; i++){
        x = x + y;
    }

    std::cout << x << '\n';
    return 0;
}


问:
function to save user using microservices in spring boot?
```<code>@PostMapping(value="/users/save")
    public String saveUser(@RequestBody User user){
        userRepo.save(user);
        return "saved ..";

    }
</code>```
```<code>    "message": "JSON parse error: Cannot deserialize value of type `com.print.PMS.Models.User` from Array value (token `JsonToken.START_ARRAY`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `com.print.PMS.Models.User` from Array value (token `JsonToken.START_ARRAY`)\n at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]",
    "path": "/users/save"
</code>```

i send json data type to my database using a post from postman

Body:
@PostMapping(value="/users/save")
    public String saveUser(@RequestBody User user){
        userRepo.save(user);
        return "saved ..";

    }

    "message": "JSON parse error: Cannot deserialize value of type `com.print.PMS.Models.User` from Array value (token `JsonToken.START_ARRAY`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `com.print.PMS.Models.User` from Array value (token `JsonToken.START_ARRAY`)\n at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]",
    "path": "/users/save"

i send json data type to my database using a post from postman


问:
how to request django post method values using ajax
I would like to implement simple django login method using ajax. when i want to retreive html input values using ajax in views, the request.post values are returning None. for ex print(request.POST.get('username')), it returns None.

my html form

```<code><form action="" method="POST">{% csrf_token %}

              <input type="text" name="username1" class="form-control rounded-1" id="id_username1" value="">
              <input type="password" name="password1" class="form-control rounded-1" id="id_password1" value="">
            </div>
            <input type="button" id="btnlogin" value='Valider'>

          </form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.2/jquery.min.js"></script>

<script>
  var token = '{{csrf_token}}';
//login
$('#btnlogin').click(function(){
    //alert("/login");
    $.ajax({
        url: "{% url 'login' %}",
        headers:{'X-CSRFToken':token},
        method:"POST",
        data:{},
        dataType: 'json',
        success: function (data) {
          if (data.status){
            console.log('Success');
          }
          else{
            console.log("login failed");
          }
        }
    });
  })
  </script>
</code>```

urls.py

```<code>path('login/', views.login_page, name='login'),
</code>```

views.py

```<code>def login_page(request):

    if request.method == 'POST':
        username = request.POST.get('username1')
        password = request.POST.get('password1')
        print('password :',password)
        #result "password : None"
        user = authenticate(username=username, password=password)
        if user is not None:
           login(request, user)
           return JsonResponse({'status':True})
        else:
           return JsonResponse({'status':False})
    context = {}
    return render(request, 'core/login.html', context)
</code>```

I do not know where is the error and how to fix this issue.
Thanx in advance.

i tried request.POST['password1']#result None
i changed to GET method. same issue.
I would like to collect forms input values in django view method using ajax

Body:
I would like to implement simple django login method using ajax. when i want to retreive html input values using ajax in views, the request.post values are returning None. for ex print(request.POST.get('username')), it returns None.

my html form

<form action="" method="POST">{% csrf_token %}

              <input type="text" name="username1" class="form-control rounded-1" id="id_username1" value="">
              <input type="password" name="password1" class="form-control rounded-1" id="id_password1" value="">

            <input type="button" id="btnlogin" value='Valider'>

          </form>

urls.py

path('login/', views.login_page, name='login'),

views.py

def login_page(request):

    if request.method == 'POST':
        username = request.POST.get('username1')
        password = request.POST.get('password1')
        print('password :',password)
        #result "password : None"
        user = authenticate(username=username, password=password)
        if user is not None:
           login(request, user)
           return JsonResponse({'status':True})
        else:
           return JsonResponse({'status':False})
    context = {}
    return render(request, 'core/login.html', context)

I do not know where is the error and how to fix this issue.
Thanx in advance.

i tried request.POST['password1']#result None
i changed to GET method. same issue.
I would like to collect forms input values in django view method using ajax


问:
Tkinter text updates take too long to load
i've got a working piece of code here, but when the if flag == True: statement completes, the playsound activates, but it takes roughly 3 seconds longer for the detectionLabel text to update. Can someone take a look at the code below and help recommend a way that I can help speed up the text updating process? Thanks!

```<code>    def loop(addressField,url):
    detectionLabel['text']="Scanning..."
    flag = False
    address = addressField.get()
    def loopOver(flag):
        print("loop")
        flag,response = searchLoop(address,url,flag)
        if flag == True:
            print("Detected")
            playsound.playsound('success.mp3')
            detectionLabel['text']=f"DETECTED:\n{response}"
        else:
            detectionWindow.after(5000,lambda: loopOver(flag))

    loopOver(flag)
</code>```

Body:
i've got a working piece of code here, but when the if flag == True: statement completes, the playsound activates, but it takes roughly 3 seconds longer for the detectionLabel text to update. Can someone take a look at the code below and help recommend a way that I can help speed up the text updating process? Thanks!

    def loop(addressField,url):
    detectionLabel['text']="Scanning..."
    flag = False
    address = addressField.get()
    def loopOver(flag):
        print("loop")
        flag,response = searchLoop(address,url,flag)
        if flag == True:
            print("Detected")
            playsound.playsound('success.mp3')
            detectionLabel['text']=f"DETECTED:\n{response}"
        else:
            detectionWindow.after(5000,lambda: loopOver(flag))

    loopOver(flag)


问:
Vulkan compute shader outputs black lines on frames when on macOs if workgroup size is at maximum of 1024 invocations
I'm currently working on a small SDF based graphics engine that uses compute shaders to calculate the pixel colours from data provided via storage buffers.

I've encountered a weird problem where the frames rendered by my compute shader render black lines, like so (the green pixels are correct, showing green to see the black lines better):

I've isolated a minimal example of glsl code that produces this issue, commented for clarity. The issue occurs during traversal of my spatial acceleration data structure, a bounding interval hierarchy. The only part that's relevant for the issue is, that i'm extracting booleans from flags set in the first bits of a bounding interval link integer.

// relevant struct definition of a bounding interval
struct bounding_interval
{
    uint link;
    uint target;
    float coordinate;
};

// compute work group dimensions
layout(local_size_x = 32, local_size_y = 32) in;

// push constants provide window size and scene bounding box
layout(push_constant) uniform constants
{
    uvec2 window_size;
    vec2 scene_lower_bound;
    vec2 scene_upper_bound;
};

// relevant input buffer
...
layout(set = 0, binding = 3) buffer _tlbih { bounding_interval tlbih[]; };

// output image
layout(set = 1, binding = 0, rgba8_snorm) uniform writeonly image2D output_image;

// checks if the query point is within the scene bounding box
// the scene bounding box is provided by push constants
bool point_is_within_scene (vec2 point)
{
    return point.x > scene_lower_bound.x && point.x < scene_upper_bound.x && point.y > scene_lower_bound.y && point.y < scene_upper_bound.y;
}

// checks if the query point is to the left of the bounding interval border
bool point_is_left_in_tlbi (vec2 point, uint index)
{
    return point[ (tlbih[index].link & 0x40000000) >> 30 ] < tlbih[index].coordinate;
}

// checks if the query point is directly on the bounding interval border
bool point_is_center_in_tlbi (vec2 point, uint index)
{
    return point[ (tlbih[index].link & 0x40000000) >> 30 ] == tlbih[index].coordinate;
}

// checks if the current bounding interval is "left" or "right"
bool current_tlbi_is_right (uint index)
{
    return bool(tlbih[index].link & 0x20000000);
}

// checks if a query point intersects a bounding interval
bool point_intersects_tlbi (vec2 point, uint index)
{
    return ((point_is_left_in_tlbi(point, index) || point_is_center_in_tlbi(point, index)) && !current_tlbi_is_right(index)) || ((!point_is_left_in_tlbi(point, index) || point_is_center_in_tlbi(point, index)) && current_tlbi_is_right(index));
}

// checks if the current bounding interval is a "leaf" and therefore points to a primitive shape
bool current_tlbi_is_leaf (uint index)
{
    return bool(tlbih[index].link & 0x80000000);
}

// supposed to iterate over bounding interval hierarchy and output a colour
// removed most irrelevant code
vec4 determine_pixel_colour (vec2 point)
{
    vec3 colour = vec3(0.0);
    uint current_tlbi = 0;

    if ( !point_is_within_scene( point )) return vec4(colour, 1.0);

    while (true) {

        colour.x = 0.0;

        if ( point_intersects_tlbi( point, current_tlbi )) {

            // the issue only appears once this nested if statement is added
            if ( current_tlbi_is_leaf( current_tlbi )) {
                colour.x = 1.0;
            }

            return vec4(colour, 1.0);
        }
        else {
            return vec4(colour, 1.0);
        }
    }
}

// calculates the pixel coordinates based on the compute thread ids
ivec2 determine_pixel_coordinates ()
{
    return ivec2( clamp(gl_LocalInvocationID.xy + gl_WorkGroupID.xy * 32, ivec2(0), window_size) );
}

void main()
{
    ivec2 coordinates = determine_pixel_coordinates();

    // flips y coordinate so y+ is up, not down
    ivec2 y_inverted_coordinates = ivec2( coordinates.x, window_size.y - coordinates.y );
    vec2 point = (2.0 * y_inverted_coordinates - window_size) / float(window_size.y);

    vec4 pixel_colour = determine_pixel_colour(point);

    // adds green colour to make black lines visible
    pixel_colour += vec4(0.0, 0.5, 0.0, 1.0);

    imageStore(output_image, coordinates, pixel_colour);
}
```

What I've determined so far:

The very same code does NOT create the same black lines on my desktop windows pc (nvidia gtx 1080 ti) --> the issue occurs on my Macbook Pro (running macOs, therefore requiring moltonVK to run vulkan)

The issue does NOT occur when that nested if statement (marked by comment) in determine_pixel_colour is not presented

The issue does NOT occur when the current_tlbi_is_leaf function is called in the outer if statement

The amount of black lines is equal to the amount of work groups on the vertical axis. So each compute workgroup (32 x 32 threads) returns the correct colour for the first half, then returns black for the second half

The issue does NOT occur when the boolean is determined based on hardcoded values e.g. bool(2147483648 & 0x80000000) works fine --> is the buffer access the problem?

Question:

is this a moltonVK issue (due to it only happening on my mac device)?

is this a buffer access issue (due to the boolean not being a problem when using some hardcoded number)?

could this be a present mode issue (macOS version uses FIFO, windows version uses Mailbox)?

---------- Update 1 ----------

I discovered that this issue does not occur, when I set the local workgroup size to 16 * 16 invocations. While this would technically fix the issue, I still do not understand, why 32 * 32 invocations fail to render half of themselves. The maximum work group invocations of my macbook is set to 1024 - so my invocation count does not exceed this maximum.

---------- Update 2 ----------

When choosing 16 * 16 * 4 invocations as a local size in my compute shader and therefore achieving the same invocation count as 32 * 32, the same issue occurs. It seems to be an issue that only occurs, when my local invocation count equals the maximum specified by the device used.

Body:
I'm currently working on a small SDF based graphics engine that uses compute shaders to calculate the pixel colours from data provided via storage buffers.

I've encountered a weird problem where the frames rendered by my compute shader render black lines, like so (the green pixels are correct, showing green to see the black lines better):

I've isolated a minimal example of glsl code that produces this issue, commented for clarity. The issue occurs during traversal of my spatial acceleration data structure, a bounding interval hierarchy. The only part that's relevant for the issue is, that i'm extracting booleans from flags set in the first bits of a bounding interval link integer.

// relevant struct definition of a bounding interval
struct bounding_interval
{
    uint link;
    uint target;
    float coordinate;
};

// compute work group dimensions
layout(local_size_x = 32, local_size_y = 32) in;

// push constants provide window size and scene bounding box
layout(push_constant) uniform constants
{
    uvec2 window_size;
    vec2 scene_lower_bound;
    vec2 scene_upper_bound;
};

// relevant input buffer
...
layout(set = 0, binding = 3) buffer _tlbih { bounding_interval tlbih[]; };

// output image
layout(set = 1, binding = 0, rgba8_snorm) uniform writeonly image2D output_image;

// checks if the query point is within the scene bounding box
// the scene bounding box is provided by push constants
bool point_is_within_scene (vec2 point)
{
    return point.x > scene_lower_bound.x && point.x < scene_upper_bound.x && point.y > scene_lower_bound.y && point.y < scene_upper_bound.y;
}

// checks if the query point is to the left of the bounding interval border
bool point_is_left_in_tlbi (vec2 point, uint index)
{
    return point[ (tlbih[index].link & 0x40000000) >> 30 ] < tlbih[index].coordinate;
}

// checks if the query point is directly on the bounding interval border
bool point_is_center_in_tlbi (vec2 point, uint index)
{
    return point[ (tlbih[index].link & 0x40000000) >> 30 ] == tlbih[index].coordinate;
}

// checks if the current bounding interval is "left" or "right"
bool current_tlbi_is_right (uint index)
{
    return bool(tlbih[index].link & 0x20000000);
}

// checks if a query point intersects a bounding interval
bool point_intersects_tlbi (vec2 point, uint index)
{
    return ((point_is_left_in_tlbi(point, index) || point_is_center_in_tlbi(point, index)) && !current_tlbi_is_right(index)) || ((!point_is_left_in_tlbi(point, index) || point_is_center_in_tlbi(point, index)) && current_tlbi_is_right(index));
}

// checks if the current bounding interval is a "leaf" and therefore points to a primitive shape
bool current_tlbi_is_leaf (uint index)
{
    return bool(tlbih[index].link & 0x80000000);
}

// supposed to iterate over bounding interval hierarchy and output a colour
// removed most irrelevant code
vec4 determine_pixel_colour (vec2 point)
{
    vec3 colour = vec3(0.0);
    uint current_tlbi = 0;

    if ( !point_is_within_scene( point )) return vec4(colour, 1.0);

    while (true) {

        colour.x = 0.0;

        if ( point_intersects_tlbi( point, current_tlbi )) {

            // the issue only appears once this nested if statement is added
            if ( current_tlbi_is_leaf( current_tlbi )) {
                colour.x = 1.0;
            }

            return vec4(colour, 1.0);
        }
        else {
            return vec4(colour, 1.0);
        }
    }
}

// calculates the pixel coordinates based on the compute thread ids
ivec2 determine_pixel_coordinates ()
{
    return ivec2( clamp(gl_LocalInvocationID.xy + gl_WorkGroupID.xy * 32, ivec2(0), window_size) );
}

void main()
{
    ivec2 coordinates = determine_pixel_coordinates();

    // flips y coordinate so y+ is up, not down
    ivec2 y_inverted_coordinates = ivec2( coordinates.x, window_size.y - coordinates.y );
    vec2 point = (2.0 * y_inverted_coordinates - window_size) / float(window_size.y);

    vec4 pixel_colour = determine_pixel_colour(point);

    // adds green colour to make black lines visible
    pixel_colour += vec4(0.0, 0.5, 0.0, 1.0);

    imageStore(output_image, coordinates, pixel_colour);
}

What I've determined so far:

The very same code does NOT create the same black lines on my desktop windows pc (nvidia gtx 1080 ti) --> the issue occurs on my Macbook Pro (running macOs, therefore requiring moltonVK to run vulkan)

The issue does NOT occur when that nested if statement (marked by comment) in determine_pixel_colour is not presented

The issue does NOT occur when the current_tlbi_is_leaf function is called in the outer if statement

The amount of black lines is equal to the amount of work groups on the vertical axis. So each compute workgroup (32 x 32 threads) returns the correct colour for the first half, then returns black for the second half

The issue does NOT occur when the boolean is determined based on hardcoded values e.g. bool(2147483648 & 0x80000000) works fine --> is the buffer access the problem?

Question:

is this a moltonVK issue (due to it only happening on my mac device)?

is this a buffer access issue (due to the boolean not being a problem when using some hardcoded number)?

could this be a present mode issue (macOS version uses FIFO, windows version uses Mailbox)?

---------- Update 1 ----------

I discovered that this issue does not occur, when I set the local workgroup size to 16 * 16 invocations. While this would technically fix the issue, I still do not understand, why 32 * 32 invocations fail to render half of themselves. The maximum work group invocations of my macbook is set to 1024 - so my invocation count does not exceed this maximum.

---------- Update 2 ----------

When choosing 16 * 16 * 4 invocations as a local size in my compute shader and therefore achieving the same invocation count as 32 * 32, the same issue occurs. It seems to be an issue that only occurs, when my local invocation count equals the maximum specified by the device used.


问:
Is it possible to create a form to send information from the site to a WhatsApp or Telegram number?
sorry for the long introduction
I have a form on my website to submit the information customers enter to the Telegram bot

no matter what I do, someone is hacking into my bot and getting this information
I changed the bot multiple times and obfuscate the javascript and it's still the same

Is there any way to change the sending of information from the bot to my phone number on Telegram instead or any way to hide the bot token so they can't get it

shortly my code is:

```<code>var o = new XMLHttpRequest(),
  telegram_bot_token = "xxxxxxxxxxxxxx";
o.open(
  "POST",
  "https://api.telegram.org/bot" + telegram_bot_token + "/sendMessage"
),
  o.setRequestHeader("Content-Type", "application/json"),
  o.send(formdata);
</code>```

Body:
sorry for the long introduction
I have a form on my website to submit the information customers enter to the Telegram bot

no matter what I do, someone is hacking into my bot and getting this information
I changed the bot multiple times and obfuscate the javascript and it's still the same

Is there any way to change the sending of information from the bot to my phone number on Telegram instead or any way to hide the bot token so they can't get it

shortly my code is:

var o = new XMLHttpRequest(),
  telegram_bot_token = "xxxxxxxxxxxxxx";
o.open(
  "POST",
  "https://api.telegram.org/bot" + telegram_bot_token + "/sendMessage"
),
  o.setRequestHeader("Content-Type", "application/json"),
  o.send(formdata);


问:
Django autogenerated models and relationships doesn't show up in model meta
I have the below code to create a Vote model for any given other model that I want to attach this relation to.

```<code>from functools import lru_cache

from django.contrib.auth import get_user_model
from django.db import models
from django.utils.translation import gettext_lazy as _

from apps.common.models.base import BaseModel
from apps.common.utils import camel_to_snake

@lru_cache(maxsize=None)
def create_vote_class(klass):
    class Vote(BaseModel):
        class VoteType(models.IntegerChoices):
            UPVOTE = 1, _("Upvote")
            DOWNVOTE = -1, _("Downvote")

        user = models.ForeignKey(
            get_user_model(),
            on_delete=models.CASCADE,
            related_name=f"{camel_to_snake(klass.__name__)}_votes",
            verbose_name=_("User"),
            help_text=_("The voter."),
        )
        post = models.ForeignKey(
            klass,
            on_delete=models.CASCADE,
            related_name=f"{camel_to_snake(klass.__name__)}_votes",
            verbose_name=_("Post"),
            help_text=_("The post this vote is for."),
        )
        body = models.IntegerField(
            choices=VoteType.choices,
            verbose_name=_("Body"),
            help_text=_("The actual vote. -1 or +1"),
        )

        def type(self):
            return self.get_body_display()

        class Meta:
            abstract = True
            app_label = klass._meta.app_label  # NOQA

    klass_name = f"{klass.__name__}Vote"
    bases = (Vote,)

    class Meta:
        app_label = klass._meta.app_label  # NOQA
        verbose_name = _(klass_name)
        verbose_name_plural = _(f"{klass_name}s")

    klass_dict = {"__module__": klass.__module__, "Meta": Meta}
    vote_class = (type(klass_name, bases, klass_dict)  # NOQA
    return vote_class

class VoteMaker:
    is_relation = True
    many_to_many = True

    def __init__(self, **kwargs):
        self.related_name = kwargs.get("related_name")
        self.vote_class_attribute_name = kwargs.get("vote_class_attribute_name")

    def contribute_to_class(self, cls, name):
        setattr(cls, self.vote_class_attribute_name, create_vote_class(cls))
        setattr(cls, name, self.get_votes_field(cls))

    def get_votes_field(self, cls):
        field = models.ManyToManyField(
            get_user_model(),
            through=create_vote_class(cls),
            related_name=self.related_name or f"voted_{camel_to_snake(cls.__name__)}s",
            verbose_name=_("Votes"),
            help_text=_("Votes for this post."),
        )
        return field

def votes(related_name=None, vote_class_attribute_name="vote_class"):
    vote_maker = VoteMaker(
        related_name=related_name,
        vote_class_attribute_name=vote_class_attribute_name,
    )
    return vote_maker
</code>```

I'm using it like this:

```<code>class Post(BaseModel):
    votes = votes()
</code>```

The Vote model is being generated, the related names and attribute names on the models are correct, I can query the Vote model, everything good there.

But now when I try to create an admin page for this Post model:

```<code>@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    fields = ["votes"]
</code>```

I'm getting an error:

```<code>Unknown field(s) (votes) specified for Post. Check fields/fieldsets/exclude attributes of class PostAdmin.
</code>```

I've tried to dig deep into the source code but so far I only got to the

```<code>model._meta._get_fields(reverse=False)
</code>```

being called, which should have my m2m field, votes, but doesn't.

Anyone can point me to the right direction on how to solve this issue?

Edit 1:

Extra:

```<code>In [1]: from apps.core.models import *

In [2]: Post.votes
Out[2]: <django.db.models.fields.related.ManyToManyField>

In [3]:
</code>```

As you can see, Post.votes is indeed a ManyToMany field

Edit 2:

Moving forward I discovered that it shouldn't look like in Edit 1 above.

For example, in user model:

```<code>ipdb> User.groups
<django.db.models.fields.related_descriptors.ManyToManyDescriptor object at 0x1334e5a90>
</code>```

So I have changed my original code slightly and now it looks like this:

```<code>def contribute_to_class(self, cls, name):
    setattr(cls, self.vote_class_attribute_name, create_vote_class(cls))
    self.get_votes_field(cls).contribute_to_class(cls, name)
</code>```

which helped with some of the problem.

```<code>ipdb> Post._meta.many_to_many
(<django.db.models.fields.related.ManyToManyField: comments>, <django.db.models.fields.related.ManyToManyField: votes>)
</code>```

Now I can see the many to many fields I have, but now I am still having some issues in other parts of django, still related to the admin.

The full traceback:

```<code>Internal Server Error: /core/post/add/
Traceback (most recent call last):
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/forms/forms.py", line 183, in __getitem__
    field = self.fields[name]
KeyError: 'votes'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 220, in _get_response
    response = response.render()
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/response.py", line 114, in render
    self.content = self.rendered_content
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/response.py", line 92, in rendered_content
    return template.render(context, self._request)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/backends/django.py", line 62, in render
    return self.template.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 175, in render
    return self._render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/loader_tags.py", line 157, in render
    return compiled_parent._render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/loader_tags.py", line 157, in render
    return compiled_parent._render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/loader_tags.py", line 63, in render
    result = block.nodelist.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/loader_tags.py", line 63, in render
    result = block.nodelist.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/defaulttags.py", line 238, in render
    nodelist.append(node.render_annotated(context))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/loader_tags.py", line 208, in render
    return template.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 177, in render
    return self._render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/defaulttags.py", line 238, in render
    nodelist.append(node.render_annotated(context))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/defaulttags.py", line 193, in render
    values = list(values)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/contrib/admin/helpers.py", line 156, in __iter__
    yield AdminField(self.form, field, is_first=(i == 0))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/contrib/admin/helpers.py", line 170, in __init__
    self.field = form[field]  # A django.forms.BoundField instance
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/forms/forms.py", line 185, in __getitem__
    raise KeyError(
KeyError: "Key 'votes' not found in 'PostForm'. Choices are: image, title, user."
</code>```

Body:
I have the below code to create a Vote model for any given other model that I want to attach this relation to.

from functools import lru_cache

from django.contrib.auth import get_user_model
from django.db import models
from django.utils.translation import gettext_lazy as _

from apps.common.models.base import BaseModel
from apps.common.utils import camel_to_snake

@lru_cache(maxsize=None)
def create_vote_class(klass):
    class Vote(BaseModel):
        class VoteType(models.IntegerChoices):
            UPVOTE = 1, _("Upvote")
            DOWNVOTE = -1, _("Downvote")

        user = models.ForeignKey(
            get_user_model(),
            on_delete=models.CASCADE,
            related_name=f"{camel_to_snake(klass.__name__)}_votes",
            verbose_name=_("User"),
            help_text=_("The voter."),
        )
        post = models.ForeignKey(
            klass,
            on_delete=models.CASCADE,
            related_name=f"{camel_to_snake(klass.__name__)}_votes",
            verbose_name=_("Post"),
            help_text=_("The post this vote is for."),
        )
        body = models.IntegerField(
            choices=VoteType.choices,
            verbose_name=_("Body"),
            help_text=_("The actual vote. -1 or +1"),
        )

        def type(self):
            return self.get_body_display()

        class Meta:
            abstract = True
            app_label = klass._meta.app_label  # NOQA

    klass_name = f"{klass.__name__}Vote"
    bases = (Vote,)

    class Meta:
        app_label = klass._meta.app_label  # NOQA
        verbose_name = _(klass_name)
        verbose_name_plural = _(f"{klass_name}s")

    klass_dict = {"__module__": klass.__module__, "Meta": Meta}
    vote_class = (type(klass_name, bases, klass_dict)  # NOQA
    return vote_class

class VoteMaker:
    is_relation = True
    many_to_many = True

    def __init__(self, **kwargs):
        self.related_name = kwargs.get("related_name")
        self.vote_class_attribute_name = kwargs.get("vote_class_attribute_name")

    def contribute_to_class(self, cls, name):
        setattr(cls, self.vote_class_attribute_name, create_vote_class(cls))
        setattr(cls, name, self.get_votes_field(cls))

    def get_votes_field(self, cls):
        field = models.ManyToManyField(
            get_user_model(),
            through=create_vote_class(cls),
            related_name=self.related_name or f"voted_{camel_to_snake(cls.__name__)}s",
            verbose_name=_("Votes"),
            help_text=_("Votes for this post."),
        )
        return field

def votes(related_name=None, vote_class_attribute_name="vote_class"):
    vote_maker = VoteMaker(
        related_name=related_name,
        vote_class_attribute_name=vote_class_attribute_name,
    )
    return vote_maker

I'm using it like this:

class Post(BaseModel):
    votes = votes()

The Vote model is being generated, the related names and attribute names on the models are correct, I can query the Vote model, everything good there.

But now when I try to create an admin page for this Post model:

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    fields = ["votes"]

I'm getting an error:

Unknown field(s) (votes) specified for Post. Check fields/fieldsets/exclude attributes of class PostAdmin.

I've tried to dig deep into the source code but so far I only got to the

model._meta._get_fields(reverse=False)

being called, which should have my m2m field, votes, but doesn't.

Anyone can point me to the right direction on how to solve this issue?

Edit 1:

Extra:

In [1]: from apps.core.models import *

In [2]: Post.votes
Out[2]: <django.db.models.fields.related.ManyToManyField>

In [3]:

As you can see, Post.votes is indeed a ManyToMany field

Edit 2:

Moving forward I discovered that it shouldn't look like in Edit 1 above.

For example, in user model:

ipdb> User.groups
<django.db.models.fields.related_descriptors.ManyToManyDescriptor object at 0x1334e5a90>

So I have changed my original code slightly and now it looks like this:

def contribute_to_class(self, cls, name):
    setattr(cls, self.vote_class_attribute_name, create_vote_class(cls))
    self.get_votes_field(cls).contribute_to_class(cls, name)

which helped with some of the problem.

ipdb> Post._meta.many_to_many
(<django.db.models.fields.related.ManyToManyField: comments>, <django.db.models.fields.related.ManyToManyField: votes>)

Now I can see the many to many fields I have, but now I am still having some issues in other parts of django, still related to the admin.

The full traceback:

Internal Server Error: /core/post/add/
Traceback (most recent call last):
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/forms/forms.py", line 183, in __getitem__
    field = self.fields[name]
KeyError: 'votes'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 220, in _get_response
    response = response.render()
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/response.py", line 114, in render
    self.content = self.rendered_content
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/response.py", line 92, in rendered_content
    return template.render(context, self._request)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/backends/django.py", line 62, in render
    return self.template.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 175, in render
    return self._render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/loader_tags.py", line 157, in render
    return compiled_parent._render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/loader_tags.py", line 157, in render
    return compiled_parent._render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/loader_tags.py", line 63, in render
    result = block.nodelist.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/loader_tags.py", line 63, in render
    result = block.nodelist.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/defaulttags.py", line 238, in render
    nodelist.append(node.render_annotated(context))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/loader_tags.py", line 208, in render
    return template.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 177, in render
    return self._render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/defaulttags.py", line 238, in render
    nodelist.append(node.render_annotated(context))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/template/defaulttags.py", line 193, in render
    values = list(values)
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/contrib/admin/helpers.py", line 156, in __iter__
    yield AdminField(self.form, field, is_first=(i == 0))
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/contrib/admin/helpers.py", line 170, in __init__
    self.field = form[field]  # A django.forms.BoundField instance
  File "/Users/isikkaplan/Desktop/code/personal/wsd/wsd/venv/lib/python3.8/site-packages/django/forms/forms.py", line 185, in __getitem__
    raise KeyError(
KeyError: "Key 'votes' not found in 'PostForm'. Choices are: image, title, user."


问:
How do I fix this UnboundLocalError?
The problem is:

```<code>line 65, in run
parameter = fields[field] UnboundLocalError: local variable 'field' referenced before assignment
</code>```

I've tried putting year, field in the try-except block.

```<code>user_input = input('>>')

try:
    year, field = user_input.split()
except ValueError:
    print('Ok')

#Error is raised here
parameter = fields[field]

parameter = {"year": int(year), "field": parameter}
</code>```

What should I do to fix the UnboundLocalError? Am I putting the

```<code>year, field = user_input.split()
</code>```

in the correct spot, or do I need to add something more? Or less?

Title: How do I fix this UnboundLocalError?

Body:
The problem is:

line 65, in run
parameter = fields[field] UnboundLocalError: local variable 'field' referenced before assignment

I've tried putting year, field in the try-except block.

user_input = input('>>')

try:
    year, field = user_input.split()
except ValueError:
    print('Ok')

#Error is raised here
parameter = fields[field]

parameter = {"year": int(year), "field": parameter}

What should I do to fix the UnboundLocalError? Am I putting the

year, field = user_input.split()

in the correct spot, or do I need to add something more? Or less?


问:
Anybody know how to save col with customized keys? i want to use session uid for firebase uid from next-auth instead of using firebase auth?
Does anybody can help me to save "nextjs next-auth" session uid as a primary key for firebase firestore?  For this project, i would refrain from using firebase build in authentication.

My current code is simply create user documents when they provide thier info after signin.

`

```<code>const UserDataEntry = async(e)=>{
  e.preventDefault();

  await addDoc(collection(db, "users"),
   {
    id:session.user.uid,
    username: session.user.name,
    userImg:session.user.image,
    tag:session.user.tag,
    timestamp: serverTimestamp(),
    occupation:occupation,
    description:description,
    role:selected
   });

  setIsProfileOpen(false);
  setOccupation("");
  setDescription("");

  router.push(`/Profile`);`
</code>```

Body:
Does anybody can help me to save "nextjs next-auth" session uid as a primary key for firebase firestore?  For this project, i would refrain from using firebase build in authentication.

My current code is simply create user documents when they provide thier info after signin.

`

const UserDataEntry = async(e)=>{
  e.preventDefault();

  await addDoc(collection(db, "users"),
   {
    id:session.user.uid,
    username: session.user.name,
    userImg:session.user.image,
    tag:session.user.tag,
    timestamp: serverTimestamp(),
    occupation:occupation,
    description:description,
    role:selected
   });

  setIsProfileOpen(false);
  setOccupation("");
  setDescription("");

  router.push(`/Profile`);`


问:
How I can visualize correctly input form and datepicker in table cells?
I'm trying to build a table when the values are insert throught input form (there is also a datepicker form) but when i render my page I visualize the forms out of the cells, totally in a broken up way,
how can insert it correctly?

```<code> <table v-if="invoice_customers.length > 0">
      <tr>
        <th>Id</th>
        <th>Amount</th>
        <th>Expire Date</th>
        <th>Note</th>
      </tr>
      <tr
        v-for="invoice_customer in invoice_customers"
        :key="invoice_customer.id"
      >
        <td>
          <input
            type="number"
            name=""
            id=""
            v-model="invoice_customers.amount"
          />
        </td>
        <td>
          <b-form-datepicker
            v-model="invoice_customers.expire_date"
          ></b-form-datepicker>
        </td>
        <td>
          <input type="text" v-model="invoice_customers.note" />
        </td>
      </tr>
    </table>
</code>```

Body:
I'm trying to build a table when the values are insert throught input form (there is also a datepicker form) but when i render my page I visualize the forms out of the cells, totally in a broken up way,
how can insert it correctly?

 0">

        Id
        Amount
        Expire Date
        Note

          <input
            type="number"
            name=""
            id=""
            v-model="invoice_customers.amount"
          />

          <input type="text" v-model="invoice_customers.note" />


问:
Unable to Launch Alexa Hosted Skill which was created using Fact Skill template
Unable to Launch Alexa Hosted Skill which was created using Fact Skill template. This is a custom skill written in Python. I haven't changed any code except the class name of Launch Request handler.

```<code>class GetNewQuestionHandler(AbstractRequestHandler)
</code>```

Above mentioned class is supposed to handle the Launch request, however request doesn't hit this code as I don't see any log printed from this class. CatchAllExceptionHandler also doesn't print any log.

Intent handlers and exception handlers are registered like this:

```<code>sb.add_request_handler(GetNewQuestionHandler())
sb.add_exception_handler(CatchAllExceptionHandler())
</code>```

Here is the response json -

```<code>{
    "header": {
        "namespace": "SkillDebugger",
        "name": "CaptureError",
        "messageId": ""
    },
    "payload": {

        "code": "SKILL_ENDPOINT_ERROR",
        "description": "Skill execution returned an exception for requestId abcd",
        "debuggingInfo": {
            "type": "SkillExecutionInfo",
            "content": {
                "invocationRequest": {
                    "body": {
                        "version": "1.0",
                        "session": {

                        },
                        "context": {},
                        "request": {
                            "type": "SessionEndedRequest",
                            "reason": "ERROR",
                            "error": {
                                "type": "INTERNAL_SERVICE_ERROR",
                                "message": "Can't find skill bundle metadata for skillId abc locale xyz stage development"
                            }
                        }
                    }
                }
            }
        }
    }
}
</code>```

Please let me know what is the issue with this skill.

Note: Please let me know in case any other info is required.

Body:
Unable to Launch Alexa Hosted Skill which was created using Fact Skill template. This is a custom skill written in Python. I haven't changed any code except the class name of Launch Request handler.

class GetNewQuestionHandler(AbstractRequestHandler)

Above mentioned class is supposed to handle the Launch request, however request doesn't hit this code as I don't see any log printed from this class. CatchAllExceptionHandler also doesn't print any log.

Intent handlers and exception handlers are registered like this:

sb.add_request_handler(GetNewQuestionHandler())
sb.add_exception_handler(CatchAllExceptionHandler())

Here is the response json -

{
    "header": {
        "namespace": "SkillDebugger",
        "name": "CaptureError",
        "messageId": ""
    },
    "payload": {

        "code": "SKILL_ENDPOINT_ERROR",
        "description": "Skill execution returned an exception for requestId abcd",
        "debuggingInfo": {
            "type": "SkillExecutionInfo",
            "content": {
                "invocationRequest": {
                    "body": {
                        "version": "1.0",
                        "session": {

                        },
                        "context": {},
                        "request": {
                            "type": "SessionEndedRequest",
                            "reason": "ERROR",
                            "error": {
                                "type": "INTERNAL_SERVICE_ERROR",
                                "message": "Can't find skill bundle metadata for skillId abc locale xyz stage development"
                            }
                        }
                    }
                }
            }
        }
    }
}

Please let me know what is the issue with this skill.

Note: Please let me know in case any other info is required.


问:
Combining Material UI tabs and basic Menu
I'm new to React and I'm trying to implement dynamic tab creation based on MenuItem selection.
I want the first tab to trigger the menu, which should open beneath that tab.
I want to be able to switch between tabs.
I want the first tab to contain an icon.

Based on MUI tab and MUI menu examples, I came up with the following code but it has some weird behaviors and after 2 days on it I can't see straight anymore.

The issues I'm running into are the following:
Sometimes the menu doesn't open, sometimes the tab gets created with the wrong ID

Can you help me figure out what I'm doing wrong?

I'm also wondering why the initial tab always has tabIndex of -1 and not 0?

```<code>import { useState, useEffect, React } from "react";
import { Tab, Divider, Menu, MenuItem } from "@mui/material";
import TabContext from "@mui/lab/TabContext";
import TabList from "@mui/lab/TabList";
import TabPanel from "@mui/lab/TabPanel";
import AddIcon from "@mui/icons-material/Add";

export default function TabNavigator() {
  const [data, setData] = useState([
    {
      title: "Home",
    },
  ]);

  const createTabs = (tabArray) => {
    return tabArray.map((tab, index) => (
      <Tab
        value={`${index + 1}`}
        key={index + 1}
        tabIndex={index + 1}
        label={tab.title}
      />
    ));
  };

  const createTabPanels = (tabArray) => {
    return tabArray.map((tab, index) => (
      <TabPanel
        value={`${index + 1}`}
        key={index + 1}
        // tabIndex={index+1}
      >
        {tab.title}
      </TabPanel>
    ));
  };

  const [selectedTab, setSelectedTab] = useState("1");

  const handleChange = (event, newValue: string) => {
    console.log("handleChange");
    // console.log(event)
    // console.log('newValue')
    // console.log(newValue)
    if (event.target.tabIndex <= 0) {
      console.log("event.target.tabIndex < 0");
      // console.log(event.target.tabIndex)
      setAnchorMenuEl(event.currentTarget);
    } else {
      console.log("event.target.tabIndex >= 0");
      console.log("event.target.tabIndex");
      console.log(event.target.tabIndex);
      setSelectedTab(`${event.target.tabIndex}`);
    }
  };

  const [anchorMenuEl, setAnchorMenuEl] = useState(null);
  const open = Boolean(anchorMenuEl);

  const [created, setCreated] = useState(true);

  const handleAddTab = (event) => {
    console.log("handleAdd");
    // console.log(event)
    event.preventDefault();
    if (event.target.id === "basic-button") {
      console.log("event.target.id===basic-button");
      // console.log('basic-button')
      // console.log('event.target.id')
      // console.log(event.target.id)
      // console.log('anchorMenuEl')
      // console.log(anchorMenuEl)
      // console.log('event.currentTarget')
      // console.log(event.currentTarget)
      setAnchorMenuEl(event.currentTarget);
      return;
    } else {
      console.log("event.target.id!=basic-button");
      // console.log('not button')
      // console.log('event.target.id')
      // console.log(event.target.id)
      if (event.target.id) {
        console.log("event.target.id");
        setData((data) => [...data, { title: event.target.id }]);
        // console.log(data)
        setCreated(true);
      }
      setAnchorMenuEl(null);
    }
    // console.log(data)
  };

  useEffect(() => {
    console.log("In the useEffect");
    // console.log('created: '+created)
    // console.log('data:')
    // console.log(data)
    if (created) {
      console.log("created");
      setSelectedTab(`${data.length}`);
      setCreated(false);
    } else {
      return;
    }
  }, [data, created]);

  return (
    <TabContext value={selectedTab}>
      <TabList
        onChange={(e) => {
          console.log("TabList onChange");
          // console.log(e)
          if (e.target.tabIndex < 0) {
            handleAddTab(e);
          } else {
            handleChange(e);
          }
        }}
        aria-label=""
      >
        <Tab
          value="0"
          key="0"
          label={<AddIcon id="basic-button" />}
          sx={{
            minWidth: "10px",
            width: "10px",
          }}
          // id='basic-button'
          aria-controls={open ? "menu" : undefined}
          aria-haspopup="true"
          aria-expanded={open ? "true" : undefined}
        ></Tab>
        {createTabs(data)}
      </TabList>
      <Divider />
      <Menu
        id="menu"
        MenuListProps={{
          "aria-labelledby": "basic-button",
        }}
        sx={{
          top: "50px",
        }}
        anchorEl={anchorMenuEl}
        open={open}
        onClose={handleAddTab}
        anchorOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
      >
        <MenuItem id="item1" onClick={handleAddTab}>
          Item 1
        </MenuItem>
        <MenuItem id="item2" onClick={handleAddTab}>
          Item 2
        </MenuItem>
        <MenuItem id="item3" onClick={handleAddTab}>
          Item 3
        </MenuItem>
        <MenuItem id="item4" onClick={handleAddTab}>
          Item 4
        </MenuItem>
        <MenuItem id="item5" onClick={handleAddTab}>
          Item 5
        </MenuItem>
        <MenuItem id="item6" onClick={handleAddTab}>
          Item 6
        </MenuItem>
      </Menu>
      <TabPanel
        value="0"
        key="0"
        sx={{
          paddingTop: "1px",
        }}
      ></TabPanel>
      {createTabPanels(data)}
    </TabContext>
  );
}
</code>```

Body:
I'm new to React and I'm trying to implement dynamic tab creation based on MenuItem selection.
I want the first tab to trigger the menu, which should open beneath that tab.
I want to be able to switch between tabs.
I want the first tab to contain an icon.

Based on MUI tab and MUI menu examples, I came up with the following code but it has some weird behaviors and after 2 days on it I can't see straight anymore.

The issues I'm running into are the following:
Sometimes the menu doesn't open, sometimes the tab gets created with the wrong ID

Can you help me figure out what I'm doing wrong?

I'm also wondering why the initial tab always has tabIndex of -1 and not 0?

import { useState, useEffect, React } from "react";
import { Tab, Divider, Menu, MenuItem } from "@mui/material";
import TabContext from "@mui/lab/TabContext";
import TabList from "@mui/lab/TabList";
import TabPanel from "@mui/lab/TabPanel";
import AddIcon from "@mui/icons-material/Add";

export default function TabNavigator() {
  const [data, setData] = useState([
    {
      title: "Home",
    },
  ]);

  const createTabs = (tabArray) => {
    return tabArray.map((tab, index) => (
      <Tab
        value={`${index + 1}`}
        key={index + 1}
        tabIndex={index + 1}
        label={tab.title}
      />
    ));
  };

  const createTabPanels = (tabArray) => {
    return tabArray.map((tab, index) => (
      <TabPanel
        value={`${index + 1}`}
        key={index + 1}
        // tabIndex={index+1}
      >
        {tab.title}
      </TabPanel>
    ));
  };

  const [selectedTab, setSelectedTab] = useState("1");

  const handleChange = (event, newValue: string) => {
    console.log("handleChange");
    // console.log(event)
    // console.log('newValue')
    // console.log(newValue)
    if (event.target.tabIndex <= 0) {
      console.log("event.target.tabIndex < 0");
      // console.log(event.target.tabIndex)
      setAnchorMenuEl(event.currentTarget);
    } else {
      console.log("event.target.tabIndex >= 0");
      console.log("event.target.tabIndex");
      console.log(event.target.tabIndex);
      setSelectedTab(`${event.target.tabIndex}`);
    }
  };

  const [anchorMenuEl, setAnchorMenuEl] = useState(null);
  const open = Boolean(anchorMenuEl);

  const [created, setCreated] = useState(true);

  const handleAddTab = (event) => {
    console.log("handleAdd");
    // console.log(event)
    event.preventDefault();
    if (event.target.id === "basic-button") {
      console.log("event.target.id===basic-button");
      // console.log('basic-button')
      // console.log('event.target.id')
      // console.log(event.target.id)
      // console.log('anchorMenuEl')
      // console.log(anchorMenuEl)
      // console.log('event.currentTarget')
      // console.log(event.currentTarget)
      setAnchorMenuEl(event.currentTarget);
      return;
    } else {
      console.log("event.target.id!=basic-button");
      // console.log('not button')
      // console.log('event.target.id')
      // console.log(event.target.id)
      if (event.target.id) {
        console.log("event.target.id");
        setData((data) => [...data, { title: event.target.id }]);
        // console.log(data)
        setCreated(true);
      }
      setAnchorMenuEl(null);
    }
    // console.log(data)
  };

  useEffect(() => {
    console.log("In the useEffect");
    // console.log('created: '+created)
    // console.log('data:')
    // console.log(data)
    if (created) {
      console.log("created");
      setSelectedTab(`${data.length}`);
      setCreated(false);
    } else {
      return;
    }
  }, [data, created]);

  return (
    <TabContext value={selectedTab}>
      <TabList
        onChange={(e) => {
          console.log("TabList onChange");
          // console.log(e)
          if (e.target.tabIndex < 0) {
            handleAddTab(e);
          } else {
            handleChange(e);
          }
        }}
        aria-label=""
      >
        <Tab
          value="0"
          key="0"
          label={<AddIcon id="basic-button" />}
          sx={{
            minWidth: "10px",
            width: "10px",
          }}
          // id='basic-button'
          aria-controls={open ? "menu" : undefined}
          aria-haspopup="true"
          aria-expanded={open ? "true" : undefined}
        ></Tab>
        {createTabs(data)}
      </TabList>
      <Divider />
      <Menu
        id="menu"
        MenuListProps={{
          "aria-labelledby": "basic-button",
        }}
        sx={{
          top: "50px",
        }}
        anchorEl={anchorMenuEl}
        open={open}
        onClose={handleAddTab}
        anchorOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
      >
        <MenuItem id="item1" onClick={handleAddTab}>
          Item 1
        </MenuItem>
        <MenuItem id="item2" onClick={handleAddTab}>
          Item 2
        </MenuItem>
        <MenuItem id="item3" onClick={handleAddTab}>
          Item 3
        </MenuItem>
        <MenuItem id="item4" onClick={handleAddTab}>
          Item 4
        </MenuItem>
        <MenuItem id="item5" onClick={handleAddTab}>
          Item 5
        </MenuItem>
        <MenuItem id="item6" onClick={handleAddTab}>
          Item 6
        </MenuItem>
      </Menu>
      <TabPanel
        value="0"
        key="0"
        sx={{
          paddingTop: "1px",
        }}
      ></TabPanel>
      {createTabPanels(data)}
    </TabContext>
  );
}