问:
FastAPI + SQLModel Distinguishing Unset from Null (None) query parameters
I am playing around with using pydantic/SQLModels to specify query parameters for FastAPI endpoints. The model would have all optional types, and then get passed the endpoint using query_params:QuerySchema=Depends(QuerySchema). This works fine but I am having issues distinguishing between values that are unset and values that the user has explicitly set to None as to query for Null values.

I have tried using .dict(exclude_unset==True) model but it seems FastAPI is doing some magic behind the scenes to set optional params to None which means exclude_unset doesn't exclude anything from the returned dictionary.

Anyone have and ideas on how to approach this? I've include an example of what I'm trying below.

crud/base.py

```<code>import logging
from datetime import datetime
from typing import Any, Callable, Generic, Optional, TypeVar, Union
from uuid import UUID

from app.models.base_models import _SQLModel
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from sqlmodel import SQLModel, select
from sqlmodel.ext.asyncio.session import AsyncSession
from sqlmodel.sql.expression import Select

ModelType = TypeVar("ModelType", bound=_SQLModel)
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)
# SchemaType = TypeVar("SchemaType", bound=BaseModel)
T = TypeVar("T", bound=SQLModel)

IdType = Union[str, UUID, int]

class SessionNotFoundException(BaseException):
    ...

class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
    def __init__(
        self,
        model: type[ModelType],
        session_factory: Optional[Callable[[], AsyncSession]] = None,
    ) -> None:
        self.model: type[ModelType] = model
        self.session_factory = session_factory
        self._logger = logging.getLogger(str(self.model.__tablename__))

    @property
    def _local_session(self) -> AsyncSession:
        if not self.session_factory:
            raise SessionNotFoundException(
                "No session provided or session_factory initialized."
            )
        return self.session_factory()

    ### OMITTED FOR LENGTH

    async def get_multi(
        self,
        *,
        offset: int = 0,
        limit: Optional[int] = 100,
        query: Optional[Select[T]] = None,
        db_session: Optional[AsyncSession] = None,
    ) -> list[ModelType]:

        session = db_session or self._local_session
        statement = query if query is not None else select(self.model)

        statement = (
            statement.offset(offset).limit(limit).order_by(self.model.created_at)
        )
        response = await session.execute(statement)
        return response.scalars().all()

### OMITTED FOR LENGTH

</code>```

Usage example. This doesn't work. I think because FastAPI is setting unset optional params to none, so the exclude unset option doesn't exclude anything.

crud/sports_crud.py

```<code>from typing import Optional, Union

from app.models import Sport
from app.schemas.sports import ISportCreate, ISportUpdate
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession
from app.db.session import SessionLocal
from .base import CRUDBase, IdType

class CRUDSports(CRUDBase[Sport, ISportCreate, ISportUpdate]):
    ...

sports = CRUDSports(Sport, session_factory=SessionLocal)
</code>```

router

```<code>@sports_router_v1.get("", response_model=list[ISportRead])
async def get_sports(
    *,
    query_params: ISportQuery = Depends(ISportQuery),
    page_params: PageParams = Depends(PageParams),
) -> list[Sport]:
    # Get explicitly set query params
    query = query_params.dict(exclude_unset=True) # debugger shows this includes all keys with None values

    # build select query
    stmt = select(Sport)
    if query != {}:
        for k, v in query.items():
            stmt = stmt.where(getattr(Sport, k) == v)

    sports = await crud.sports.get_multi(query=stmt, **page_params.dict())
    return sports

</code>```

schemas/sports.py

```<code>def optional(*fields):
    # https://github.com/pydantic/pydantic/issues/1223
    # https://github.com/pydantic/pydantic/pull/3179

    def dec(_cls):
        for field in fields:
            _cls.__fields__[field].required = False
        return _cls

    if fields and inspect.isclass(fields[0]) and issubclass(fields[0], BaseModel):
        cls = fields[0]
        fields = cls.__fields__
        return dec(cls)
    return dec

class ISportRead(SportBase):
    id: UUID

@optional
class ISportQuery(ISportRead):
    ...

</code>```

Body:
I am playing around with using pydantic/SQLModels to specify query parameters for FastAPI endpoints. The model would have all optional types, and then get passed the endpoint using query_params:QuerySchema=Depends(QuerySchema). This works fine but I am having issues distinguishing between values that are unset and values that the user has explicitly set to None as to query for Null values.

I have tried using .dict(exclude_unset==True) model but it seems FastAPI is doing some magic behind the scenes to set optional params to None which means exclude_unset doesn't exclude anything from the returned dictionary.

Anyone have and ideas on how to approach this? I've include an example of what I'm trying below.

crud/base.py

import logging
from datetime import datetime
from typing import Any, Callable, Generic, Optional, TypeVar, Union
from uuid import UUID

from app.models.base_models import _SQLModel
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from sqlmodel import SQLModel, select
from sqlmodel.ext.asyncio.session import AsyncSession
from sqlmodel.sql.expression import Select

ModelType = TypeVar("ModelType", bound=_SQLModel)
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)
# SchemaType = TypeVar("SchemaType", bound=BaseModel)
T = TypeVar("T", bound=SQLModel)

IdType = Union[str, UUID, int]

class SessionNotFoundException(BaseException):
    ...

class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
    def __init__(
        self,
        model: type[ModelType],
        session_factory: Optional[Callable[[], AsyncSession]] = None,
    ) -> None:
        self.model: type[ModelType] = model
        self.session_factory = session_factory
        self._logger = logging.getLogger(str(self.model.__tablename__))

    @property
    def _local_session(self) -> AsyncSession:
        if not self.session_factory:
            raise SessionNotFoundException(
                "No session provided or session_factory initialized."
            )
        return self.session_factory()

    ### OMITTED FOR LENGTH

    async def get_multi(
        self,
        *,
        offset: int = 0,
        limit: Optional[int] = 100,
        query: Optional[Select[T]] = None,
        db_session: Optional[AsyncSession] = None,
    ) -> list[ModelType]:

        session = db_session or self._local_session
        statement = query if query is not None else select(self.model)

        statement = (
            statement.offset(offset).limit(limit).order_by(self.model.created_at)
        )
        response = await session.execute(statement)
        return response.scalars().all()

### OMITTED FOR LENGTH

Usage example. This doesn't work. I think because FastAPI is setting unset optional params to none, so the exclude unset option doesn't exclude anything.

crud/sports_crud.py

from typing import Optional, Union

from app.models import Sport
from app.schemas.sports import ISportCreate, ISportUpdate
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession
from app.db.session import SessionLocal
from .base import CRUDBase, IdType

class CRUDSports(CRUDBase[Sport, ISportCreate, ISportUpdate]):
    ...

sports = CRUDSports(Sport, session_factory=SessionLocal)

router

@sports_router_v1.get("", response_model=list[ISportRead])
async def get_sports(
    *,
    query_params: ISportQuery = Depends(ISportQuery),
    page_params: PageParams = Depends(PageParams),
) -> list[Sport]:
    # Get explicitly set query params
    query = query_params.dict(exclude_unset=True) # debugger shows this includes all keys with None values

    # build select query
    stmt = select(Sport)
    if query != {}:
        for k, v in query.items():
            stmt = stmt.where(getattr(Sport, k) == v)

    sports = await crud.sports.get_multi(query=stmt, **page_params.dict())
    return sports

schemas/sports.py

def optional(*fields):
    # https://github.com/pydantic/pydantic/issues/1223
    # https://github.com/pydantic/pydantic/pull/3179

    def dec(_cls):
        for field in fields:
            _cls.__fields__[field].required = False
        return _cls

    if fields and inspect.isclass(fields[0]) and issubclass(fields[0], BaseModel):
        cls = fields[0]
        fields = cls.__fields__
        return dec(cls)
    return dec

class ISportRead(SportBase):
    id: UUID

@optional
class ISportQuery(ISportRead):
    ...


来源: stackexchange

问:
How to get the value of Location Header Response in Angular
I am trying to get the value of Header Response enter image description here"Location" after a post 201 method, I want to get that result and send it as a variable to another api post

```<code>public saveNote(note: any): Observable\<any\> {
return this.http.post\<any\>(
this.apiURL + '/contract/api/notes/' + Location,
JSON.stringify(note),
this.httpOptions,
)
.pipe(retry(1), catchError(this.handleError));
}
</code>```

How can I do it? I'm already lost
thanks for your help

In Contractadd.ts

```<code>return this.restApi.post(this.contract, body, options)
        .flatMap((res:Response) => {
          var location = res.headers.get('Location');
          return this._http.get(location);
        }).map((res:Response) => res.json()))
        .catch(this.handleError)
</code>```

Get errors in code TS

In service.ts

```<code>Access-Control-Allow-Headers:location
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to get the value of Header Response enter image description here"Location" after a post 201 method, I want to get that result and send it as a variable to another api post

public saveNote(note: any): Observable\<any\> {
return this.http.post\<any\>(
this.apiURL + '/contract/api/notes/' + Location,
JSON.stringify(note),
this.httpOptions,
)
.pipe(retry(1), catchError(this.handleError));
}

How can I do it? I'm already lost
thanks for your help

In Contractadd.ts

return this.restApi.post(this.contract, body, options)
        .flatMap((res:Response) => {
          var location = res.headers.get('Location');
          return this._http.get(location);
        }).map((res:Response) => res.json()))
        .catch(this.handleError)

Get errors in code TS

In service.ts

Access-Control-Allow-Headers:location


问:
How to specify that carrier supports or not supports IKEv2 Mobility and Multihoming Protocol (MOBIKE) in Android programmatically?
I am implementing a carrier app (https://source.android.com/docs/core/connect/uicc), that should make configurations for operators.

Currently, there is need to configure whether carrier supports or not supports IKEv2 Mobility and Multihoming Protocol (MOBIKE) on Android phone (programmatically).

I have tried to find such configuration, but could not find any API in Android that would suit the need. Usually such configurations appear in CarrierConfigManager configuration keys (https://developer.android.com/reference/android/telephony/CarrierConfigManager), but there seems to be none for MOBIKE.


问:
How to kill running "invisible" containers?
I installed docker using snap (during the install process of 22.04) and it was working fine, and all my containers were spun up using docker run ...

This was until I installed docker-compose using apt later on. When I attempted to bring up containers with docker-compose I would get errors stating that the port was already in use.

So I then checked what program/command was using these ports:

```<code>sudo lsof -i :9091:
COMMAND    PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
docker-pr 1883 root    4u  IPv4  28696      0t0  TCP *:9091 (LISTEN)
docker-pr 1890 root    4u  IPv6  27395      0t0  TCP *:9091 (LISTEN)
</code>```
```<code>sudo netstat -pna | grep 9091
tcp        0      0 0.0.0.0:9091            0.0.0.0:*               LISTEN      1883/docker-proxy
tcp6       0      0 :::9091                 :::*                    LISTEN      1890/docker-proxy
</code>```

This showed that my container was still somehow running, as the port was in use. However, when running docker ps -a no containers were running...

The commands above all pointed towards docker-proxy, what is this service? Also, why is it so under the radar that docker itself can't even stop the container with commands like: docker rm $(docker ps -aq)? Also, not sure why my container became invisible and was unable to stop it without stopping the docker service entirely.

Body:
I installed docker using snap (during the install process of 22.04) and it was working fine, and all my containers were spun up using docker run ...

This was until I installed docker-compose using apt later on. When I attempted to bring up containers with docker-compose I would get errors stating that the port was already in use.

So I then checked what program/command was using these ports:

sudo lsof -i :9091:
COMMAND    PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
docker-pr 1883 root    4u  IPv4  28696      0t0  TCP *:9091 (LISTEN)
docker-pr 1890 root    4u  IPv6  27395      0t0  TCP *:9091 (LISTEN)

sudo netstat -pna | grep 9091
tcp        0      0 0.0.0.0:9091            0.0.0.0:*               LISTEN      1883/docker-proxy
tcp6       0      0 :::9091                 :::*                    LISTEN      1890/docker-proxy

This showed that my container was still somehow running, as the port was in use. However, when running docker ps -a no containers were running...

The commands above all pointed towards docker-proxy, what is this service? Also, why is it so under the radar that docker itself can't even stop the container with commands like: docker rm $(docker ps -aq)? Also, not sure why my container became invisible and was unable to stop it without stopping the docker service entirely.


问:
Calling private method in debug mode inside the class
I came across a question about Python debugger when working with pandas inside a class. In short, I could not call the "private method" in the debug console with its original(unmangled) method name.

A sample code would be as follows:

import pandas as pd

class Foo:
    def __init__(self):
        self.df = pd.DataFrame({'a':[1,1,2,2,3,3],'b':[4,5,6,7,8,9]})
    def __private_method(self,df):
        df['c'] = df['b'] + df['a']
        return df
    def public_method(self):
        new_df = self.df.groupby('a').apply(self.__private_method)
        print(new_df)

foo = Foo()
foo.public_method()
```
<p>The code runs well as a script, either directly running it or with debugger. However, when I add a breakpoint in line 10:<code>new_df = self.df.groupby('a').apply(self.__private_method)</code>, start debugging and stop there, and run this line of code in the debug console, I would see the following exception:</p>
```Traceback (most recent call last):
  File "<string>", line 1, in <module>
AttributeError: 'Foo' object has no attribute '__private_method'
```

However, in the debug console, if I simply put self.__private_method, it seems to be able to find the method in the namespace and returns <bound method Foo.__private_method of <__main__.Foo object at 0x000002011DCA6790>>.

Lastly, I could run self.df.groupby('a').apply(self._Foo__private_method) in the debug console and get no error.

Could anyone help me understand what is going on when I pause in the debug mode and why I could visit self.__private_method but unable to call it? Thank you!

Body:
I came across a question about Python debugger when working with pandas inside a class. In short, I could not call the "private method" in the debug console with its original(unmangled) method name.

A sample code would be as follows:

import pandas as pd

class Foo:
    def __init__(self):
        self.df = pd.DataFrame({'a':[1,1,2,2,3,3],'b':[4,5,6,7,8,9]})
    def __private_method(self,df):
        df['c'] = df['b'] + df['a']
        return df
    def public_method(self):
        new_df = self.df.groupby('a').apply(self.__private_method)
        print(new_df)

foo = Foo()
foo.public_method()

The code runs well as a script, either directly running it or with debugger. However, when I add a breakpoint in line 10:new_df = self.df.groupby('a').apply(self.__private_method), start debugging and stop there, and run this line of code in the debug console, I would see the following exception:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
AttributeError: 'Foo' object has no attribute '__private_method'

However, in the debug console, if I simply put self.__private_method, it seems to be able to find the method in the namespace and returns <bound method Foo.__private_method of <__main__.Foo object at 0x000002011DCA6790>>.

Lastly, I could run self.df.groupby('a').apply(self._Foo__private_method) in the debug console and get no error.

Could anyone help me understand what is going on when I pause in the debug mode and why I could visit self.__private_method but unable to call it? Thank you!


问:
in React if I want to conditionally render a component based on screen size is it better to use State or CSS?
Lets say I have a navigation bar, and for Mobile its a hamburger menu, and for desktop its a standard nav bar with links.

I could use CSS media queries to display none for certain screen size, or I could use react hooks useState and useEffect with some event listeners.

For starters it seems way easier to create the CSS solution, but is there a benefit to either or?

I've tried both of these my question is more so about performance or what is seen as the most preferred way to achieve this effect.


问:
Return the first row if duplicate exist
Note I always want to return all columns and not only those that are defined as distinct
I have a table lets call it Foo with these columns DeviceId, TransactionId, IndetId, Datetime, SalesId, and Quantity and some more columns

If I have rows that are identical for columns DeviceId, TransactionId, IndetId, Datetime, SalesId I want to select only the first row and skip the rest.
An example
DeviceId TransactionId IndetId  Datetime SalesId Quantity
123      10              8     2022-12-12   700    45

123      10              8     2022-12-12   700    75
In this example only the first row should be returned.
I can't use a simple distinct because I need all columns to be returned

I had hoped that the syntax for doing this should be something like this. Telling sql to use distinct only on these columns.
SELECT distinct(DeviceId, TransactionId, IndetId,Datetime, SalesId), Quantity
FROM Foo

If I do SELECT distinctDeviceId, TransactionId, IndetId, Datetime, SalesId
FROM Foo
then I miss a lot of columns and the result will be wrong

Title: Return the first row if duplicate exist


问:
Is there a way to mock Webclient post call with mockito
I want to mock a webclient post call using Mockito. But when mocking the post call I get a null pointer exception with the stacktrace:

Cannot invoke "org.springframework.web.reactive.function.client.WebClient$RequestBodyUriSpec.uri(String, Object[])" because the return value of "org.springframework.web.reactive.function.client.WebClient.post()" is null

My code

```<code>
@ActiveProfiles("unit-test")
@SpringBootTest
class ServiceTest {
   @MockBean
   lateinit var mockWebClient: WebClient

   @Test
   fun webclientMockedTest() {
       `when`(mockWebClient.post().uri("/path").body(Mono.just(request), request::class.java)
        .retrieve().bodyToMono(response::class.java).block())
        .thenReturn(response)
   }
}
</code>```

I was trying to mock webclient post call with the request and response DTO, however I am getting NPE. I am using mock.mockito.MockBean and Mockito.when library

Body:
I want to mock a webclient post call using Mockito. But when mocking the post call I get a null pointer exception with the stacktrace:

Cannot invoke "org.springframework.web.reactive.function.client.WebClient$RequestBodyUriSpec.uri(String, Object[])" because the return value of "org.springframework.web.reactive.function.client.WebClient.post()" is null

My code

@ActiveProfiles("unit-test")
@SpringBootTest
class ServiceTest {
   @MockBean
   lateinit var mockWebClient: WebClient

   @Test
   fun webclientMockedTest() {
       `when`(mockWebClient.post().uri("/path").body(Mono.just(request), request::class.java)
        .retrieve().bodyToMono(response::class.java).block())
        .thenReturn(response)
   }
}

I was trying to mock webclient post call with the request and response DTO, however I am getting NPE. I am using mock.mockito.MockBean and Mockito.when library


问:
Categorizing/classifying unlabeled text data
I've got an excel file which contains text data that I have to clean.

Example of the data I have

Each sentence contains many informations that are messed up. I have to extract dimension, colors, size, type of the product... from each sentence.

I really don't know where to start. I've thought of using NLTK or some NLP techniques but I'm still not sure what to do exactly.


问:
Roblox Studio Camera Script Kill Player
I have this script that makes the camera follow the player from a top down perspective, but when the camera pass the 55 studs Y position the player die. I don't know how to make the player stop dying.

```<code>local Players = game:GetService("Players")
local offset = 0
local wheelpos = 20
local cam = game.Workspace.CurrentCamera
local RunService = game:GetService("RunService")
local mouse = Players.LocalPlayer:GetMouse()
cam.CameraType = "Scriptable"

RunService.RenderStepped:Connect(function()
    local Pos = game.Players.LocalPlayer.Character.HumanoidRootPart.Position
    local pos = Vector3.new(Pos.X ,wheelpos,Pos.Z)
    local lookat = Vector3.new(Pos.x,0,Pos.Z)
    cam.CFrame = CFrame.new(pos, -lookat)
end)

mouse.WheelForward:Connect(function()
    if offset == 0 then
        wheelpos += 5
        offset += 1
        offset = 0
    end
end)

mouse.WheelBackward:Connect(function()
    if offset == 0 then
        wheelpos -= 5
        offset += 1
        offset = 0
    end
end)

</code>```

I tried to wait for player to spawn and then run the script but didn't work.

Title: Roblox Studio Camera Script Kill Player

Body:
I have this script that makes the camera follow the player from a top down perspective, but when the camera pass the 55 studs Y position the player die. I don't know how to make the player stop dying.

local Players = game:GetService("Players")
local offset = 0
local wheelpos = 20
local cam = game.Workspace.CurrentCamera
local RunService = game:GetService("RunService")
local mouse = Players.LocalPlayer:GetMouse()
cam.CameraType = "Scriptable"

RunService.RenderStepped:Connect(function()
    local Pos = game.Players.LocalPlayer.Character.HumanoidRootPart.Position
    local pos = Vector3.new(Pos.X ,wheelpos,Pos.Z)
    local lookat = Vector3.new(Pos.x,0,Pos.Z)
    cam.CFrame = CFrame.new(pos, -lookat)
end)

mouse.WheelForward:Connect(function()
    if offset == 0 then
        wheelpos += 5
        offset += 1
        offset = 0
    end
end)

mouse.WheelBackward:Connect(function()
    if offset == 0 then
        wheelpos -= 5
        offset += 1
        offset = 0
    end
end)

I tried to wait for player to spawn and then run the script but didn't work.


问:
to classify the extracted text from images into spam or non spam using python
<**

extract text from all the images in a folder

storing the text in a single file

from PIL import Image
import pytesseract as pt
import pandas as pd
from tabulate import tabulate
from io import StringIO
import os
import json
import csv

def main():
# path for the folder for getting the raw images
path ="E:/mehr mtech p1/images/"

```<code># link to the file in which output needs to be kept
fullTempPath ="E:/mehr mtech p1/out.txt"

# iterating the images inside the folder
for imageName in os.listdir(path):
    inputPath = os.path.join(path, imageName)
    img = Image.open(inputPath)
    #print(imageName)

    # applying ocr using pytesseract for python
    pt.pytesseract.tesseract_cmd = r'C:/Program Files/Tesseract-OCR/tesseract.exe'
    text = pt.image_to_string(img, lang ="eng")
    #print(text)

    dictionary = {'image': imageName, 'Text': text}
    print(dictionary)

    #Create a datafrmae from the dictionary
    df = pd.DataFrame(dictionary, index=[0])
    #print dataframe.
    #print(df)
    #print(tabulate(df, headers = 'keys', tablefmt = 'psql'))

    #Creating a string of the dictionary to print the data with labels in string format in the txt file
    #string = json.dumps(dictionary)
    #f1 = open("E:/mehr mtech p1/mmyfile.txt","a+")
    #f1.write(string)

    #df = pd.read_csv(string, sep =";")
    #print(df)

    df.to_csv("E:/mehr mtech p1/tableimage.csv")

    # saving the  text for appending it to the output.txt file
    # a + parameter used for creating the file if not present
    # and if present then append the text content
    file1 = open(fullTempPath, "a+")

    # providing the name of the image
    file1.write(imageName+"\n")

    # providing the content in the image
    file1.write(text+"\n")
    file1.close()

# for printing the output file
file2 = open(fullTempPath, 'r')
print(file2.read())

file2.close()
</code>```

if name == 'main':
main()

**>

the extracted text was converted into a dataframe by first converting it into a dictionary. but while converting that dataframe to a csv file and transferring data to excel file..only 1record i.e., only text of 1 image is coming in csv file..what to do now

the dataframe is coming in this way

the dictionary is coming this way

csv file

error

Body:
<**

extract text from all the images in a folder

storing the text in a single file

from PIL import Image
import pytesseract as pt
import pandas as pd
from tabulate import tabulate
from io import StringIO
import os
import json
import csv

def main():
# path for the folder for getting the raw images
path ="E:/mehr mtech p1/images/"

# link to the file in which output needs to be kept
fullTempPath ="E:/mehr mtech p1/out.txt"

# iterating the images inside the folder
for imageName in os.listdir(path):
    inputPath = os.path.join(path, imageName)
    img = Image.open(inputPath)
    #print(imageName)

    # applying ocr using pytesseract for python
    pt.pytesseract.tesseract_cmd = r'C:/Program Files/Tesseract-OCR/tesseract.exe'
    text = pt.image_to_string(img, lang ="eng")
    #print(text)

    dictionary = {'image': imageName, 'Text': text}
    print(dictionary)

    #Create a datafrmae from the dictionary
    df = pd.DataFrame(dictionary, index=[0])
    #print dataframe.
    #print(df)
    #print(tabulate(df, headers = 'keys', tablefmt = 'psql'))

    #Creating a string of the dictionary to print the data with labels in string format in the txt file
    #string = json.dumps(dictionary)
    #f1 = open("E:/mehr mtech p1/mmyfile.txt","a+")
    #f1.write(string)

    #df = pd.read_csv(string, sep =";")
    #print(df)

    df.to_csv("E:/mehr mtech p1/tableimage.csv")

    # saving the  text for appending it to the output.txt file
    # a + parameter used for creating the file if not present
    # and if present then append the text content
    file1 = open(fullTempPath, "a+")

    # providing the name of the image
    file1.write(imageName+"\n")

    # providing the content in the image
    file1.write(text+"\n")
    file1.close()

# for printing the output file
file2 = open(fullTempPath, 'r')
print(file2.read())

file2.close()

if name == 'main':
main()

**>

the extracted text was converted into a dataframe by first converting it into a dictionary. but while converting that dataframe to a csv file and transferring data to excel file..only 1record i.e., only text of 1 image is coming in csv file..what to do now

the dataframe is coming in this way

the dictionary is coming this way

csv file

error


问:
What would be the best approach to do borders where you form a cross. (see Picture for context)

I am using bootstrap for this template, and my first approach was to use d-flex  and apply justify-content-end the ones on the left  and justify-content-start so they all get close to each other. So far so good until I had to apply the borders so it would show that nice line on the middle of the columns (the one that divides all columns as a cross. The problem is that when I try to apply it the cross is not centered and its not able to close completely

Here is what I have so far
https://codepen.io/fjadvocates/pen/ExpKZJw

What is the best approach to make it look like the image I uploaded?


问:
Python - using data from multiple lines in a txt file
I'm on a coding course and am struggling with a task.

I have a txt file that I'm importing data from (in this case usernames and passwords). The first line (and only provided to start with) is:
admin, adm1n
Logging in with this is fine. Once I've added a 2nd user and password though only the new user works to log in and the admin one no longer works.

So for the below code, my txt now reads:

admin, adm1n

user2, password

```<code>file = open("user.txt", "r")

user = file.readlines()
for line in user:
    data = line.split(", ")

user_username = data[0]
user_password = data[1]

while username != user_username:
    username = input("Sorry, that username is not recognised, please try again: ")

else:
    password = input("Please enter your password: ")

    while password != user_password:
        password = input("Sorry, that password is not recognised, please try again: ")

    else:
        print("\nThank you. Logging in...\n")
</code>```

In case it's relevant, I've added the new login details in the below way:

```<code>while True:
    menu = input('''Select one of the following Options below:
r - Registering a user
a - Adding a task
va - View all tasks
vm - view my task
e - Exit
: ''').lower()

    if menu == 'r':
        new_user = input("Please enter a new username: ")
        new_password = input("Please enter a new password: ")
        password_confirmation = input("Please confirm your password: ")
        while new_password != password_confirmation:
            new_password = input("Sorry, those did not match. Please enter a new password: ")
            password_confirmation = input("Please confirm your password: ")

        with open("user.txt", "a") as file:
            file.write("\n" + new_user + ", " + new_password)
</code>```

The above all works but I can no longer use admin as a login, only user2 once entered.

Thanks in advance for any help - please let me know if I need to clarify anything! I'm a beginner so if you can explain where I'm going wrong as well as the code I should be using so I can learn I'd really appreciate it!

Body:
I'm on a coding course and am struggling with a task.

I have a txt file that I'm importing data from (in this case usernames and passwords). The first line (and only provided to start with) is:
admin, adm1n
Logging in with this is fine. Once I've added a 2nd user and password though only the new user works to log in and the admin one no longer works.

So for the below code, my txt now reads:

admin, adm1n

user2, password

file = open("user.txt", "r")

user = file.readlines()
for line in user:
    data = line.split(", ")

user_username = data[0]
user_password = data[1]

while username != user_username:
    username = input("Sorry, that username is not recognised, please try again: ")

else:
    password = input("Please enter your password: ")

    while password != user_password:
        password = input("Sorry, that password is not recognised, please try again: ")

    else:
        print("\nThank you. Logging in...\n")

In case it's relevant, I've added the new login details in the below way:

while True:
    menu = input('''Select one of the following Options below:
r - Registering a user
a - Adding a task
va - View all tasks
vm - view my task
e - Exit
: ''').lower()

    if menu == 'r':
        new_user = input("Please enter a new username: ")
        new_password = input("Please enter a new password: ")
        password_confirmation = input("Please confirm your password: ")
        while new_password != password_confirmation:
            new_password = input("Sorry, those did not match. Please enter a new password: ")
            password_confirmation = input("Please confirm your password: ")

        with open("user.txt", "a") as file:
            file.write("\n" + new_user + ", " + new_password)

The above all works but I can no longer use admin as a login, only user2 once entered.

Thanks in advance for any help - please let me know if I need to clarify anything! I'm a beginner so if you can explain where I'm going wrong as well as the code I should be using so I can learn I'd really appreciate it!


问:
Scipy PearsonR p-value confusion when using the alternative hypothesis as less than 0
So I understand that scipy.stats.pearsonr() produces a p-value and correlation coefficient of the given observations. By default, it performs a 2-tailed test but when I change this to one-tailed, I get a wildly different result especially when testing the less than 0 tail.

Input:

```<code>scipy.stats.pearsonr(x, y)
scipy.stats.pearsonr(x, y, alternative='less')
scipy.stats.pearsonr(x, y, alternative='greater')
</code>```

Output:

```<code>PearsonRResult(statistic=-0.199716724929402, pvalue=1.8904897940408397e-05)
PearsonRResult(statistic=-0.199716724929402, pvalue=0.9999905475510298)
PearsonRResult(statistic=-0.199716724929402, pvalue=9.452448970204198e-06)
</code>```

So the Pearson correlation coefficient between the arrays is negative and significantly not 0 in a 2-tailed test, but then not significantly negative but also significantly positive?

Body:
So I understand that scipy.stats.pearsonr() produces a p-value and correlation coefficient of the given observations. By default, it performs a 2-tailed test but when I change this to one-tailed, I get a wildly different result especially when testing the less than 0 tail.

Input:

scipy.stats.pearsonr(x, y)
scipy.stats.pearsonr(x, y, alternative='less')
scipy.stats.pearsonr(x, y, alternative='greater')

Output:

PearsonRResult(statistic=-0.199716724929402, pvalue=1.8904897940408397e-05)
PearsonRResult(statistic=-0.199716724929402, pvalue=0.9999905475510298)
PearsonRResult(statistic=-0.199716724929402, pvalue=9.452448970204198e-06)

So the Pearson correlation coefficient between the arrays is negative and significantly not 0 in a 2-tailed test, but then not significantly negative but also significantly positive?


问:
Align right inside block
I have a template which has 4 list items for some links. I minimized them to 2 and want to put country flags to both sides. Here's a screenshot:

When I grow the page the flag seems left part of the item:

Here's my code:

```<code><li><a class="active">Türkçe<img style="position: absolute; height: 23px; width: 34px; top: 0.15em; margin-left: 12%; margin-right: auto;" src="./images/turkey-flag2.jpg" /></a></li>
</code>```

How can I put the flag to the right side of the item?

Title: Align right inside block

Body:
I have a template which has 4 list items for some links. I minimized them to 2 and want to put country flags to both sides. Here's a screenshot:

When I grow the page the flag seems left part of the item:

Here's my code:

Türkçe

How can I put the flag to the right side of the item?


问:
Can't use custom tax query on archive-product.php in Woocommerce
I am using a custom archive-product.php file in my WooCommerce theme. I haven't changed much about the file, just added a few HTML elements for sidebars and such, but the main componants remain untouched.

In my template, I'm trying to get a list of categories with this code, in a sidebar (outside the loop):

```<code>$prodCats = get_categories(array('taxonomy'=>'product_cat','exclude'=>'26,482,474','parent'=>0));
    if (!empty($prodCats)) {
        //echo '<center><strong>Jump to Category</strong></center>';
        echo '<ul>';
        foreach ($prodCats as $cat) {
            // get the thumbnail id using the queried category term_id
            $thumbnail_id = get_term_meta( $cat->term_id, 'thumbnail_id', true );

            // get the image URL
            $image = wp_get_attachment_url( $thumbnail_id );
            echo '<li>';
            echo '<a href="'.get_category_link( $cat->term_id ).'"></a>';
            echo '<div class="catName">'.$cat->name.'</div>';
            echo '<img src="'.$image.'"/>';
            echo '</li>';
        }
        echo '</ul>';
    }
</code>```

But, this outputs only the product categories that are part of the current WooCommerce loop. It will not get all the product categories. It seems to somehow be tied to the WC loop on that page instead of operating independantly.

Is this intended behavior on a custom post type archive or specifically on WooCommerce?

If not, what might I look for to solve this?

This code, which does a similar thing on a woocommerce Product Attribute (pa_brand) is also affected. Note that I'm using new WP_Term_Query here to see if that solves it, but it still only pulls the terms that are in the current WC loop.

```<code>//Get brand list and display it
function ppp_get_brand_list() {
    ?>
    <div id="brandList">
    <center><h4>Brands</h4></center>
    <?php
    $brandArgs = array(
        'taxonomy' => 'pa_brand',
        'hide_empty' => true,
    );
    $brands = new WP_Term_Query( $brandArgs );

    echo '<ul>';
    foreach ( $brands->terms as $brand ) {
        $brand_image_id = get_term_meta( $brand->term_id, 'product_search_image_id', true );
        $brand_image = wp_get_attachment_url( $brand_image_id );
        $brand_link = get_term_link($brand->term_id,'pa_brand');
        echo '<li><a href="'.$brand_link.'"><img src="'.$brand_image.'" alt="" /></a></li>';
    }
    echo '</ul>';

    ?>
    </div>
    <?php
}
</code>```

Body:
I am using a custom archive-product.php file in my WooCommerce theme. I haven't changed much about the file, just added a few HTML elements for sidebars and such, but the main componants remain untouched.

In my template, I'm trying to get a list of categories with this code, in a sidebar (outside the loop):

$prodCats = get_categories(array('taxonomy'=>'product_cat','exclude'=>'26,482,474','parent'=>0));
    if (!empty($prodCats)) {
        //echo 'Jump to Category';
        echo '
';
        foreach ($prodCats as $cat) {
            // get the thumbnail id using the queried category term_id
            $thumbnail_id = get_term_meta( $cat->term_id, 'thumbnail_id', true );

            // get the image URL
            $image = wp_get_attachment_url( $thumbnail_id );
            echo '
';
            echo 'term_id ).'">';
            echo '
'.$cat->name.'
';
            echo '';
            echo '
';
        }
        echo '
';
    }

But, this outputs only the product categories that are part of the current WooCommerce loop. It will not get all the product categories. It seems to somehow be tied to the WC loop on that page instead of operating independantly.

Is this intended behavior on a custom post type archive or specifically on WooCommerce?

If not, what might I look for to solve this?

This code, which does a similar thing on a woocommerce Product Attribute (pa_brand) is also affected. Note that I'm using new WP_Term_Query here to see if that solves it, but it still only pulls the terms that are in the current WC loop.

//Get brand list and display it
function ppp_get_brand_list() {
    ?>

Brands

    <?php
    $brandArgs = array(
        'taxonomy' => 'pa_brand',
        'hide_empty' => true,
    );
    $brands = new WP_Term_Query( $brandArgs );

    echo '
';
    foreach ( $brands->terms as $brand ) {
        $brand_image_id = get_term_meta( $brand->term_id, 'product_search_image_id', true );
        $brand_image = wp_get_attachment_url( $brand_image_id );
        $brand_link = get_term_link($brand->term_id,'pa_brand');
        echo '

';
    }
    echo '
';

    ?>

    <?php
}


问:
Prevent spam with Future.wait in flutter
i have a anti DDOS rule in my server with max 20 requests in 1 second.

In my flutter program, i want to call an API n times but sometimes n is greater than 20.
How to avoid some issue

Here my code (don't work it seems)

```<code>      // Search token informations
      final tokenMap = <String, Token>{};
      var antiSpam = 0;
      final getTokens = await Future.wait(
        tokenAddressList.toSet().map((final tokenAddress) async {
          if (antiSpam > 0 && antiSpam % 19 == 1) {
            return Future.delayed(const Duration(seconds: 1));
          } else {
            antiSpam++;
            return sl.get<ApiService>().getToken(
              [tokenAddress],

            );
          }
        }),
      );
</code>```

Body:
i have a anti DDOS rule in my server with max 20 requests in 1 second.

In my flutter program, i want to call an API n times but sometimes n is greater than 20.
How to avoid some issue

Here my code (don't work it seems)

      // Search token informations
      final tokenMap = <String, Token>{};
      var antiSpam = 0;
      final getTokens = await Future.wait(
        tokenAddressList.toSet().map((final tokenAddress) async {
          if (antiSpam > 0 && antiSpam % 19 == 1) {
            return Future.delayed(const Duration(seconds: 1));
          } else {
            antiSpam++;
            return sl.get<ApiService>().getToken(
              [tokenAddress],

            );
          }
        }),
      );


问:
How to use the parameter in fetchTicker?
I need that in the telegram bot, after writing the words "Exchange rate",
I get the last price of the pair "BTC/ USD". But I get all the information
about the "BTC/USD" pair. What am I doing wrong? (For now, I just output it
to the console to avoid errors)

```<code>const { wavesexchange } = require('ccxt');
const ccxt = require ('ccxt')
const exchange = new ccxt.bitfinex ()

const we = new wavesexchange({
    apiKey: 'PUBLIC',
    secret: 'SECRET',
});

(async () => {
    await we.loadMarkets();

}) ()

const { Telegraf } = require('telegraf');
const TELEGRAM_BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN || "BOT_TOKEN";

const bot = new Telegraf(TELEGRAM_BOT_TOKEN);

bot.start(ctx => {
    return ctx.reply("Welcome to WX Currency Bot");
})

bot.hears('Exchange rate', ctx => {
    //ctx.reply('Wait ⌛');
    (async function test () {
    console.log (await (exchange.fetchTicker ('BTC/USD',{ 'info': 'last_price' })))
    //return ctx.reply(exchange.fetchTicker ('BTC/USD',{ 'info': 'last_price' }));
    }) ()

});
bot.startPolling();
</code>```

I have tried to get information about the latest price in different ways:
1.

```<code>console.log (await (exchange.fetchTicker ('BTC/USD',{ 'info': 'last_price' })))
</code>```

```<code>console.log (await (exchange.fetchTicker ('BTC/USD','info:last_price')))
</code>```

```<code>console.log (await (exchange.fetchTicker ('BTC/USD',info=last_price)))
</code>```

Body:
I need that in the telegram bot, after writing the words "Exchange rate",
I get the last price of the pair "BTC/ USD". But I get all the information
about the "BTC/USD" pair. What am I doing wrong? (For now, I just output it
to the console to avoid errors)

const { wavesexchange } = require('ccxt');
const ccxt = require ('ccxt')
const exchange = new ccxt.bitfinex ()

const we = new wavesexchange({
    apiKey: 'PUBLIC',
    secret: 'SECRET',
});

(async () => {
    await we.loadMarkets();

}) ()

const { Telegraf } = require('telegraf');
const TELEGRAM_BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN || "BOT_TOKEN";

const bot = new Telegraf(TELEGRAM_BOT_TOKEN);

bot.start(ctx => {
    return ctx.reply("Welcome to WX Currency Bot");
})

bot.hears('Exchange rate', ctx => {
    //ctx.reply('Wait ⌛');
    (async function test () {
    console.log (await (exchange.fetchTicker ('BTC/USD',{ 'info': 'last_price' })))
    //return ctx.reply(exchange.fetchTicker ('BTC/USD',{ 'info': 'last_price' }));
    }) ()

});
bot.startPolling();

I have tried to get information about the latest price in different ways:
1.

console.log (await (exchange.fetchTicker ('BTC/USD',{ 'info': 'last_price' })))

console.log (await (exchange.fetchTicker ('BTC/USD','info:last_price')))

console.log (await (exchange.fetchTicker ('BTC/USD',info=last_price)))


问:
Can't print string inside window object in Python curses
This program should display an user input field using curses. I'm facing a problem when I'm trying to create a rectangle around the user_input window and put a ">" character inside it. Playing around with the order of the code I can get the terminal to print either the rectangle or the ">" character but never both unfortunately.

```<code>    def update_screen(self):
        self.y, self.x = self.stdscr.getmaxyx()

        self.stdscr.clear()

        self.stdscr.addstr(0, 1, f"{self.x}, {self.y}")

        # update user input window
        self.user_input.resize(3, self.x - 2)
        self.user_input.mvwin(self.y - 3, 1)
        a, b = self.user_input.getbegyx()
        c, d = self.user_input.getmaxyx()
        rectangle(self.stdscr, a, b, a + c - 1, b + d - 1) #should print a rectangle

        self.user_input.addstr(1, 1, ">") # should print the ">" char inside rect

        self.user_input.refresh()

        self.stdscr.refresh()
</code>```

I'm assuming refresh() clears either one of them, but I don't know how else to program it. Pastebin: https://pastebin.com/jGjEkEqx

Body:
This program should display an user input field using curses. I'm facing a problem when I'm trying to create a rectangle around the user_input window and put a ">" character inside it. Playing around with the order of the code I can get the terminal to print either the rectangle or the ">" character but never both unfortunately.

    def update_screen(self):
        self.y, self.x = self.stdscr.getmaxyx()

        self.stdscr.clear()

        self.stdscr.addstr(0, 1, f"{self.x}, {self.y}")

        # update user input window
        self.user_input.resize(3, self.x - 2)
        self.user_input.mvwin(self.y - 3, 1)
        a, b = self.user_input.getbegyx()
        c, d = self.user_input.getmaxyx()
        rectangle(self.stdscr, a, b, a + c - 1, b + d - 1) #should print a rectangle

        self.user_input.addstr(1, 1, ">") # should print the ">" char inside rect

        self.user_input.refresh()

        self.stdscr.refresh()

I'm assuming refresh() clears either one of them, but I don't know how else to program it. Pastebin: https://pastebin.com/jGjEkEqx


问:
The wp.customize object is not working for me
I used to add Customizer Panel, Section and Controles using the classic PHP Method, but, then I found Weston Ruter's post and found that the PHP method is just a wraper for wp.customize JavaScript object.

The post -> https://make.wordpress.org/core/2017/11/01/improvements-to-the-customize-js-api-in-4-9/.

I'm trying to create new panel, section and control using the wp.customize control on my custom theme, but IDK why I can't see any changes in the customizer.

In functions.php

function customize_preview_js() {
    wp_enqueue_script( 'agilitywp-customizer', THEME_DIR . 'js/customizer-preview.js', array( 'customize-preview' ), VERSION, true );
}
add_action( 'customize_preview_init', 'customize_preview_js' );
```
<p>In customizer-preview.js:</p>
```wp.customize.bind( 'ready', function() {
    // Add a custom panel
    wp.customize.panel.add( 'my_panel', {
      title: 'My Panel',
      priority: 10,
    } );

    // Add a custom section
    wp.customize.section.add( 'my_section', {
      title: 'My Section',
      panel: 'my_panel',
      priority: 10,
    } );

    // Add a custom control
    const control = new wp.customize.Control( 'my_control', {
      type: 'text',
      label: 'My Control',
      section: 'my_section',
      settings: {
            default: 'my_setting',
      },
    } );
    wp.customize.add( control );
} );
```

I'm not sure if I' doing something wrong or I understand the Weston's post wrong. I'd appreciate all your help and discussion.

Thank you!

Body:
I used to add Customizer Panel, Section and Controles using the classic PHP Method, but, then I found Weston Ruter's post and found that the PHP method is just a wraper for wp.customize JavaScript object.

The post -> https://make.wordpress.org/core/2017/11/01/improvements-to-the-customize-js-api-in-4-9/.

I'm trying to create new panel, section and control using the wp.customize control on my custom theme, but IDK why I can't see any changes in the customizer.

In functions.php

function customize_preview_js() {
    wp_enqueue_script( 'agilitywp-customizer', THEME_DIR . 'js/customizer-preview.js', array( 'customize-preview' ), VERSION, true );
}
add_action( 'customize_preview_init', 'customize_preview_js' );

In customizer-preview.js:

wp.customize.bind( 'ready', function() {
    // Add a custom panel
    wp.customize.panel.add( 'my_panel', {
      title: 'My Panel',
      priority: 10,
    } );

    // Add a custom section
    wp.customize.section.add( 'my_section', {
      title: 'My Section',
      panel: 'my_panel',
      priority: 10,
    } );

    // Add a custom control
    const control = new wp.customize.Control( 'my_control', {
      type: 'text',
      label: 'My Control',
      section: 'my_section',
      settings: {
            default: 'my_setting',
      },
    } );
    wp.customize.add( control );
} );

I'm not sure if I' doing something wrong or I understand the Weston's post wrong. I'd appreciate all your help and discussion.

Thank you!


问:
Tizen Studio Certificate Samsung TV remote device
After accidentally pushing update on Package manager my tizen Studio stop functioning the way it did before.

I had to remove all my IDE files and install from scratch
After 1 week struggling i managed to install the recent Extention 6.5 and my Extention 4.0 for My tizen smart tv 2.4

Now im connecting to the same tv and stuck in this for about 4 minutes before the app starts:
`

```<code>Launching the Tizen application...
# If you want to see the detailed information,
# please set the logging level to DEBUG in Preferences and check the log file in '/Users/ANYNO/tizen-studio-data/ide/logs/ide-20221229_161441.log'.

[Initializing the launch environment...]
    RDS: On
    Target information: UE55KU6075
    Application information: Id(HV7Ga7JLUO.SoleimanTV), Package Name(HV7Ga7JLUO), Project Name(SoleimanTV)
[Transferring the package...]
</code>```

`

I took stopwatch and its taking 4,20 min to "transfer the package to the tv"

at the same time the certificate i created for my samsung tv in CF MANAGER should work for my Emulator also?

My questions are:

Why taking so long for pushing the app to the remote tv? what im doing wrong?

Should i create two different certificate one for TV and one for emulator?

Please respond if you have experienced the same. I would otherwise not have other solutions than reset my MAC and start all over again.

PS: friendly advice: IF you ever see a button with the text "Updates available" STAY AWAY

Uninstalled Tizen Studio and installed all over again.

Body:
After accidentally pushing update on Package manager my tizen Studio stop functioning the way it did before.

I had to remove all my IDE files and install from scratch
After 1 week struggling i managed to install the recent Extention 6.5 and my Extention 4.0 for My tizen smart tv 2.4

Now im connecting to the same tv and stuck in this for about 4 minutes before the app starts:
`

Launching the Tizen application...
# If you want to see the detailed information,
# please set the logging level to DEBUG in Preferences and check the log file in '/Users/ANYNO/tizen-studio-data/ide/logs/ide-20221229_161441.log'.

[Initializing the launch environment...]
    RDS: On
    Target information: UE55KU6075
    Application information: Id(HV7Ga7JLUO.SoleimanTV), Package Name(HV7Ga7JLUO), Project Name(SoleimanTV)
[Transferring the package...]

`

I took stopwatch and its taking 4,20 min to "transfer the package to the tv"

at the same time the certificate i created for my samsung tv in CF MANAGER should work for my Emulator also?

My questions are:

Why taking so long for pushing the app to the remote tv? what im doing wrong?

Should i create two different certificate one for TV and one for emulator?

Please respond if you have experienced the same. I would otherwise not have other solutions than reset my MAC and start all over again.

PS: friendly advice: IF you ever see a button with the text "Updates available" STAY AWAY

Uninstalled Tizen Studio and installed all over again.


问:
mypy: how to ignore specified files (not talking about how to ignore errors)
I want to let mypy ignore a specified file. I'm not talking about just ignoring error (which already answered in many places), rather I want mypy to completely ignore specified files.

When applying mypy to jax library, mypy somehow hangs. For example, let's say there is a file named main.py with only single file

import jax
```
<p>Mypy somehow takes really long time (over 5 minuites) when applying <code>main.py</code> with the following log (abbreviated). Thus I want let mypy ignore specific file.</p>
```h-ishida@stone-jsk:/tmp/test$ mypy -v main.py
LOG:  Could not load plugins snapshot: @plugins_snapshot.json

LOG:  Mypy Version:           0.991
LOG:  Config File:            Default
LOG:  Configured Executable:  /usr/bin/python3
LOG:  Current Executable:     /usr/bin/python3
LOG:  Cache Dir:              .mypy_cache
LOG:  Compiled:               True
LOG:  Exclude:                []
LOG:  Found source:           BuildSource(path='main.py', module='main', has_text=False, base_dir='/tmp/test', followed=False)
LOG:  Could not load cache for main: main.meta.json
LOG:  Metadata not found for main
LOG:  Parsing main.py (main)
LOG:  Could not load cache for jax: jax/__init__.meta.json
LOG:  Metadata not found for jax
LOG:  Parsing /home/h-ishida/.local/lib/python3.8/site-packages/jax/__init__.py (jax)
LOG:  Metadata fresh for builtins: file /home/h-ishida/.local/lib/python3.8/site-packages/mypy/typeshed/stdlib/builtins.pyi
LOG:  Metadata fresh for jax._src.cloud_tpu_init: file /home/h-ishida/.local/lib/python3.8/site-packages/jax/_src/cloud_tpu_init.py
LOG:  Could not load cache for jax._src.basearray: jax/_src/basearray.meta.json
LOG:  Metadata not found for jax._src.basearray
...
LOG:  Found 163 SCCs; largest has 196 nodes
LOG:  Processing 161 queued fresh SCCs
LOG:  Processing SCC of size 196 (jax.scipy jax._src.lib jax._src.config jax.experimental.x64_context jax._src.iree jax.config jax._src.pretty_printer jax._src.util jax.util jax._src.lax.stack jax._src.state.types jax._src.lax.svd jax._src.nn.initializers jax._src.lax.qdwh jax._src.debugger.web_debugger jax._src.debugger.colab_debugger jax._src.debugger.cli_debugger jax._src.debugger.core jax._src.clusters.cloud_tpu_cluster jax._src.clusters.slurm_cluster jax._src.clusters jax._src.lax.utils jax._src.profiler jax._src.ops.scatter jax._src.numpy.vectorize jax._src.lax.ann jax._src.lax.other jax._src.errors jax._src.abstract_arrays jax._src.traceback_util jax._src.source_info_util jax._src.callback jax._src.lib.xla_bridge jax._src.sharding jax.lib jax._src.tree_util jax._src.environment_info jax._src.lax.eigh jax._src.lib.mlir.dialects jax.lib.xla_bridge jax._src.stages jax.nn.initializers jax._src.debugger jax._src.distributed jax._src.api_util jax.tree_util jax.profiler jax.ops jax.errors jax._src.typing jax._src.array jax._src.basearray jax._src.state.primitives jax._src.numpy.ndarray jax._src.custom_transpose jax._src.ad_checkpoint jax._src.lax.convolution jax._src.lax.slicing jax._src.debugging jax.linear_util jax.interpreters.mlir jax._src.dtypes jax._src.dispatch jax._src.device_array jax.stages jax.distributed jax.api_util jax.core jax._src.state.discharge jax._src.lax.control_flow.common jax._src.numpy.util jax._src.ad_util jax._src.lax.parallel jax.custom_transpose jax.ad_checkpoint jax.interpreters.pxla jax.interpreters.xla jax.interpreters.partial_eval jax.dtypes jax.debug jax.abstract_arrays jax._src.state jax._src.third_party.numpy.linalg jax._src.numpy.fft jax._src.lax.control_flow.solves jax._src.lax.control_flow.conditionals jax._src.numpy.reductions jax._src.numpy.index_tricks jax.interpreters.batching jax.interpreters.ad jax.sharding jax._src.custom_derivatives jax._src.custom_batching jax.numpy.fft jax._src.lax.lax jax._src.lax.linalg jax.custom_derivatives jax.custom_batching jax.lax.linalg jax._src.api jax.experimental.global_device_array jax._src.prng jax._src.numpy.ufuncs jax._src.lax.fft jax jax._src.numpy.linalg jax._src.lax.control_flow.loops jax.experimental.maps jax._src.lax.windowed_reductions jax._src.image.scale jax._src.numpy.lax_numpy jax.experimental.pjit jax._src.ops.special jax.numpy.linalg jax._src.numpy.setops jax._src.numpy.polynomial jax._src.lax.control_flow jax.image jax._src.random jax._src.nn.functions jax.numpy jax.lax jax.random jax.nn jax._src.dlpack jax.experimental.compilation_cache.compilation_cache jax.experimental jax.interpreters jax._src.lax jax.dlpack jax._src.scipy.cluster.vq jax._src.scipy.stats.gennorm jax._src.scipy.stats.chi2 jax._src.scipy.stats.uniform jax._src.scipy.stats.t jax._src.scipy.stats.pareto jax._src.scipy.stats.multivariate_normal jax._src.scipy.stats.laplace jax._src.scipy.stats.expon jax._src.scipy.stats.cauchy jax._src.third_party.scipy.betaln jax._src.scipy.sparse.linalg jax._src.third_party.scipy.signal_helper jax._src.scipy.fft jax._src.scipy.stats._core jax._src.scipy.ndimage jax._src.scipy.linalg jax._src.third_party.scipy.interpolate jax.scipy.cluster.vq jax.scipy.stats.gennorm jax.scipy.stats.chi2 jax.scipy.stats.uniform jax.scipy.stats.t jax.scipy.stats.pareto jax.scipy.stats.multivariate_normal jax.scipy.stats.laplace jax.scipy.stats.expon jax.scipy.stats.cauchy jax._src.scipy.special jax.scipy.sparse.linalg jax._src.scipy.signal jax._src.third_party.scipy.linalg jax.scipy.fft jax.scipy.ndimage jax.scipy.interpolate jax._src.scipy.stats.betabinom jax._src.scipy.stats.nbinom jax._src.scipy.stats.multinomial jax.scipy.cluster jax.scipy.special jax.scipy.sparse jax.scipy.signal jax.scipy.linalg jax._src.scipy.stats.poisson jax._src.scipy.stats.norm jax._src.scipy.stats.logistic jax._src.scipy.stats.geom jax._src.scipy.stats.gamma jax._src.scipy.stats.dirichlet jax._src.scipy.stats.beta jax._src.scipy.stats.bernoulli jax.scipy.stats.betabinom jax.scipy.stats.nbinom jax.scipy.stats.multinomial jax._src.scipy.stats.kde jax._src.scipy.stats.truncnorm jax.scipy.stats.poisson jax.scipy.stats.norm jax.scipy.stats.logistic jax.scipy.stats.geom jax.scipy.stats.gamma jax.scipy.stats.dirichlet jax.scipy.stats.beta jax.scipy.stats.bernoulli jax.scipy.stats.truncnorm jax.scipy.stats) as inherently stale

```

Body:
I want to let mypy ignore a specified file. I'm not talking about just ignoring error (which already answered in many places), rather I want mypy to completely ignore specified files.

When applying mypy to jax library, mypy somehow hangs. For example, let's say there is a file named main.py with only single file

import jax

Mypy somehow takes really long time (over 5 minuites) when applying main.py with the following log (abbreviated). Thus I want let mypy ignore specific file.

h-ishida@stone-jsk:/tmp/test$ mypy -v main.py
LOG:  Could not load plugins snapshot: @plugins_snapshot.json

LOG:  Mypy Version:           0.991
LOG:  Config File:            Default
LOG:  Configured Executable:  /usr/bin/python3
LOG:  Current Executable:     /usr/bin/python3
LOG:  Cache Dir:              .mypy_cache
LOG:  Compiled:               True
LOG:  Exclude:                []
LOG:  Found source:           BuildSource(path='main.py', module='main', has_text=False, base_dir='/tmp/test', followed=False)
LOG:  Could not load cache for main: main.meta.json
LOG:  Metadata not found for main
LOG:  Parsing main.py (main)
LOG:  Could not load cache for jax: jax/__init__.meta.json
LOG:  Metadata not found for jax
LOG:  Parsing /home/h-ishida/.local/lib/python3.8/site-packages/jax/__init__.py (jax)
LOG:  Metadata fresh for builtins: file /home/h-ishida/.local/lib/python3.8/site-packages/mypy/typeshed/stdlib/builtins.pyi
LOG:  Metadata fresh for jax._src.cloud_tpu_init: file /home/h-ishida/.local/lib/python3.8/site-packages/jax/_src/cloud_tpu_init.py
LOG:  Could not load cache for jax._src.basearray: jax/_src/basearray.meta.json
LOG:  Metadata not found for jax._src.basearray
...
LOG:  Found 163 SCCs; largest has 196 nodes
LOG:  Processing 161 queued fresh SCCs
LOG:  Processing SCC of size 196 (jax.scipy jax._src.lib jax._src.config jax.experimental.x64_context jax._src.iree jax.config jax._src.pretty_printer jax._src.util jax.util jax._src.lax.stack jax._src.state.types jax._src.lax.svd jax._src.nn.initializers jax._src.lax.qdwh jax._src.debugger.web_debugger jax._src.debugger.colab_debugger jax._src.debugger.cli_debugger jax._src.debugger.core jax._src.clusters.cloud_tpu_cluster jax._src.clusters.slurm_cluster jax._src.clusters jax._src.lax.utils jax._src.profiler jax._src.ops.scatter jax._src.numpy.vectorize jax._src.lax.ann jax._src.lax.other jax._src.errors jax._src.abstract_arrays jax._src.traceback_util jax._src.source_info_util jax._src.callback jax._src.lib.xla_bridge jax._src.sharding jax.lib jax._src.tree_util jax._src.environment_info jax._src.lax.eigh jax._src.lib.mlir.dialects jax.lib.xla_bridge jax._src.stages jax.nn.initializers jax._src.debugger jax._src.distributed jax._src.api_util jax.tree_util jax.profiler jax.ops jax.errors jax._src.typing jax._src.array jax._src.basearray jax._src.state.primitives jax._src.numpy.ndarray jax._src.custom_transpose jax._src.ad_checkpoint jax._src.lax.convolution jax._src.lax.slicing jax._src.debugging jax.linear_util jax.interpreters.mlir jax._src.dtypes jax._src.dispatch jax._src.device_array jax.stages jax.distributed jax.api_util jax.core jax._src.state.discharge jax._src.lax.control_flow.common jax._src.numpy.util jax._src.ad_util jax._src.lax.parallel jax.custom_transpose jax.ad_checkpoint jax.interpreters.pxla jax.interpreters.xla jax.interpreters.partial_eval jax.dtypes jax.debug jax.abstract_arrays jax._src.state jax._src.third_party.numpy.linalg jax._src.numpy.fft jax._src.lax.control_flow.solves jax._src.lax.control_flow.conditionals jax._src.numpy.reductions jax._src.numpy.index_tricks jax.interpreters.batching jax.interpreters.ad jax.sharding jax._src.custom_derivatives jax._src.custom_batching jax.numpy.fft jax._src.lax.lax jax._src.lax.linalg jax.custom_derivatives jax.custom_batching jax.lax.linalg jax._src.api jax.experimental.global_device_array jax._src.prng jax._src.numpy.ufuncs jax._src.lax.fft jax jax._src.numpy.linalg jax._src.lax.control_flow.loops jax.experimental.maps jax._src.lax.windowed_reductions jax._src.image.scale jax._src.numpy.lax_numpy jax.experimental.pjit jax._src.ops.special jax.numpy.linalg jax._src.numpy.setops jax._src.numpy.polynomial jax._src.lax.control_flow jax.image jax._src.random jax._src.nn.functions jax.numpy jax.lax jax.random jax.nn jax._src.dlpack jax.experimental.compilation_cache.compilation_cache jax.experimental jax.interpreters jax._src.lax jax.dlpack jax._src.scipy.cluster.vq jax._src.scipy.stats.gennorm jax._src.scipy.stats.chi2 jax._src.scipy.stats.uniform jax._src.scipy.stats.t jax._src.scipy.stats.pareto jax._src.scipy.stats.multivariate_normal jax._src.scipy.stats.laplace jax._src.scipy.stats.expon jax._src.scipy.stats.cauchy jax._src.third_party.scipy.betaln jax._src.scipy.sparse.linalg jax._src.third_party.scipy.signal_helper jax._src.scipy.fft jax._src.scipy.stats._core jax._src.scipy.ndimage jax._src.scipy.linalg jax._src.third_party.scipy.interpolate jax.scipy.cluster.vq jax.scipy.stats.gennorm jax.scipy.stats.chi2 jax.scipy.stats.uniform jax.scipy.stats.t jax.scipy.stats.pareto jax.scipy.stats.multivariate_normal jax.scipy.stats.laplace jax.scipy.stats.expon jax.scipy.stats.cauchy jax._src.scipy.special jax.scipy.sparse.linalg jax._src.scipy.signal jax._src.third_party.scipy.linalg jax.scipy.fft jax.scipy.ndimage jax.scipy.interpolate jax._src.scipy.stats.betabinom jax._src.scipy.stats.nbinom jax._src.scipy.stats.multinomial jax.scipy.cluster jax.scipy.special jax.scipy.sparse jax.scipy.signal jax.scipy.linalg jax._src.scipy.stats.poisson jax._src.scipy.stats.norm jax._src.scipy.stats.logistic jax._src.scipy.stats.geom jax._src.scipy.stats.gamma jax._src.scipy.stats.dirichlet jax._src.scipy.stats.beta jax._src.scipy.stats.bernoulli jax.scipy.stats.betabinom jax.scipy.stats.nbinom jax.scipy.stats.multinomial jax._src.scipy.stats.kde jax._src.scipy.stats.truncnorm jax.scipy.stats.poisson jax.scipy.stats.norm jax.scipy.stats.logistic jax.scipy.stats.geom jax.scipy.stats.gamma jax.scipy.stats.dirichlet jax.scipy.stats.beta jax.scipy.stats.bernoulli jax.scipy.stats.truncnorm jax.scipy.stats) as inherently stale


问:
Logstash error: open /usr/share/logstash/config/logstash.yml: permission denied
I have a logging repo that contains kibana, logstash, elasticsearch and a setup file, it is running on a server and works well, but now i want to run it on another server using docker but didn't run and it returns that the permission denied.

I have ran docker compose logs -f for setup it return the following: Could not resolve host. Is Elasticsearch running?
Note: it build correctly and show started but just filebeat and setup are up, logstash and elasticsearch are  not.


问:
ImageView and TextView assigned incorrectly in onBindViewHolder
Expected outcome:

I want to show only ImageView and TextView that corresponds to the current position e.g if I have

```<code>val icons = craftingExpandableList[position].requiredList?.icon
val amounts = craftingExpandableList[position].requiredList?.amount
</code>```

I want to show in RecyclerView only icons and amounts from current position, not all existing icons and amounts.

Current outcome:

I've added 2 items to my list. The problem is with the expandable list. It has values and images from both items that I've added previously. I suppose, that the problem is with for loop or with assigning values to the views.

CraftingExpandableListAdapter:

```<code>override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val iconListSize = craftingExpandableList[position].requiredList?.icon?.size
        val amountListSize = craftingExpandableList[position].requiredList?.amount?.size

        if (iconListSize!! > 0 || amountListSize!! > 0) {
            val icons = craftingExpandableList[position].requiredList?.icon
            val amounts = craftingExpandableList[position].requiredList?.amount

            // Create a LinearLayout to hold the views
            val verticalLinearLayout = LinearLayout(mContext)
            verticalLinearLayout.orientation = LinearLayout.VERTICAL
            verticalLinearLayout.setBackgroundColor(Color.parseColor("#002019"))

            for (i in 0 until iconListSize) {
                // Create the ImageView and TextView views
                val iconView = ImageView(mContext)
                val amountView = TextView(mContext)

                // Set the image resource and text for the views
                iconView.setImageResource(icons!![i])
                amountView.text = amounts!![i].toString()

                // Create a horizontal LinearLayout to hold the views
                val horizontalLinearLayout = LinearLayout(mContext)
                horizontalLinearLayout.orientation = LinearLayout.HORIZONTAL

                // Set the size and margins of the ImageView view
                val layoutParams = LinearLayout.LayoutParams(dpToPx(50), dpToPx(50))
                layoutParams.setMargins(dpToPx(16), dpToPx(16), 0, dpToPx(16))
                iconView.layoutParams = layoutParams

                // Set the margins of the TextView view
                val textLayoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                )
                textLayoutParams.gravity = Gravity.CENTER_VERTICAL
                textLayoutParams.setMargins(dpToPx(16), 0, 0, 0)
                amountView.layoutParams = textLayoutParams

                // Set the font of the TextView view
                // Set the typeface of the TextView view
                amountView.typeface = ResourcesCompat.getFont(mContext!!, R.font.roboto_bold)
                amountView.setTextColor(Color.parseColor("#F6E9E0"))

                // Add the views to the horizontal LinearLayout
                horizontalLinearLayout.addView(iconView)
                horizontalLinearLayout.addView(amountView)

                // Add the horizontal LinearLayout to the vertical LinearLayout
                verticalLinearLayout.addView(horizontalLinearLayout)
            }

            // Add the vertical LinearLayout to the holder's ViewGroup
            holder.viewGroup.addView(verticalLinearLayout)
        }
    }
</code>```

Additionally my CraftingListModel:

```<code>data class CraftingListModel(
    val icon: Int = 0,
    val name: String = "",
    val type: String = "",
    val requiredList: RequiredList? = null
)
    fun CraftingListModel.toListModel(): List<CraftingListModel> {
        val list = mutableListOf<CraftingListModel>()
        val requiredList = mutableListOf<RequiredList>()

        requiredList.add(RequiredList(listOf(R.raw.high_quality_metal_icon, R.raw.gears_icon), listOf(20, 5)))
        requiredList.add(RequiredList(listOf(R.raw.high_quality_metal_icon, R.raw.gears_icon), listOf(30, 5)))

        list.add(CraftingListModel(R.raw.armored_door_icon, "Armored Door", "Construction", requiredList[0]))
        list.add(CraftingListModel(R.raw.armored_double_door_icon, "Armored Double Door", "Construction", requiredList[1]))
        return list
    }
</code>```

and RequiredList:

```<code>data class RequiredList(
    val icon: List<Int> = emptyList(),
    val amount: List<Int> = emptyList()
)
</code>```

Body:
Expected outcome:

I want to show only ImageView and TextView that corresponds to the current position e.g if I have

val icons = craftingExpandableList[position].requiredList?.icon
val amounts = craftingExpandableList[position].requiredList?.amount

I want to show in RecyclerView only icons and amounts from current position, not all existing icons and amounts.

Current outcome:

I've added 2 items to my list. The problem is with the expandable list. It has values and images from both items that I've added previously. I suppose, that the problem is with for loop or with assigning values to the views.

CraftingExpandableListAdapter:

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val iconListSize = craftingExpandableList[position].requiredList?.icon?.size
        val amountListSize = craftingExpandableList[position].requiredList?.amount?.size

        if (iconListSize!! > 0 || amountListSize!! > 0) {
            val icons = craftingExpandableList[position].requiredList?.icon
            val amounts = craftingExpandableList[position].requiredList?.amount

            // Create a LinearLayout to hold the views
            val verticalLinearLayout = LinearLayout(mContext)
            verticalLinearLayout.orientation = LinearLayout.VERTICAL
            verticalLinearLayout.setBackgroundColor(Color.parseColor("#002019"))

            for (i in 0 until iconListSize) {
                // Create the ImageView and TextView views
                val iconView = ImageView(mContext)
                val amountView = TextView(mContext)

                // Set the image resource and text for the views
                iconView.setImageResource(icons!![i])
                amountView.text = amounts!![i].toString()

                // Create a horizontal LinearLayout to hold the views
                val horizontalLinearLayout = LinearLayout(mContext)
                horizontalLinearLayout.orientation = LinearLayout.HORIZONTAL

                // Set the size and margins of the ImageView view
                val layoutParams = LinearLayout.LayoutParams(dpToPx(50), dpToPx(50))
                layoutParams.setMargins(dpToPx(16), dpToPx(16), 0, dpToPx(16))
                iconView.layoutParams = layoutParams

                // Set the margins of the TextView view
                val textLayoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                )
                textLayoutParams.gravity = Gravity.CENTER_VERTICAL
                textLayoutParams.setMargins(dpToPx(16), 0, 0, 0)
                amountView.layoutParams = textLayoutParams

                // Set the font of the TextView view
                // Set the typeface of the TextView view
                amountView.typeface = ResourcesCompat.getFont(mContext!!, R.font.roboto_bold)
                amountView.setTextColor(Color.parseColor("#F6E9E0"))

                // Add the views to the horizontal LinearLayout
                horizontalLinearLayout.addView(iconView)
                horizontalLinearLayout.addView(amountView)

                // Add the horizontal LinearLayout to the vertical LinearLayout
                verticalLinearLayout.addView(horizontalLinearLayout)
            }

            // Add the vertical LinearLayout to the holder's ViewGroup
            holder.viewGroup.addView(verticalLinearLayout)
        }
    }

Additionally my CraftingListModel:

data class CraftingListModel(
    val icon: Int = 0,
    val name: String = "",
    val type: String = "",
    val requiredList: RequiredList? = null
)
    fun CraftingListModel.toListModel(): List<CraftingListModel> {
        val list = mutableListOf<CraftingListModel>()
        val requiredList = mutableListOf<RequiredList>()

        requiredList.add(RequiredList(listOf(R.raw.high_quality_metal_icon, R.raw.gears_icon), listOf(20, 5)))
        requiredList.add(RequiredList(listOf(R.raw.high_quality_metal_icon, R.raw.gears_icon), listOf(30, 5)))

        list.add(CraftingListModel(R.raw.armored_door_icon, "Armored Door", "Construction", requiredList[0]))
        list.add(CraftingListModel(R.raw.armored_double_door_icon, "Armored Double Door", "Construction", requiredList[1]))
        return list
    }

and RequiredList:

data class RequiredList(
    val icon: List<Int> = emptyList(),
    val amount: List<Int> = emptyList()
)


问:
Error: No value passed for parameter 'data' inside MainActivity (Jetpack compose)
Hello stack overflow community.

I would like to pass (data class AndroidItem) parameter to Nav function inside MainActivity Class without empty data, how can i do? it must be like this (data) not (data = ) and it shows error (No value passed for parameter 'data').
i have tried but unfortunately i could not do. I know that there is similar questions about this subject but i want to help me right now

Here my code:

```<code>class MainActivity : ComponentActivity() {

@OptIn(ExperimentalMaterialApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContent {
        Diwaanka2022Theme {
            // A surface container using the 'background' color from the theme
            Surface(
                modifier = Modifier.fillMaxSize(),
                color = MaterialTheme.colors.background
            ) {
                // here it must be like (data) only not (data = )
                Nav(data = )
            }
        }
    }
}
}

@Composable
data class AndroidItem(
    val ID: Int?,
    val ItemType: String?,
    val Price: Int?,
)

@Composable
fun Nav(data: AndroidItem) {
   val context = LocalContext.current
   val navController = rememberNavController()

   NavHost(
      navController = navController,
      startDestination = Screen.LoginScreen.route
   ) {

  composable(
     route = "Search_Screen_Details/{name}",
     arguments = listOf(
        navArgument(name = "name") {
           type = NavType.StringType
        }
     )
  ) {
        backStackEntry ->

     eee(
        navController,
        myName = backStackEntry.arguments?.getString("name"),
        data
     )
  }
 }
}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun eee(navController: NavController, myName: String?, data: AndroidItem) {

val scope = rememberCoroutineScope()
val scaffoldState = rememberBottomSheetScaffoldState()

BottomSheetScaffold(
    scaffoldState = scaffoldState,
    sheetPeekHeight = 0.dp,
    sheetContent = {

        Column(
            Modifier
                .fillMaxWidth()
                .height(500.dp)
                .padding(15.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {

            val context = LocalContext.current

            Text(
                text = data.ID.toString(),
                fontSize = 25.sp,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 20.dp),
                textAlign = TextAlign.Center

            )

            Button(onClick = {

            }) {
                Text(text = "welcome", fontSize = 22.sp)
            }
            Spacer(modifier = Modifier.height(10.dp))

        }
    }

) {

    Search_Screen_Details(navController, myName, scaffoldState)

}
}

@OptIn(ExperimentalMaterialApi::class)
@SuppressLint("MutableCollectionMutableState")
@Composable
fun Search_Screen_Details(
    navController: NavController,
    myName: String?,
    scaffoldState: BottomSheetScaffoldState
) {

Column(
    modifier = Modifier
        .fillMaxSize(),
    verticalArrangement = Arrangement.Center,
    horizontalAlignment = Alignment.CenterHorizontally
) {

    val context = LocalContext.current

    if(myName == "all") {

        val baseUrl = "https://adeega.xisaabso.online/Api/android_all_customers_all.php"
        val android = Android()

        val data = remember {
            mutableStateOf(Android())
        }

        val stringRequest = StringRequest(baseUrl, { it ->
            val gsonBuilder = GsonBuilder()
            val gson = gsonBuilder.create()
            gson.fromJson(it, Array<AndroidItem>::class.java)?.forEach {
                android.add(it)
            }
            data.value = android
        }, {
            Toast.makeText(context, it.toString(), Toast.LENGTH_LONG).show()
        }).apply {

            LazyColumn(
                contentPadding = PaddingValues(12.dp)
            ) {
                items(data.value) { item ->
                    MyCard(
                        data = item,
                        navController
                    )
                }
            } // END LazyColumn

        }// StringRequest

        val volleyRequest = Volley.newRequestQueue(context)
        volleyRequest.add(stringRequest)
    }

} // END Column

}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun MyCard(
    data : AndroidItem,
    navController: NavController,
    scaffoldState: BottomSheetScaffoldState
) {

Card(
    modifier = Modifier
        .fillMaxWidth(),
    RoundedCornerShape(10.dp),
    elevation = 5.dp,
) {
    Row(verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.Start,
        modifier = Modifier
            .padding(15.dp)
    ) {
        Column() {
            Text(
                text = data.ID.toString(),
                fontSize = 25.sp,
                fontWeight = FontWeight.Bold
            )

            Text(
                text = "Price: $" + data.Price,
                fontSize = 19.sp,
                fontWeight = FontWeight.Bold
            )
        }

    }//END Row

} //END Card

}
</code>```

Body:
Hello stack overflow community.

I would like to pass (data class AndroidItem) parameter to Nav function inside MainActivity Class without empty data, how can i do? it must be like this (data) not (data = ) and it shows error (No value passed for parameter 'data').
i have tried but unfortunately i could not do. I know that there is similar questions about this subject but i want to help me right now

Here my code:

class MainActivity : ComponentActivity() {

@OptIn(ExperimentalMaterialApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContent {
        Diwaanka2022Theme {
            // A surface container using the 'background' color from the theme
            Surface(
                modifier = Modifier.fillMaxSize(),
                color = MaterialTheme.colors.background
            ) {
                // here it must be like (data) only not (data = )
                Nav(data = )
            }
        }
    }
}
}

@Composable
data class AndroidItem(
    val ID: Int?,
    val ItemType: String?,
    val Price: Int?,
)

@Composable
fun Nav(data: AndroidItem) {
   val context = LocalContext.current
   val navController = rememberNavController()

   NavHost(
      navController = navController,
      startDestination = Screen.LoginScreen.route
   ) {

  composable(
     route = "Search_Screen_Details/{name}",
     arguments = listOf(
        navArgument(name = "name") {
           type = NavType.StringType
        }
     )
  ) {
        backStackEntry ->

     eee(
        navController,
        myName = backStackEntry.arguments?.getString("name"),
        data
     )
  }
 }
}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun eee(navController: NavController, myName: String?, data: AndroidItem) {

val scope = rememberCoroutineScope()
val scaffoldState = rememberBottomSheetScaffoldState()

BottomSheetScaffold(
    scaffoldState = scaffoldState,
    sheetPeekHeight = 0.dp,
    sheetContent = {

        Column(
            Modifier
                .fillMaxWidth()
                .height(500.dp)
                .padding(15.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {

            val context = LocalContext.current

            Text(
                text = data.ID.toString(),
                fontSize = 25.sp,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 20.dp),
                textAlign = TextAlign.Center

            )

            Button(onClick = {

            }) {
                Text(text = "welcome", fontSize = 22.sp)
            }
            Spacer(modifier = Modifier.height(10.dp))

        }
    }

) {

    Search_Screen_Details(navController, myName, scaffoldState)

}
}

@OptIn(ExperimentalMaterialApi::class)
@SuppressLint("MutableCollectionMutableState")
@Composable
fun Search_Screen_Details(
    navController: NavController,
    myName: String?,
    scaffoldState: BottomSheetScaffoldState
) {

Column(
    modifier = Modifier
        .fillMaxSize(),
    verticalArrangement = Arrangement.Center,
    horizontalAlignment = Alignment.CenterHorizontally
) {

    val context = LocalContext.current

    if(myName == "all") {

        val baseUrl = "https://adeega.xisaabso.online/Api/android_all_customers_all.php"
        val android = Android()

        val data = remember {
            mutableStateOf(Android())
        }

        val stringRequest = StringRequest(baseUrl, { it ->
            val gsonBuilder = GsonBuilder()
            val gson = gsonBuilder.create()
            gson.fromJson(it, Array<AndroidItem>::class.java)?.forEach {
                android.add(it)
            }
            data.value = android
        }, {
            Toast.makeText(context, it.toString(), Toast.LENGTH_LONG).show()
        }).apply {

            LazyColumn(
                contentPadding = PaddingValues(12.dp)
            ) {
                items(data.value) { item ->
                    MyCard(
                        data = item,
                        navController
                    )
                }
            } // END LazyColumn

        }// StringRequest

        val volleyRequest = Volley.newRequestQueue(context)
        volleyRequest.add(stringRequest)
    }

} // END Column

}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun MyCard(
    data : AndroidItem,
    navController: NavController,
    scaffoldState: BottomSheetScaffoldState
) {

Card(
    modifier = Modifier
        .fillMaxWidth(),
    RoundedCornerShape(10.dp),
    elevation = 5.dp,
) {
    Row(verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.Start,
        modifier = Modifier
            .padding(15.dp)
    ) {
        Column() {
            Text(
                text = data.ID.toString(),
                fontSize = 25.sp,
                fontWeight = FontWeight.Bold
            )

            Text(
                text = "Price: $" + data.Price,
                fontSize = 19.sp,
                fontWeight = FontWeight.Bold
            )
        }

    }//END Row

} //END Card

}


问:
Android Application Showing Crosses over the Google Map
I have developed 2 or 3 android application in which i used Google Maps. But today i find a problem. When i tap on the google map. Its showing multiple crosses over the map. Even every application those i have developed and have tested starts doing same thing. Can anyone suggest me some solutions.</p>

ContentLicense: CC BY-SA 3.0


问:
How can I solve this problem that two keyboard cursors in textfield?
https://i.stack.imgur.com/YKClg.png

I have multiple textfields and I have written code that expects that clearing index 0, i.e. the first textfield in the list, will set the focus back to the first textfield, but contrary to expectations, the cursor moves to the second field. text field. , and why do I see two cursors when I click on another textfield in this state?
`

```<code>import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:todolist/dataForm.dart';

class TodoCase extends StatefulWidget {
  final String title;
  const TodoCase({
    Key? key,
    required this.title,
  }) : super(key: key);

  @override
  State<TodoCase> createState() => _TodoCaseState();
}

class _TodoCaseState extends State<TodoCase> {
  List<ToDoDataForm> toDoLineList = [];
  final FocusScopeNode textListScopeNode = FocusScopeNode();
  final ScrollController toDoScrollController = ScrollController();
  List<TextEditingController> textEditController = [];
  List<FocusNode> keyBoardFocusNode = [];
  List<FocusNode> textFocusNode = [];
  Future<void> scrollToEnd() async {
    await Future.delayed(const Duration(milliseconds: 100));
    toDoScrollController.animateTo(
      toDoScrollController.position.maxScrollExtent,
      duration: const Duration(milliseconds: 400),
      curve: Curves.ease,
    );
  }

  @override
  Widget build(BuildContext context) {
    void addList() {
      setState(() {
        toDoLineList.add(ToDoDataForm(todoData: ""));
        scrollToEnd();
      });
    }

    Widget renderTextFormField(ToDoDataForm dataForm, int index) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Checkbox(
              value: dataForm.isDone,
              onChanged: (value) {
                setState(() {
                  dataForm.isDone = value!;
                });
              }),
          Flexible(
            child: KeyboardListener(
              focusNode: keyBoardFocusNode[index],
              onKeyEvent: (value) {
                if (value.logicalKey == LogicalKeyboardKey.backspace &&
                    dataForm.todoData.isEmpty) {
                  setState(() {
                    if (index != 0) {
                      textFocusNode[index - 1].requestFocus();
                      toDoLineList.removeAt(index);
                      textFocusNode.removeAt(index);
                      keyBoardFocusNode.removeAt(index);
                      textEditController.removeAt(index);
                    } else if (index == 0 && toDoLineList.length == 1) {
                      toDoLineList.removeAt(index);
                      textFocusNode.removeAt(index);
                      textEditController.removeAt(index);
                      keyBoardFocusNode.removeAt(index);
                    } else if (index == 0 && toDoLineList.length != 1) {
                      FocusScope.of(context)
                          .requestFocus(textFocusNode[index + 1]);
                      toDoLineList.removeAt(index);
                      textFocusNode.removeAt(index);
                      textEditController.removeAt(index);
                      keyBoardFocusNode.removeAt(index);
                    }
                  });
                  print(textFocusNode);
                }
              },
              child: TextField(
                decoration: const InputDecoration(
                  border: InputBorder.none,
                ),
                autofocus: false,
                controller: textEditController[index],
                focusNode: textFocusNode[index],
                onChanged: (value) {
                  //print('edit : $index');
                  dataForm.todoData = value;
                  //print(textFocusNode);
                },
              ),
            ),
          )
        ],
      );
    }

    return SizedBox(
      width: 180,
      height: 200,
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                widget.title,
                style: const TextStyle(
                  color: Colors.black,
                  fontSize: 24,
                ),
              ),
              IconButton(
                onPressed: addList,
                icon: const Icon(Icons.add),
                padding: EdgeInsets.zero,
                iconSize: 20,
              ),
            ],
          ),
          Container(
            height: 1,
            color: Colors.black,
          ),
          Expanded(
            child: ListView.builder(
              itemCount: toDoLineList.length,
              controller: toDoScrollController,
              itemBuilder: ((context, index) {
                if (textEditController.length - 1 < index) {
                  print(index);
                  textEditController.add(TextEditingController(
                      text: toDoLineList[index].todoData));
                  textFocusNode.add(FocusNode());
                  textFocusNode[index].unfocus();
                  keyBoardFocusNode.add(FocusNode());
                }
                print(index);
                print(textFocusNode);
                return renderTextFormField(toDoLineList[index], index);
              }),
            ),
          ),
        ],
      ),
    );
  }
}

</code>```

`

i try to focusNode List move to glover and textfield wrap FocusScopeNode and many try things but i can't solve this problem...

Body:
https://i.stack.imgur.com/YKClg.png

I have multiple textfields and I have written code that expects that clearing index 0, i.e. the first textfield in the list, will set the focus back to the first textfield, but contrary to expectations, the cursor moves to the second field. text field. , and why do I see two cursors when I click on another textfield in this state?
`

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:todolist/dataForm.dart';

class TodoCase extends StatefulWidget {
  final String title;
  const TodoCase({
    Key? key,
    required this.title,
  }) : super(key: key);

  @override
  State<TodoCase> createState() => _TodoCaseState();
}

class _TodoCaseState extends State<TodoCase> {
  List<ToDoDataForm> toDoLineList = [];
  final FocusScopeNode textListScopeNode = FocusScopeNode();
  final ScrollController toDoScrollController = ScrollController();
  List<TextEditingController> textEditController = [];
  List<FocusNode> keyBoardFocusNode = [];
  List<FocusNode> textFocusNode = [];
  Future<void> scrollToEnd() async {
    await Future.delayed(const Duration(milliseconds: 100));
    toDoScrollController.animateTo(
      toDoScrollController.position.maxScrollExtent,
      duration: const Duration(milliseconds: 400),
      curve: Curves.ease,
    );
  }

  @override
  Widget build(BuildContext context) {
    void addList() {
      setState(() {
        toDoLineList.add(ToDoDataForm(todoData: ""));
        scrollToEnd();
      });
    }

    Widget renderTextFormField(ToDoDataForm dataForm, int index) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Checkbox(
              value: dataForm.isDone,
              onChanged: (value) {
                setState(() {
                  dataForm.isDone = value!;
                });
              }),
          Flexible(
            child: KeyboardListener(
              focusNode: keyBoardFocusNode[index],
              onKeyEvent: (value) {
                if (value.logicalKey == LogicalKeyboardKey.backspace &&
                    dataForm.todoData.isEmpty) {
                  setState(() {
                    if (index != 0) {
                      textFocusNode[index - 1].requestFocus();
                      toDoLineList.removeAt(index);
                      textFocusNode.removeAt(index);
                      keyBoardFocusNode.removeAt(index);
                      textEditController.removeAt(index);
                    } else if (index == 0 && toDoLineList.length == 1) {
                      toDoLineList.removeAt(index);
                      textFocusNode.removeAt(index);
                      textEditController.removeAt(index);
                      keyBoardFocusNode.removeAt(index);
                    } else if (index == 0 && toDoLineList.length != 1) {
                      FocusScope.of(context)
                          .requestFocus(textFocusNode[index + 1]);
                      toDoLineList.removeAt(index);
                      textFocusNode.removeAt(index);
                      textEditController.removeAt(index);
                      keyBoardFocusNode.removeAt(index);
                    }
                  });
                  print(textFocusNode);
                }
              },
              child: TextField(
                decoration: const InputDecoration(
                  border: InputBorder.none,
                ),
                autofocus: false,
                controller: textEditController[index],
                focusNode: textFocusNode[index],
                onChanged: (value) {
                  //print('edit : $index');
                  dataForm.todoData = value;
                  //print(textFocusNode);
                },
              ),
            ),
          )
        ],
      );
    }

    return SizedBox(
      width: 180,
      height: 200,
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                widget.title,
                style: const TextStyle(
                  color: Colors.black,
                  fontSize: 24,
                ),
              ),
              IconButton(
                onPressed: addList,
                icon: const Icon(Icons.add),
                padding: EdgeInsets.zero,
                iconSize: 20,
              ),
            ],
          ),
          Container(
            height: 1,
            color: Colors.black,
          ),
          Expanded(
            child: ListView.builder(
              itemCount: toDoLineList.length,
              controller: toDoScrollController,
              itemBuilder: ((context, index) {
                if (textEditController.length - 1 < index) {
                  print(index);
                  textEditController.add(TextEditingController(
                      text: toDoLineList[index].todoData));
                  textFocusNode.add(FocusNode());
                  textFocusNode[index].unfocus();
                  keyBoardFocusNode.add(FocusNode());
                }
                print(index);
                print(textFocusNode);
                return renderTextFormField(toDoLineList[index], index);
              }),
            ),
          ),
        ],
      ),
    );
  }
}

`

i try to focusNode List move to glover and textfield wrap FocusScopeNode and many try things but i can't solve this problem...