问:
AWS Lambda Function(Python) and Issues with External packages: Cyptodome.Hash
So I have a test python lambda function that calls a simple method that relies on the py-algorand-sdk. This is my first time working with AWS Lambda, but my code has worked for a while now running locally in docker containers. I found with aws lambda function, to get my packages in my requirements.txt, I need to actually pull them and zip them up, then passing them as a lambda layer so that my lambda function will be able to use those external packages. BUT when I run my test function, something in the py-algorand-sdk is calling Cryptodome and that is causing an error I just can not get passed.

requirements.txt

```<code>requests==2.28.1
py-algorand-sdk==1.20.1
multihash==0.1.1
py-cid==0.3.0
pycryptodomex==3.16.0
</code>```

Dockerfile

```<code>FROM amazonlinux:2.0.20221210.0

COPY ./requirements.txt /tmp/requirements.txt
COPY ./mycode  /mycode

# Prepare amazonlinux image
RUN yum -y groupinstall "Development Tools" && \
    yum -y install gcc openssl-devel bzip2-devel libffi-devel wget build-essential python3-dev

# Get and unpack Python 3.9
RUN wget https://www.python.org/ftp/python/3.9.7/Python-3.9.7.tgz && \
    tar zxvf Python-3.9.7.tgz && \
    cd Python-3.9.7/ && \
    ./configure && \
    make && \
    make altinstall && \
    cd .. && \
    rm Python-3.9.7.tgz

# Pull the requirements and install
RUN python3.9 -m venv /requirements && \
    /requirements/bin/pip3.9 install --upgrade pip && \
    /requirements/bin/pip3.9 install -r /tmp/requirements.txt -t ./python

# Copy in our code as module and zip
RUN cp -rf /mycode  ./python/ && \
    zip -r python_layer.zip ./python/
</code>```

At this point I copy up the zip file into aws as a layer and test my lambda function... but for days I keep getting the same error, even after trying everything I could find online.

```<code>Cannot load native module 'Cryptodome.Hash._SHA512': Not found '_SHA512.cpython-39-x86_64-linux-gnu.so'...
</code>```

I have tried using pycrypto, pycryptodome, pycryptodomex; I have tried removing the target flag and installing everything directly in the venv and copying all the site-packages into a zip. Nothing seems to work, so I must be missing something.

Any help would save me from pulling out any more hair.

Full Error

```<code>Response
{
  "errorMessage": "Cannot load native module 'Cryptodome.Hash._SHA512': Not found '_SHA512.cpython-39-x86_64-linux-gnu.so', Cannot load '_SHA512.abi3.so': /opt/python/Cryptodome/Util/../Hash/_SHA512.abi3.so: cannot open shared object file: No such file or directory, Not found '_SHA512.so'",
  "errorType": "OSError",
  "requestId": "",
  "stackTrace": [
    "  File \"/var/lang/lib/python3.9/importlib/__init__.py\", line 127, in import_module\n    return _bootstrap._gcd_import(name[level:], package, level)\n",
    "  File \"<frozen importlib._bootstrap>\", line 1030, in _gcd_import\n",
    "  File \"<frozen importlib._bootstrap>\", line 1007, in _find_and_load\n",
    "  File \"<frozen importlib._bootstrap>\", line 986, in _find_and_load_unlocked\n",
    "  File \"<frozen importlib._bootstrap>\", line 680, in _load_unlocked\n",
    "  File \"<frozen importlib._bootstrap_external>\", line 850, in exec_module\n",
    "  File \"<frozen importlib._bootstrap>\", line 228, in _call_with_frames_removed\n",
    "  File \"/var/task/lambda_function.py\", line 3, in <module>\n    from mycode import *\n",
    "  File \"/opt/python/mycode/__init__.py\", line 1, in <module>\n    from . import transactions\n",
    "  File \"/opt/python/mycode/transactions.py\", line 5, in <module>\n    from algosdk.v2client import algod\n",
    "  File \"/opt/python/algosdk/__init__.py\", line 1, in <module>\n    from . import abi\n",
    "  File \"/opt/python/algosdk/abi/__init__.py\", line 6, in <module>\n    from algosdk.abi.address_type import AddressType\n",
    "  File \"/opt/python/algosdk/abi/address_type.py\", line 8, in <module>\n    from algosdk import encoding\n",
    "  File \"/opt/python/algosdk/encoding.py\", line 7, in <module>\n    from Cryptodome.Hash import SHA512\n",
    "  File \"/opt/python/Cryptodome/Hash/SHA512.py\", line 29, in <module>\n    _raw_sha512_lib = load_pycryptodome_raw_lib(\"Cryptodome.Hash._SHA512\",\n",
    "  File \"/opt/python/Cryptodome/Util/_raw_api.py\", line 309, in load_pycryptodome_raw_lib\n    raise OSError(\"Cannot load native module '%s': %s\" % (name, \", \".join(attempts)))\n"
  ]
}
</code>```

Body:
So I have a test python lambda function that calls a simple method that relies on the py-algorand-sdk. This is my first time working with AWS Lambda, but my code has worked for a while now running locally in docker containers. I found with aws lambda function, to get my packages in my requirements.txt, I need to actually pull them and zip them up, then passing them as a lambda layer so that my lambda function will be able to use those external packages. BUT when I run my test function, something in the py-algorand-sdk is calling Cryptodome and that is causing an error I just can not get passed.

requirements.txt

requests==2.28.1
py-algorand-sdk==1.20.1
multihash==0.1.1
py-cid==0.3.0
pycryptodomex==3.16.0

Dockerfile

FROM amazonlinux:2.0.20221210.0

COPY ./requirements.txt /tmp/requirements.txt
COPY ./mycode  /mycode

# Prepare amazonlinux image
RUN yum -y groupinstall "Development Tools" && \
    yum -y install gcc openssl-devel bzip2-devel libffi-devel wget build-essential python3-dev

# Get and unpack Python 3.9
RUN wget https://www.python.org/ftp/python/3.9.7/Python-3.9.7.tgz && \
    tar zxvf Python-3.9.7.tgz && \
    cd Python-3.9.7/ && \
    ./configure && \
    make && \
    make altinstall && \
    cd .. && \
    rm Python-3.9.7.tgz

# Pull the requirements and install
RUN python3.9 -m venv /requirements && \
    /requirements/bin/pip3.9 install --upgrade pip && \
    /requirements/bin/pip3.9 install -r /tmp/requirements.txt -t ./python

# Copy in our code as module and zip
RUN cp -rf /mycode  ./python/ && \
    zip -r python_layer.zip ./python/

At this point I copy up the zip file into aws as a layer and test my lambda function... but for days I keep getting the same error, even after trying everything I could find online.

Cannot load native module 'Cryptodome.Hash._SHA512': Not found '_SHA512.cpython-39-x86_64-linux-gnu.so'...

I have tried using pycrypto, pycryptodome, pycryptodomex; I have tried removing the target flag and installing everything directly in the venv and copying all the site-packages into a zip. Nothing seems to work, so I must be missing something.

Any help would save me from pulling out any more hair.

Full Error

Response
{
  "errorMessage": "Cannot load native module 'Cryptodome.Hash._SHA512': Not found '_SHA512.cpython-39-x86_64-linux-gnu.so', Cannot load '_SHA512.abi3.so': /opt/python/Cryptodome/Util/../Hash/_SHA512.abi3.so: cannot open shared object file: No such file or directory, Not found '_SHA512.so'",
  "errorType": "OSError",
  "requestId": "",
  "stackTrace": [
    "  File \"/var/lang/lib/python3.9/importlib/__init__.py\", line 127, in import_module\n    return _bootstrap._gcd_import(name[level:], package, level)\n",
    "  File \"<frozen importlib._bootstrap>\", line 1030, in _gcd_import\n",
    "  File \"<frozen importlib._bootstrap>\", line 1007, in _find_and_load\n",
    "  File \"<frozen importlib._bootstrap>\", line 986, in _find_and_load_unlocked\n",
    "  File \"<frozen importlib._bootstrap>\", line 680, in _load_unlocked\n",
    "  File \"<frozen importlib._bootstrap_external>\", line 850, in exec_module\n",
    "  File \"<frozen importlib._bootstrap>\", line 228, in _call_with_frames_removed\n",
    "  File \"/var/task/lambda_function.py\", line 3, in <module>\n    from mycode import *\n",
    "  File \"/opt/python/mycode/__init__.py\", line 1, in <module>\n    from . import transactions\n",
    "  File \"/opt/python/mycode/transactions.py\", line 5, in <module>\n    from algosdk.v2client import algod\n",
    "  File \"/opt/python/algosdk/__init__.py\", line 1, in <module>\n    from . import abi\n",
    "  File \"/opt/python/algosdk/abi/__init__.py\", line 6, in <module>\n    from algosdk.abi.address_type import AddressType\n",
    "  File \"/opt/python/algosdk/abi/address_type.py\", line 8, in <module>\n    from algosdk import encoding\n",
    "  File \"/opt/python/algosdk/encoding.py\", line 7, in <module>\n    from Cryptodome.Hash import SHA512\n",
    "  File \"/opt/python/Cryptodome/Hash/SHA512.py\", line 29, in <module>\n    _raw_sha512_lib = load_pycryptodome_raw_lib(\"Cryptodome.Hash._SHA512\",\n",
    "  File \"/opt/python/Cryptodome/Util/_raw_api.py\", line 309, in load_pycryptodome_raw_lib\n    raise OSError(\"Cannot load native module '%s': %s\" % (name, \", \".join(attempts)))\n"
  ]
}


来源: stackexchange

问:
how to custom select component with react hook form
```<code>import React, { useState } from "react";

export default function TestDropdown() {
  const [isOpen, setIsOpen] = useState(false);
  const [selected, setSelected] = useState("전체");

  const menu = ["menu1", "menu2", "menu3", "menu4", "menu5"];

  return (
    <>
      <div onClick={() => setIsOpen(true)}>{selected}</div>
      {isOpen && (
        <ul>
          {menu.map((item, i) => (
            <li
              key={i}
              onClick={() => {
                setSelected(item);
                setIsOpen(false);
              }}
            >
              menu1
            </li>
          ))}
        </ul>
      )}
    </>
  );
}
</code>```

I want to use react hook form by making select components with custom without using select tag.

I want to use the register of the reaction hook form for the custom select component I made.

I'd appreciate it if you could tell me a good way.

ContentLicense: CC BY-SA 4.0

Body:
import React, { useState } from "react";

export default function TestDropdown() {
  const [isOpen, setIsOpen] = useState(false);
  const [selected, setSelected] = useState("전체");

  const menu = ["menu1", "menu2", "menu3", "menu4", "menu5"];

  return (
    <>

 setIsOpen(true)}>{selected}

      {isOpen && (

          {menu.map((item, i) => (

 {
                setSelected(item);
                setIsOpen(false);
              }}
            >
              menu1

          ))}

      )}
    </>
  );
}

I want to use react hook form by making select components with custom without using select tag.

I want to use the register of the reaction hook form for the custom select component I made.

I'd appreciate it if you could tell me a good way.


问:
I'm using Next.ts AWS api gateway, lambda, and DynamoDB to go serverless. I'm getting an unexplainable error, chatGPT can't
```<code>AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
</code>```

code "ERR_BAD_REQUEST"
config

:  {transitional: {…}, adapter: Array(2), transformRequest: Array(1),
transformResponse: Array(1), timeout: 0, …} message :  "Request failed
with status code 400" name :  "AxiosError" request :  XMLHttpRequest
{onreadystatechange: null, readyState: 4, timeout: 0, withCredentials:
false, upload: XMLHttpRequestUpload, …} response :  {data: 'Unexpected
token u in JSON at position 0', status: 400, statusText: '', headers:
AxiosHeaders, config: {…}, …} stack :  "AxiosError: Request failed
with status code 400\n    at settle
(webpack-internal:///./node_modules/axios/lib/core/settle.js:24:12)\n
at XMLHttpRequest.onloadend
(webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:117:66)"
[[Prototype]] :  Error

This is the error code, I don't know how else to check the response in lambda to see where this "u" is.

I've swapped to fetch, tried stringing and using those strings in the api gateway test to the same error. No clue where this u is

Body:
AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}

code "ERR_BAD_REQUEST"
config

:  {transitional: {…}, adapter: Array(2), transformRequest: Array(1),
transformResponse: Array(1), timeout: 0, …} message :  "Request failed
with status code 400" name :  "AxiosError" request :  XMLHttpRequest
{onreadystatechange: null, readyState: 4, timeout: 0, withCredentials:
false, upload: XMLHttpRequestUpload, …} response :  {data: 'Unexpected
token u in JSON at position 0', status: 400, statusText: '', headers:
AxiosHeaders, config: {…}, …} stack :  "AxiosError: Request failed
with status code 400\n    at settle
(webpack-internal:///./node_modules/axios/lib/core/settle.js:24:12)\n
at XMLHttpRequest.onloadend
(webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:117:66)"
[[Prototype]] :  Error

This is the error code, I don't know how else to check the response in lambda to see where this "u" is.

I've swapped to fetch, tried stringing and using those strings in the api gateway test to the same error. No clue where this u is


问:
mathematical operations inside of variables in python
heres an image of the problem in a better formatvariabl =

```<code>sta = 2+2

ste = 1+1

sta + ste
</code>```

print (variabl)

how can i make it so that when i print "varibl" a number 6 shows up on the console?
im trying to make it so that the operations inside of the variable are stored within it so that when i print them, the answer to all of them shows up on the console.

my plan was to make two variables inside of "variabl", one that contains the operation 2+2 and another one that contains the operation 1+1, at the end having the result of both being added together stored inside of "variabl".

is this possible?

ive tried using parenthesis and other types of symbols to try and find a way of connecting all parts of the varible together

Body:
heres an image of the problem in a better formatvariabl =

sta = 2+2

ste = 1+1

sta + ste

print (variabl)

how can i make it so that when i print "varibl" a number 6 shows up on the console?
im trying to make it so that the operations inside of the variable are stored within it so that when i print them, the answer to all of them shows up on the console.

my plan was to make two variables inside of "variabl", one that contains the operation 2+2 and another one that contains the operation 1+1, at the end having the result of both being added together stored inside of "variabl".

is this possible?

ive tried using parenthesis and other types of symbols to try and find a way of connecting all parts of the varible together


问:
Victory Chart y axis is overflowing when the numbers get big
I'm having an issue with Victory Chart where the y axis labels are overflowing when the numbers get big. This is a design example to achieve.

This is my implementation (Ignore the bars)

There's a slider above the chart that can change the chart data dynamically. And if the numbers get big, it will look like this

Here's my chart implementation

<Row>
    <VictoryChart
        domainPadding={{ x: 20 }}
        padding={{
            top: 50,
            bottom: 50,
            right: 0,
            left: 50,
        }}
        theme={VictoryTheme.material}
    >
        <VictoryAxis
            tickValues={[0, 11]}
            tickFormat={[currentYear, currentYear + 5]}
            style={{
                axis: { stroke: 'none' },
                ticks: { stroke: 'none' },
                grid: { stroke: 'transparent' },
                tickLabels: {
                    fontFamily: 'Roboto',
                    fill: '#a5a5a5',
                    fontSize: 16,
                },
                axisLabel: {
                    fontFamily: 'Roboto',
                },
            }}
        />
        <VictoryAxis
            dependentAxis
            fixLabelOverlap
            style={{
                axis: { stroke: 'none' },
                tickLabels: {
                    fontFamily: 'Roboto',
                    fontSize: 11,
                    fill: '#d5d5d5',
                },
                axisLabel: {
                    fontFamily: 'Roboto',
                },
            }}
            // tickFormat specifies how ticks should be displayed
            tickFormat={(x) =>
                `${formatCurrency(x, 0, 'EUR')}`
            }
        />
        <VictoryBar
            barWidth={21}
            style={{
                data: {
                    fill: '#DCE5FF',
                },
            }}
            cornerRadius={{
                top: 5,
                bottom: 5,
            }}
            data={chartData}
        />
    </VictoryChart>
</Row>```

I wonder if there's any solution for this. Maybe moving the y axis a little bit to the right like in the design so that the x axis will look like a full width.

Body:
I'm having an issue with Victory Chart where the y axis labels are overflowing when the numbers get big. This is a design example to achieve.

This is my implementation (Ignore the bars)

There's a slider above the chart that can change the chart data dynamically. And if the numbers get big, it will look like this

Here's my chart implementation

<Row>
    <VictoryChart
        domainPadding={{ x: 20 }}
        padding={{
            top: 50,
            bottom: 50,
            right: 0,
            left: 50,
        }}
        theme={VictoryTheme.material}
    >
        <VictoryAxis
            tickValues={[0, 11]}
            tickFormat={[currentYear, currentYear + 5]}
            style={{
                axis: { stroke: 'none' },
                ticks: { stroke: 'none' },
                grid: { stroke: 'transparent' },
                tickLabels: {
                    fontFamily: 'Roboto',
                    fill: '#a5a5a5',
                    fontSize: 16,
                },
                axisLabel: {
                    fontFamily: 'Roboto',
                },
            }}
        />
        <VictoryAxis
            dependentAxis
            fixLabelOverlap
            style={{
                axis: { stroke: 'none' },
                tickLabels: {
                    fontFamily: 'Roboto',
                    fontSize: 11,
                    fill: '#d5d5d5',
                },
                axisLabel: {
                    fontFamily: 'Roboto',
                },
            }}
            // tickFormat specifies how ticks should be displayed
            tickFormat={(x) =>
                `${formatCurrency(x, 0, 'EUR')}`
            }
        />
        <VictoryBar
            barWidth={21}
            style={{
                data: {
                    fill: '#DCE5FF',
                },
            }}
            cornerRadius={{
                top: 5,
                bottom: 5,
            }}
            data={chartData}
        />
    </VictoryChart>
</Row>

I wonder if there's any solution for this. Maybe moving the y axis a little bit to the right like in the design so that the x axis will look like a full width.


问:
How to use a spring boost web service project from another one
I'm kind of new to java / Spring boot,
I'm building a microservice solution and I have two projects, lets's call both apps mainApp and eventApp

both mainApp and eventApp are spring boot web REST API's.

the eventApp has a simple CRUD (@RestController, @Service, @Repository, etc) that manage all the event related stuff.

from the MainApp I need to be able to create, update, fetch the events from the EventApp

something like:

```<code>Event newEvent = EventApp.EventService.createEvent(...somePayload)
</code>```

but I need to keep both EventApp and MainApp as webapps (users should be able to interact with the EventApp CRUD itself)

how can I achieve this?

Body:
I'm kind of new to java / Spring boot,
I'm building a microservice solution and I have two projects, lets's call both apps mainApp and eventApp

both mainApp and eventApp are spring boot web REST API's.

the eventApp has a simple CRUD (@RestController, @Service, @Repository, etc) that manage all the event related stuff.

from the MainApp I need to be able to create, update, fetch the events from the EventApp

something like:

Event newEvent = EventApp.EventService.createEvent(...somePayload)

but I need to keep both EventApp and MainApp as webapps (users should be able to interact with the EventApp CRUD itself)

how can I achieve this?


问:
Redirect by url suffix to specific html file
What I want is simple I guess:

I want it that when the user types something like: myurl.com/this_suffix

It automatically redirects to something else like:

myurl.com/final_adress.html

My first question is if this must be handled in the server for example via the .htaccess file or there is a way to do it purely with javascript?

And if server config is needed how can I do it in a nginx server which don't uses .htaccess file like apache.

Thanks in advance.


问:
Sublists of lists in Python
I wanted to know how do append function work for sublists of lists in Python

If we create a list as:

```<code>a =  [[]]*4
</code>```

and append as:

```<code>a[0].append(10)
</code>```

The output of printing a was:

```<code>[[10],[10],[10,[10]]
</code>```

Why does 10 get copied in all four sublists while it should just for the first one??? i.e.

```<code>[[10],[],[],[]]
</code>```

Title: Sublists of lists in Python

Body:
I wanted to know how do append function work for sublists of lists in Python

If we create a list as:

a =  [[]]*4

and append as:

a[0].append(10)

The output of printing a was:

[[10],[10],[10,[10]]

Why does 10 get copied in all four sublists while it should just for the first one??? i.e.

[[10],[],[],[]]


问:
Paramiko Doesn connect on Solaris 11
On Linux & Solaris 10, the following code works but if it is Solaris 11, it throws the following error message paramiko.ssh_exception.AuthenticationException: Authentication failed.. The credentials/authentication details are correct. The host, username and password are all correct but for some reason it complains about Authentication failure. I know that Solaris 11 has much more beefed up security. Is there any thing else I need to add to my code to get this to work? (more details below):

```<code>def setup_remote_gateway_client_connection(self, gateway_host, gateway_username, gateway_password, client_host, client_username, client_password, gateway_port=22, client_port=22):
        self.gateway_host=paramiko.SSHClient()
        self.gateway_host.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.gateway_host.connect(gateway_host, username=gateway_username, password=gateway_password )

        gateway_transport = self.gateway_host.get_transport()
        src_addr = (gateway_host, gateway_port)
        dest_addr = (client_host, client_port)
        gateway_channel = gateway_transport.open_channel("direct-tcpip", dest_addr, src_addr)

        client_host=paramiko.SSHClient()
        client_host.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client_host.connect(client_host, username=client_username, password=client_password, sock=gateway_channel)

        stdin, stdout, stderr = client_host.exec_command('ls -la')
        for line in stdout.read().split(b'\n'):
          print(str(line))

        stdin, stdout, stderr = client_host.exec_command('hostname')
        for line in stdout.read().split(b'\n'):
          print(str(line))

        client_host.close()
        self.gateway_host.close()
</code>```

Upon execution, I get the following:

```<code>fixture.py:28: in setup_remote_gateway_client_connection
    client_host.connect(client_host, username=client_username, password=client_password, sock=gateway_channel)
/usr/local/lib/python3.10/site-packages/paramiko/client.py:450: in connect
    self._auth(
/usr/local/lib/python3.10/site-packages/paramiko/client.py:781: in _auth
    raise saved_exception
/usr/local/lib/python3.10/site-packages/paramiko/client.py:768: in _auth
    self._transport.auth_password(username, password)
/usr/local/lib/python3.10/site-packages/paramiko/transport.py:1564: in auth_password
    return self.auth_handler.wait_for_response(my_event)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <paramiko.auth_handler.AuthHandler object at 0x107691ae0>
event = <threading.Event object at 0x107691a20>

    def wait_for_response(self, event):
        max_ts = None
        if self.transport.auth_timeout is not None:
            max_ts = time.time() + self.transport.auth_timeout
        while True:
            event.wait(0.1)
            if not self.transport.is_active():
                e = self.transport.get_exception()
                if (e is None) or issubclass(e.__class__, EOFError):
                    e = AuthenticationException("Authentication failed.")
                raise e
            if event.is_set():
                break
            if max_ts is not None and max_ts <= time.time():
                raise AuthenticationException("Authentication timeout.")

        if not self.is_authenticated():
            e = self.transport.get_exception()
            if e is None:
                e = AuthenticationException("Authentication failed.")
            # this is horrible.  Python Exception isn't yet descended from
            # object, so type(e) won't work. :(
            if issubclass(e.__class__, PartialAuthentication):
                return e.allowed_types
>           raise e
E           paramiko.ssh_exception.AuthenticationException: Authentication failed.

/usr/local/lib/python3.10/site-packages/paramiko/auth_handler.py:259: AuthenticationException
</code>```

Title: Paramiko Doesn connect on Solaris 11

Body:
On Linux & Solaris 10, the following code works but if it is Solaris 11, it throws the following error message paramiko.ssh_exception.AuthenticationException: Authentication failed.. The credentials/authentication details are correct. The host, username and password are all correct but for some reason it complains about Authentication failure. I know that Solaris 11 has much more beefed up security. Is there any thing else I need to add to my code to get this to work? (more details below):

def setup_remote_gateway_client_connection(self, gateway_host, gateway_username, gateway_password, client_host, client_username, client_password, gateway_port=22, client_port=22):
        self.gateway_host=paramiko.SSHClient()
        self.gateway_host.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.gateway_host.connect(gateway_host, username=gateway_username, password=gateway_password )

        gateway_transport = self.gateway_host.get_transport()
        src_addr = (gateway_host, gateway_port)
        dest_addr = (client_host, client_port)
        gateway_channel = gateway_transport.open_channel("direct-tcpip", dest_addr, src_addr)

        client_host=paramiko.SSHClient()
        client_host.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client_host.connect(client_host, username=client_username, password=client_password, sock=gateway_channel)

        stdin, stdout, stderr = client_host.exec_command('ls -la')
        for line in stdout.read().split(b'\n'):
          print(str(line))

        stdin, stdout, stderr = client_host.exec_command('hostname')
        for line in stdout.read().split(b'\n'):
          print(str(line))

        client_host.close()
        self.gateway_host.close()

Upon execution, I get the following:

fixture.py:28: in setup_remote_gateway_client_connection
    client_host.connect(client_host, username=client_username, password=client_password, sock=gateway_channel)
/usr/local/lib/python3.10/site-packages/paramiko/client.py:450: in connect
    self._auth(
/usr/local/lib/python3.10/site-packages/paramiko/client.py:781: in _auth
    raise saved_exception
/usr/local/lib/python3.10/site-packages/paramiko/client.py:768: in _auth
    self._transport.auth_password(username, password)
/usr/local/lib/python3.10/site-packages/paramiko/transport.py:1564: in auth_password
    return self.auth_handler.wait_for_response(my_event)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <paramiko.auth_handler.AuthHandler object at 0x107691ae0>
event = <threading.Event object at 0x107691a20>

    def wait_for_response(self, event):
        max_ts = None
        if self.transport.auth_timeout is not None:
            max_ts = time.time() + self.transport.auth_timeout
        while True:
            event.wait(0.1)
            if not self.transport.is_active():
                e = self.transport.get_exception()
                if (e is None) or issubclass(e.__class__, EOFError):
                    e = AuthenticationException("Authentication failed.")
                raise e
            if event.is_set():
                break
            if max_ts is not None and max_ts <= time.time():
                raise AuthenticationException("Authentication timeout.")

        if not self.is_authenticated():
            e = self.transport.get_exception()
            if e is None:
                e = AuthenticationException("Authentication failed.")
            # this is horrible.  Python Exception isn't yet descended from
            # object, so type(e) won't work. :(
            if issubclass(e.__class__, PartialAuthentication):
                return e.allowed_types
>           raise e
E           paramiko.ssh_exception.AuthenticationException: Authentication failed.

/usr/local/lib/python3.10/site-packages/paramiko/auth_handler.py:259: AuthenticationException


问:
Browserstack integration to cucumber java
I faced some problem while integrate browserstack with cucumber java. apps is already open after i run the code. but there no action after app is open until its timeout. Here is the details regarding my problem
enter image description here

io.appium.java_client.remote.AppiumCommandExecutor$1 lambda$0
INFO: Detected dialect: OSS
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by net.sf.cglib.core.ReflectUtils$1 (file:/Users/.m2/repository/cglib/cglib/3.3.0/cglib-3.3.0.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of net.sf.cglib.core.ReflectUtils$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

```<code>public static void initializeDriver() throws Exception{
    DesiredCapabilities caps = new DesiredCapabilities();

    // Set your access credentials
    caps.setCapability("browserstack.user", "....");
    caps.setCapability("browserstack.key", "....");

    //Set URL of the application under test
    caps.setCapability("app", "....");

    // Specify device and os_version for testing
    caps.setCapability("device", "Samsung Galaxy S22");
    caps.setCapability("os_version", "12.0");

    // Set other BrowserStack capabilities
    caps.setCapability("project", "First Java Project");
    caps.setCapability("build", "....");
    caps.setCapability("name", "first_test");

    AndroidDriver<AndroidElement> driver = new AndroidDriver<AndroidElement>(
            new URL("http://hub.browserstack.com/wd/hub"), caps);
}
</code>```
```<code>    @Before
    public void initialize() throws Exception {
        GlobalParams params = new GlobalParams();
        params.initializeGlobalParams();

        ThreadContext.put("ROUTINGKEY", params.getPlatformName() + "_"
                + params.getDeviceName());

        new ServerManager().startServer();
        new DriverManager().initializeDriver();
    }

    @After
    public void quit(Scenario scenario) throws IOException {
        DriverManager driverManager = new DriverManager();
        if(driverManager.getDriver() != null){
            driverManager.getDriver().quit();
            driverManager.setDriver(null);
        }
        ServerManager serverManager = new ServerManager();
        if(serverManager.getServer() != null){
            serverManager.getServer().stop();
        }
</code>```

Should be apps is do the action after open.

Body:
I faced some problem while integrate browserstack with cucumber java. apps is already open after i run the code. but there no action after app is open until its timeout. Here is the details regarding my problem
enter image description here

io.appium.java_client.remote.AppiumCommandExecutor$1 lambda$0
INFO: Detected dialect: OSS
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by net.sf.cglib.core.ReflectUtils$1 (file:/Users/.m2/repository/cglib/cglib/3.3.0/cglib-3.3.0.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of net.sf.cglib.core.ReflectUtils$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

public static void initializeDriver() throws Exception{
    DesiredCapabilities caps = new DesiredCapabilities();

    // Set your access credentials
    caps.setCapability("browserstack.user", "....");
    caps.setCapability("browserstack.key", "....");

    //Set URL of the application under test
    caps.setCapability("app", "....");

    // Specify device and os_version for testing
    caps.setCapability("device", "Samsung Galaxy S22");
    caps.setCapability("os_version", "12.0");

    // Set other BrowserStack capabilities
    caps.setCapability("project", "First Java Project");
    caps.setCapability("build", "....");
    caps.setCapability("name", "first_test");

    AndroidDriver<AndroidElement> driver = new AndroidDriver<AndroidElement>(
            new URL("http://hub.browserstack.com/wd/hub"), caps);
}

    @Before
    public void initialize() throws Exception {
        GlobalParams params = new GlobalParams();
        params.initializeGlobalParams();

        ThreadContext.put("ROUTINGKEY", params.getPlatformName() + "_"
                + params.getDeviceName());

        new ServerManager().startServer();
        new DriverManager().initializeDriver();
    }

    @After
    public void quit(Scenario scenario) throws IOException {
        DriverManager driverManager = new DriverManager();
        if(driverManager.getDriver() != null){
            driverManager.getDriver().quit();
            driverManager.setDriver(null);
        }
        ServerManager serverManager = new ServerManager();
        if(serverManager.getServer() != null){
            serverManager.getServer().stop();
        }

Should be apps is do the action after open.


问:
Querying a database view in Postgres without a primary key using Spring JPA
I have a view that I am trying to access from a postgres database.  The view does not contain a primary key, nor do the columns singly or compositely act as candidates for a primary key.  The many articles I have read propose using uuid, but since I cannot modify the view this is not an option.

Another thing I have read is mapping the view to a POJO class, but I am not quite sure I understand what that means.

For example, let's say for simplicity's sake I have a view that has the following information:

first_name
last_name
DOB

How would I map this view to a POJO class to now contain all the above information plus an ID which can serve as a primary key?  It's important to note, that I should not in any way modify the view in anyway. I assume since it's a view I wouldn't be able to.  If the view had an ID/PK I would just use the annotation @IMMUTABLE and have only getters.

Does this approach mean I am duplicating information in a new table with data from the view for the sole purpose of adding a primary key?

If these are the only two solutions available, can a list of steps be provided to implement the second solution?

Finally, is there a better way I can achieve querying a view without a primary key, than the two solutions mentioned above?


问:
Error while compiling APK file: EAS BUILD
I'm using EXPO CLI to develop app and to create test-build, i run this command:
eas build -p android --profile preview
and it stops after few minutes with this/or similar message:

Compressing project files Error: Cannot copy a socket file: /Users/mac/Library/Group  Containers/BJ4HAAB9B3.ZoomClient3rd/s.zzhost
It is always issue with compressing files stage.
How to solve it?

I tried change directory and other similar command.
Is it possible that mistake is in app?


问:
R: Error in cpp_pdf_split(input, output, password) :
I am working with the R programming language.

I was able to import a large pdf (each page is a scanned photocopy) into R:

```<code>library(pdftools)
library(qpdf)
pdf_text <- pdf_text("tess.pdf")
</code>```

I then tried to split this file and save it as multiple files:

```<code># Set the input and output file paths
input <- "C:/Users/me/OneDrive/Documents/tess.pdf"
output <- "C:/Users/me/OneDrive/Documents/tess_page"

# Split the input PDF file into multiple files
qpdf::pdf_split(input, output)
</code>```

But I am getting the following error:

```<code>Error in cpp_pdf_split(input, output, password) :
</code>```

open C:/Users/me/OneDrive/Documents_0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001.pdf: No such file or directory

I am not sure why this problem is occurring as this directory corresponds to my working directory:

```<code>> getwd()
[1] "C:/Users/me/OneDrive/Documents"
</code>```

I found a previous post (R not allowing to write documents, Error in cpp_pdf_select(input, output, pages, password)) with a similar problem, but I could not seem to figure out how to apply this logic to my problem.

Can someone please show me how I can fix this problem?

Thanks!

Body:
I am working with the R programming language.

I was able to import a large pdf (each page is a scanned photocopy) into R:

library(pdftools)
library(qpdf)
pdf_text <- pdf_text("tess.pdf")

I then tried to split this file and save it as multiple files:

# Set the input and output file paths
input <- "C:/Users/me/OneDrive/Documents/tess.pdf"
output <- "C:/Users/me/OneDrive/Documents/tess_page"

# Split the input PDF file into multiple files
qpdf::pdf_split(input, output)

But I am getting the following error:

Error in cpp_pdf_split(input, output, password) :

open C:/Users/me/OneDrive/Documents_0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001.pdf: No such file or directory

I am not sure why this problem is occurring as this directory corresponds to my working directory:

> getwd()
[1] "C:/Users/me/OneDrive/Documents"

I found a previous post (R not allowing to write documents, Error in cpp_pdf_select(input, output, pages, password)) with a similar problem, but I could not seem to figure out how to apply this logic to my problem.

Can someone please show me how I can fix this problem?

Thanks!


问:
how can I find the error of the interpolation results using Python?
I have data for X axis and Y axis,
then I have to find some Y points by inputting some X values using interpolation.
how can I find the error of the interpolation results using Python?

Thank you, I would appreciate your help


问:
MAX of SUM of attribute 1, then display attribute 2 and attribute 3 of the row that attribute 1 is in | MySQL
So, I have a SALES_DATA table with the following attributes: YEAR_ID, MONTH_ID, SALES, and ORDER_NUMBER. They're all numerical values.

I want to create a query that will display the max sum of SALES per month to find the month in which the revenue was the highest for every year, and also display the corresponding MONTH_ID and YEAR_ID. Should look something like this:

YEAR_ID
MONTH_ID
MAX_REVENUE

2003
5
150

2004
2
180

2005
8
160

This is what I've tried so far:

```<code>SELECT T.YEAR_ID, T.MONTH_ID, MAX(T.REVENUE) AS MAX_REVENUE
FROM (SELECT YEAR_ID, MONTH_ID, SUM(SALES) AS REVENUE FROM [dbo].[sales_data_sample]
GROUP BY YEAR_ID, MONTH_ID) T
GROUP BY T.YEAR_ID, MONTH_ID
ORDER BY T.YEAR_ID, MAX_REVENUE DESC;
</code>```

But it gives me all of the sales sums for each month, something like this:

YEAR_ID
MONTH_ID
MAX_REVENUE

2003
5
150

2003
1
140

...
...
...

2004
2
180

2004
4
130

...
...
...

2005
8
160

2005
10
140

...
...
...

I really don't know how to fix it :(
I've tried not grouping by MONTH_ID, but gives me an error because it says that it's not an aggregated value.

Thanks! :)

Body:
So, I have a SALES_DATA table with the following attributes: YEAR_ID, MONTH_ID, SALES, and ORDER_NUMBER. They're all numerical values.

I want to create a query that will display the max sum of SALES per month to find the month in which the revenue was the highest for every year, and also display the corresponding MONTH_ID and YEAR_ID. Should look something like this:

YEAR_ID
MONTH_ID
MAX_REVENUE

2003
5
150

2004
2
180

2005
8
160

This is what I've tried so far:

SELECT T.YEAR_ID, T.MONTH_ID, MAX(T.REVENUE) AS MAX_REVENUE
FROM (SELECT YEAR_ID, MONTH_ID, SUM(SALES) AS REVENUE FROM [dbo].[sales_data_sample]
GROUP BY YEAR_ID, MONTH_ID) T
GROUP BY T.YEAR_ID, MONTH_ID
ORDER BY T.YEAR_ID, MAX_REVENUE DESC;

But it gives me all of the sales sums for each month, something like this:

YEAR_ID
MONTH_ID
MAX_REVENUE

2003
5
150

2003
1
140

...
...
...

2004
2
180

2004
4
130

...
...
...

2005
8
160

2005
10
140

...
...
...

I really don't know how to fix it :(
I've tried not grouping by MONTH_ID, but gives me an error because it says that it's not an aggregated value.

Thanks! :)


问:
I can't choose the right 'language' when I do onCLick()
When I click on 'Edit' button, I want to show the Update form of the language. When I click on the 1st time, it still shows the correct one (for example: id 33):
enter image description here

But when I tried to repair something, it render all of my 'item' and it's show the 1st language (always id 11):
enter image description here

I dont know what should I do, so can you help me? This is my full code:

```<code>import $ from 'jquery'
import { useState, useMemo } from 'react';
import React from 'react';
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { ajaxCallGet, ajaxCallPost, setItemLocalStorage, ajaxCallGetUrlDemo, getHostname, getHostname2,URL_API_GET } from "../libs/base";
import { Const_Libs } from '../libs/Const_Libs';
import ModalAddNgonNgu from '../modal/ModalAddLanguage';
import ModalEditNgonNgu from '../modal/ModalEditLanguage';
import { changedataCam, changeDataKey, changeDataLang, changeCurrentIdLang } from "../reducer_action/BaseReducerAction";
import Select from 'react-select'
import axios from 'axios';
import { useReducer } from 'react';

const PageLanguage = () => {
const dispatch = useDispatch()
const [langs,setLangs] = useState([]);
let [language,setLanguage] = useState([]);

useEffect(()=>{
    handleGetLanguage();
},[])
const handleGetLanguage = () => {
    axios.get(URL_API_GET + 'get-lang')

    .then((response) => {return response.data;})
    .then((data)=>{
        let langData = [];
        for (let key in data){
            langData.push({...data[key], id:data[key].id})
        }
        // console.log(langData);
        setLangs(langData);
    })
}

function saveLang(arr){
        axios.post(URL_API_GET + 'save-lang',arr)
        .then((rs) => {
            console.log(rs.data);
            handleGetLanguage();
            Const_Libs.TOAST.success("Thêm thành công");
        })
}
function editLang(arr,id){
    axios.post(URL_API_GET + 'update-lang/' + id,arr)
    .then((rs) => {
        console.log(rs.data);
        handleGetLanguage();
        Const_Libs.TOAST.success("Sửa thành công");
    })
}

const deleteLangByCheckBox = async () => {
    for (const checkbox of document.querySelectorAll(
        'input[name="checkbox-lang"]'
    )) {
        if (checkbox.checked) {
            await ajaxCallGet(
                'delete-lang/' + checkbox.getAttribute('data-id-lang')).then(rs => {
                    checkbox.checked = false
                })
        }
    }
    $('#checkAllLang').prop('checked', false)
    handleGetLanguage();
    Const_Libs.TOAST.success('Đã xóa thành công.')
}
function handleUpdate(e,item){
    setLanguage(item);
    console.log(item);
}

useEffect(() => {
    handleGetLanguage()
    $('#checkAllLang').click(function () {
        if ($(this).prop('checked')) {
            $('input[name="checkbox-lang"]').prop('checked', true)
        } else {
            $('input[name="checkbox-lang"]').prop('checked', false)
        }
    })
}, [])

return (

    <div style={{ height: '77vh', width: '1600px', margin: 'auto', border: '1px solid #ccc', borderRadius: '5px', padding: '8px' }}>

        <div className='right-container position-relative'>
            <div
                className='row px-4 d-flex align-items-center justify-content-between position-sticky'
                style={{ top: '0', padding: '10px', background: '#fff' }}
            >
                <div className='col-9'>
                    <span className='fs-7 fw-bolder'>Danh sách ngôn ngữ: </span>
                    <a href='#' className='mr-2'>

                    </a>
                </div>
                <div className='col-3 d-flex flex-row justify-content-end'>
                    <div className='col-4 delete'>
                        <div className='col-4 delete'>

                            <ModalAddNgonNgu handleGetLanguage={handleGetLanguage} saveLang={saveLang}/>
                        </div>                        </div>

                    <div className='col-4 delete'>
                        <button
                            type='button'
                            className=' fw-bolder btn btn-outline-danger'
                            style={{ fontSize: '14px' }}
                            onClick={() => deleteLangByCheckBox()}
                        // onClick={() => handleTest()}
                        >
                            Xóa
                        </button>
                    </div>
                </div>
            </div>
            <div className='p-3 table-responsive'>
                <table className='table '>
                    <thead>
                        <tr>
                            <th>
                                <input type='checkbox' id='checkAllLang' />
                            </th>
                            <th />
                            <th>Tên ngôn ngữ</th>
                            <th>Ngôn ngữ chính</th>
                            <th>Tiêu đề</th>
                            <th>Mô tả</th>
                            <th>Tác giả</th>
                            <th>Đánh giá</th>
                            <th>Lượt đánh giá</th>
                            <th>Những ngôn ngữ dịch</th>
                        </tr>
                    </thead>
                    <tbody>
                        <colgroup>
                            <col style={{ width: '4%!important' }}></col>
                            <col style={{ width: '4%!important' }}></col>
                            <col style={{ width: '16%!important' }}></col>
                            <col style={{ width: '16%!important' }}></col>
                            <col style={{ width: '20%!important' }}></col>
                            <col style={{ width: '16%!important' }}></col>
                            <col style={{ width: '16%!important' }}></col>
                            <col style={{ width: '16%!important' }}></col>
                            <col style={{ width: '16%!important' }}></col>
                            <col style={{ width: '16%!important' }}></col>

                            {/* <col style={{ width: '20%!important' }}></col> */}
                        </colgroup>
                        {langs.map((item, index) => {
                                let col_key_count = `col-count-${item.id}`
                                return (
                                    <tr key={index}>
                                        <td style={{ maxHeight: '21px', width: '3%' }}>
                                            <input
                                                type='checkbox'
                                                name='checkbox-lang'
                                                data-id-lang={item.id}
                                            />
                                        </td>
                                        <td
                                            style={{
                                                maxHeight: '21px',
                                                width: '4%',
                                                textAlign: 'center'
                                            }}
                                        >
                                            {index + 1}
                                        </td>
                                        <td
                                            className='text-primary'
                                            style={{
                                                maxHeight: '21px',
                                                width: '8%',
                                                maxWidth: '300px'
                                            }}
                                        >
                                            {/* <ModalEditNgonNgu handleGetLanguage={handleGetLanguage} editLang={editLang}  item={item}/> */}
                                            {item.language_name}
                                        </td>
                                        <td
                                            style={{ maxHeight: '21px', width: '8%' }}>
                                            {item.main_lang}
                                        </td>
                                        <td
                                            style={{
                                                maxHeight: '21px', width: '15%',textAlign: 'center',fontSize: '14px'
                                            }}
                                        >
                                            {item.title_lang}
                                        </td>
                                        <td
                                            style={{ maxHeight: '21px', width: '25%' }}>
                                            {item.describe_lang}
                                        </td>
                                        <td
                                            style={{ maxHeight: '21px', width: '8%' }}>
                                            {item.author_lang}
                                        </td>
                                        <td
                                            style={{ maxHeight: '21px', width: '8%' }}>
                                            {item.rate_lang}
                                        </td>
                                        <td
                                            style={{ maxHeight: '21px', width: '8%' }}>
                                            {item.reviews_lang}
                                        </td>
                                        <td
                                            style={{ maxHeight: '21px', width: '20%' }}>
                                            {item.translate_list}
                                        </td>
                                        <td
                                            style={{ maxHeight: '15px', width: '3%' }}
                                            onClick={(e)=>handleUpdate(e,item)}>
                                            <ModalEditNgonNgu editLang={editLang} item={language} />
                                            {/* <button className='btn btn-primary'>Edit</button> */}
                                        </td>
                                    </tr>
                                )
                            })
                        }

                    </tbody>
                </table>
            </div>
        </div>
    </div>
)
}

export default PageLanguage;
</code>```

Body:
When I click on 'Edit' button, I want to show the Update form of the language. When I click on the 1st time, it still shows the correct one (for example: id 33):
enter image description here

But when I tried to repair something, it render all of my 'item' and it's show the 1st language (always id 11):
enter image description here

I dont know what should I do, so can you help me? This is my full code:

import $ from 'jquery'
import { useState, useMemo } from 'react';
import React from 'react';
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { ajaxCallGet, ajaxCallPost, setItemLocalStorage, ajaxCallGetUrlDemo, getHostname, getHostname2,URL_API_GET } from "../libs/base";
import { Const_Libs } from '../libs/Const_Libs';
import ModalAddNgonNgu from '../modal/ModalAddLanguage';
import ModalEditNgonNgu from '../modal/ModalEditLanguage';
import { changedataCam, changeDataKey, changeDataLang, changeCurrentIdLang } from "../reducer_action/BaseReducerAction";
import Select from 'react-select'
import axios from 'axios';
import { useReducer } from 'react';

const PageLanguage = () => {
const dispatch = useDispatch()
const [langs,setLangs] = useState([]);
let [language,setLanguage] = useState([]);

useEffect(()=>{
    handleGetLanguage();
},[])
const handleGetLanguage = () => {
    axios.get(URL_API_GET + 'get-lang')

    .then((response) => {return response.data;})
    .then((data)=>{
        let langData = [];
        for (let key in data){
            langData.push({...data[key], id:data[key].id})
        }
        // console.log(langData);
        setLangs(langData);
    })
}

function saveLang(arr){
        axios.post(URL_API_GET + 'save-lang',arr)
        .then((rs) => {
            console.log(rs.data);
            handleGetLanguage();
            Const_Libs.TOAST.success("Thêm thành công");
        })
}
function editLang(arr,id){
    axios.post(URL_API_GET + 'update-lang/' + id,arr)
    .then((rs) => {
        console.log(rs.data);
        handleGetLanguage();
        Const_Libs.TOAST.success("Sửa thành công");
    })
}

const deleteLangByCheckBox = async () => {
    for (const checkbox of document.querySelectorAll(
        'input[name="checkbox-lang"]'
    )) {
        if (checkbox.checked) {
            await ajaxCallGet(
                'delete-lang/' + checkbox.getAttribute('data-id-lang')).then(rs => {
                    checkbox.checked = false
                })
        }
    }
    $('#checkAllLang').prop('checked', false)
    handleGetLanguage();
    Const_Libs.TOAST.success('Đã xóa thành công.')
}
function handleUpdate(e,item){
    setLanguage(item);
    console.log(item);
}

useEffect(() => {
    handleGetLanguage()
    $('#checkAllLang').click(function () {
        if ($(this).prop('checked')) {
            $('input[name="checkbox-lang"]').prop('checked', true)
        } else {
            $('input[name="checkbox-lang"]').prop('checked', false)
        }
    })
}, [])

return (

                    Danh sách ngôn ngữ:

                            <ModalAddNgonNgu handleGetLanguage={handleGetLanguage} saveLang={saveLang}/>

                        <button
                            type='button'
                            className=' fw-bolder btn btn-outline-danger'
                            style={{ fontSize: '14px' }}
                            onClick={() => deleteLangByCheckBox()}
                        // onClick={() => handleTest()}
                        >
                            Xóa
                        </button>

                                <input type='checkbox' id='checkAllLang' />

                            Tên ngôn ngữ
                            Ngôn ngữ chính
                            Tiêu đề
                            Mô tả
                            Tác giả
                            Đánh giá
                            Lượt đánh giá
                            Những ngôn ngữ dịch

                        <colgroup>
                            <col style={{ width: '4%!important' }}></col>
                            <col style={{ width: '4%!important' }}></col>
                            <col style={{ width: '16%!important' }}></col>
                            <col style={{ width: '16%!important' }}></col>
                            <col style={{ width: '20%!important' }}></col>
                            <col style={{ width: '16%!important' }}></col>
                            <col style={{ width: '16%!important' }}></col>
                            <col style={{ width: '16%!important' }}></col>
                            <col style={{ width: '16%!important' }}></col>
                            <col style={{ width: '16%!important' }}></col>

                            {/* <col style={{ width: '20%!important' }}></col> */}
                        </colgroup>
                        {langs.map((item, index) => {
                                let col_key_count = `col-count-${item.id}`
                                return (

                                            <input
                                                type='checkbox'
                                                name='checkbox-lang'
                                                data-id-lang={item.id}
                                            />

                                            {index + 1}

                                            {/* <ModalEditNgonNgu handleGetLanguage={handleGetLanguage} editLang={editLang}  item={item}/> */}
                                            {item.language_name}

                                            {item.main_lang}

                                            {item.title_lang}

                                            {item.describe_lang}

                                            {item.author_lang}

                                            {item.rate_lang}

                                            {item.reviews_lang}

                                            {item.translate_list}

                                        handleUpdate(e,item)}>
                                            <ModalEditNgonNgu editLang={editLang} item={language} />
                                            {/* <button className='btn btn-primary'>Edit</button> */}

                                )
                            })
                        }

)
}

export default PageLanguage;


问:
How to do if else in gitlab-ci to execute different script on the same job?
I have the following job:

```<code>variables:
    MAVEN_CLI_OPTS: "-s $CI_PROJECT_DIR/.m2/settings.xml --batch-mode --errors --fail-at-end --show-version -DinstallAtEnd=false -DdeployAtEnd=false -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener='warn"

package:
  stage: package
  extends: .jdk_in_dind
  script:
    - ./builddockerimage.sh -a
    - docker save -o candy-manager-docker-image-`docker images candy-manager --format "{{.Tag}}"`.tgz  track-history-manager:`docker images candy-manager --format "{{.Tag}}"`
    - chmod 777 candy-manager-docker-image-`docker images candy-manager --format "{{.Tag}}"`.tgz
    - mvn clean ${MAVEN_CLI_OPTS} package
    - ls -la target
  artifacts:
    paths:
      - candy-manager-*.tgz
      - target/candy-manager*.jar
  only:
    - merge_requests
    - develop
    - tags
    - prod
</code>```

I was wandering if I can use rules to add a tag number when a tag is generated on the tag.
here is the desired output

if tag is created, the tag should be read from CI_COMMIT_TAG global variable and have this outcome candy-manager_0.1.1_MYTAGVAULUE.jar if there is not tag and it's a regular commit then have the jar file as follow candy-manager_0.0.1.SNAPSHOT.jar. the value 0.0.1.SNAPSHOT is read from 0.0.1.SNAPSHOT that is present from pom.xml.

I try the following technic:

```<code>package:
  stage: package
  extends: .jdk_in_dind

variables:
    MAVEN_CLI_OPTS: "-s $CI_PROJECT_DIR/.m2/settings.xml --batch-mode --errors --fail-at-end --show-version -DinstallAtEnd=false -DdeployAtEnd=false -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener='warn"

rules:
    - if: '$CI_COMMIT_TAG != ""'
      when:
MAVEN_CLI_OPTS = "-s $CI_PROJECT_DIR/.m2/settings.xml --batch-mode versions:set -DnewVersion=${CI_COMMIT_TAG} --errors --fail-at-end --show-version -DinstallAtEnd=false -DdeployAtEnd=false -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener='warn"

  script:
    - ./builddockerimage.sh -a
    - docker save -o candy-manager-docker-image-`docker images candy-manager --format "{{.Tag}}"`.tgz  track-history-manager:`docker images candy-manager --format "{{.Tag}}"`
    - chmod 777 candy-manager-docker-image-`docker images candy-manager --format "{{.Tag}}"`.tgz
    - mvn clean ${MAVEN_CLI_OPTS} package
    - ls -la target
</code>```

but it is not working.

any help on this.

Body:
I have the following job:

variables:
    MAVEN_CLI_OPTS: "-s $CI_PROJECT_DIR/.m2/settings.xml --batch-mode --errors --fail-at-end --show-version -DinstallAtEnd=false -DdeployAtEnd=false -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener='warn"

package:
  stage: package
  extends: .jdk_in_dind
  script:
    - ./builddockerimage.sh -a
    - docker save -o candy-manager-docker-image-`docker images candy-manager --format "{{.Tag}}"`.tgz  track-history-manager:`docker images candy-manager --format "{{.Tag}}"`
    - chmod 777 candy-manager-docker-image-`docker images candy-manager --format "{{.Tag}}"`.tgz
    - mvn clean ${MAVEN_CLI_OPTS} package
    - ls -la target
  artifacts:
    paths:
      - candy-manager-*.tgz
      - target/candy-manager*.jar
  only:
    - merge_requests
    - develop
    - tags
    - prod

I was wandering if I can use rules to add a tag number when a tag is generated on the tag.
here is the desired output

if tag is created, the tag should be read from CI_COMMIT_TAG global variable and have this outcome candy-manager_0.1.1_MYTAGVAULUE.jar if there is not tag and it's a regular commit then have the jar file as follow candy-manager_0.0.1.SNAPSHOT.jar. the value 0.0.1.SNAPSHOT is read from 0.0.1.SNAPSHOT that is present from pom.xml.

I try the following technic:

package:
  stage: package
  extends: .jdk_in_dind

variables:
    MAVEN_CLI_OPTS: "-s $CI_PROJECT_DIR/.m2/settings.xml --batch-mode --errors --fail-at-end --show-version -DinstallAtEnd=false -DdeployAtEnd=false -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener='warn"

rules:
    - if: '$CI_COMMIT_TAG != ""'
      when:
MAVEN_CLI_OPTS = "-s $CI_PROJECT_DIR/.m2/settings.xml --batch-mode versions:set -DnewVersion=${CI_COMMIT_TAG} --errors --fail-at-end --show-version -DinstallAtEnd=false -DdeployAtEnd=false -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener='warn"

  script:
    - ./builddockerimage.sh -a
    - docker save -o candy-manager-docker-image-`docker images candy-manager --format "{{.Tag}}"`.tgz  track-history-manager:`docker images candy-manager --format "{{.Tag}}"`
    - chmod 777 candy-manager-docker-image-`docker images candy-manager --format "{{.Tag}}"`.tgz
    - mvn clean ${MAVEN_CLI_OPTS} package
    - ls -la target

but it is not working.

any help on this.


问:
How to do lighthouse test on a protected URL
I'm working on a project and need to do end-to-end testing using cypress. I need to do a lighthouse test on that project and get the performance and accessibility scores.
Currently, I'm doing lighthouse tests using the cypress-audit package. but the problem is,
we getting very low values for the performance score when compared to the chrome devtool lighthouse plugin. this happened only for the performance, the score of the accessibility got the same value for both ways. as an example for one page I got a performance score of 22 from devtools but running this method in cypress I got 2 as the performance score.

```<code>export function lighthouseAudit(scenarioId) {
    Cypress.config('taskTimeout', Cypress.env('lighthousePreloadingTaskTimeout'));
    cy.log("scenarioId", scenarioId);
    cy.task("getExcelData", Cypress.env("lighthouseBaseValueFilePath")).then(data => {
        const baseValueData = data.find(record => {
            return record.Id == scenarioId;
        });

        const lighthouseMetrics = {
            performance: baseValueData.performance,
            accessibility: baseValueData.accessibility,
        };

        const desktopConfig = {
            formFactor: 'desktop',
            screenEmulation: { disabled: true },
        };

        const lighthouseData = {
            lighthouseReportName : scenarioId,
            thresholds : lighthouseMetrics
        }

        cy.task('setLighthouseData', lighthouseData).then(() => {
            cy.lighthouse(lighthouseMetrics, desktopConfig);
        });
    });
}
</code>```

is it correct or do I need to pass any other option to desktopConfig ?

I saw most of the developers experiencing this issue when using cypress-audit. then I tried a new approach. I installed the lighthouse package globally and use this method to do the lighthouse test.

```<code>cy.exec(`lighthouse ${url} --chrome-flags="--headless" --preset=desktop  --emulatedUserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36" --output="json" `).then(({ stdout }) => {
    const { categories } = JSON.parse(stdout);
    var res =  Object.keys(categories).reduce((acc, key) => {
      return {
        ...acc,
        [key]: categories[key].score
      }
    }, {})

    cy.log(res)

  });
</code>```

seems like this will give a fire score for the performance than cypress-audit.
but the issue is we can't do lighthouse tests on a protected URL using this.
because when we run the cypress it opens a new chrome instance in which we can log in to our site and then we can go to protected URLs. but when this method runs it will open a new chrome instance that does not have any previously saved cookies or session ids, because of that we can't access the protected URLs

need help finding a better solution to get the correct performance and accessibility score from the lighthouse test. and it should be able to do a lighthouse test on protected URLs aswell

Body:
I'm working on a project and need to do end-to-end testing using cypress. I need to do a lighthouse test on that project and get the performance and accessibility scores.
Currently, I'm doing lighthouse tests using the cypress-audit package. but the problem is,
we getting very low values for the performance score when compared to the chrome devtool lighthouse plugin. this happened only for the performance, the score of the accessibility got the same value for both ways. as an example for one page I got a performance score of 22 from devtools but running this method in cypress I got 2 as the performance score.

export function lighthouseAudit(scenarioId) {
    Cypress.config('taskTimeout', Cypress.env('lighthousePreloadingTaskTimeout'));
    cy.log("scenarioId", scenarioId);
    cy.task("getExcelData", Cypress.env("lighthouseBaseValueFilePath")).then(data => {
        const baseValueData = data.find(record => {
            return record.Id == scenarioId;
        });

        const lighthouseMetrics = {
            performance: baseValueData.performance,
            accessibility: baseValueData.accessibility,
        };

        const desktopConfig = {
            formFactor: 'desktop',
            screenEmulation: { disabled: true },
        };

        const lighthouseData = {
            lighthouseReportName : scenarioId,
            thresholds : lighthouseMetrics
        }

        cy.task('setLighthouseData', lighthouseData).then(() => {
            cy.lighthouse(lighthouseMetrics, desktopConfig);
        });
    });
}

is it correct or do I need to pass any other option to desktopConfig ?

I saw most of the developers experiencing this issue when using cypress-audit. then I tried a new approach. I installed the lighthouse package globally and use this method to do the lighthouse test.

cy.exec(`lighthouse ${url} --chrome-flags="--headless" --preset=desktop  --emulatedUserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36" --output="json" `).then(({ stdout }) => {
    const { categories } = JSON.parse(stdout);
    var res =  Object.keys(categories).reduce((acc, key) => {
      return {
        ...acc,
        [key]: categories[key].score
      }
    }, {})

    cy.log(res)

  });

seems like this will give a fire score for the performance than cypress-audit.
but the issue is we can't do lighthouse tests on a protected URL using this.
because when we run the cypress it opens a new chrome instance in which we can log in to our site and then we can go to protected URLs. but when this method runs it will open a new chrome instance that does not have any previously saved cookies or session ids, because of that we can't access the protected URLs

need help finding a better solution to get the correct performance and accessibility score from the lighthouse test. and it should be able to do a lighthouse test on protected URLs aswell


问:
Manage multiple cards animation, while using map() to render multiple components in React JS
I have this Card component. I am iterating over an array of objects (3 objects). This array represents my data.

I want to manage the cards animation. Basically, I want to change the background color to blue.
The problem is that 1 card already comes with a background set to blue by default. The idea is to remove the background color of the active card, and set it to the hovered one.

Any ideas?

DATA:

```<code>const cardsInfo = [
  {
    backgroundColor: "",
    numberBackground: "",
    numberColor: "",
    textColor: "",
    number: "2",
    headline: "Experience",
    subText: `More than 3 Years
        of experience`,
  },
  {
    backgroundColor: "var(--primary-color)",
    numberBackground: "white",
    numberColor: "black",
    textColor: "white",
    number: "1",
    headline: "Creativity",
    subText: `Ability to solve
    problems the best
    way`,
  },
  {
    numberBackground: "",
    numberColor: "",
    textColor: "",
    number: "3",
    headline: "Response",
    subText: `Fast client
    response
    with a great
    communication`,
  },
];

export default cardsInfo;
</code>```

MAIN PAGE with a hoverFunction (I tested a lot of code, I don't know what to do anymore):

```<code>const About = () => {

  return (
    <main className={styles["about"]}>
      <section>
        <h1>RESUME</h1>
        <h3>
          Important info About <span>Me</span>
        </h3>
      </section>
      <section className={styles.cards}>
        {cardsInfo.map((card, index) => (
          <Card
            hoverFunction={() => {
              //CODE
            }}
            Id={index}
            key={index}
            {...card}
          />
        ))}
      </section>
    </main>
  );
};

export default About;
</code>```

I already tried creating and state, which the default value is 1 (index of the default card with blue background color). And when a card gets hovered, I set the state value to the index of that card.
But when it comes to the background color change, it does not work properly...

I don't know what to do...
So, any ideas?

Body:
I have this Card component. I am iterating over an array of objects (3 objects). This array represents my data.

I want to manage the cards animation. Basically, I want to change the background color to blue.
The problem is that 1 card already comes with a background set to blue by default. The idea is to remove the background color of the active card, and set it to the hovered one.

Any ideas?

DATA:

const cardsInfo = [
  {
    backgroundColor: "",
    numberBackground: "",
    numberColor: "",
    textColor: "",
    number: "2",
    headline: "Experience",
    subText: `More than 3 Years
        of experience`,
  },
  {
    backgroundColor: "var(--primary-color)",
    numberBackground: "white",
    numberColor: "black",
    textColor: "white",
    number: "1",
    headline: "Creativity",
    subText: `Ability to solve
    problems the best
    way`,
  },
  {
    numberBackground: "",
    numberColor: "",
    textColor: "",
    number: "3",
    headline: "Response",
    subText: `Fast client
    response
    with a great
    communication`,
  },
];

export default cardsInfo;

MAIN PAGE with a hoverFunction (I tested a lot of code, I don't know what to do anymore):

const About = () => {

  return (

RESUME

          Important info About Me

        {cardsInfo.map((card, index) => (
          <Card
            hoverFunction={() => {
              //CODE
            }}
            Id={index}
            key={index}
            {...card}
          />
        ))}

  );
};

export default About;

I already tried creating and state, which the default value is 1 (index of the default card with blue background color). And when a card gets hovered, I set the state value to the index of that card.
But when it comes to the background color change, it does not work properly...

I don't know what to do...
So, any ideas?


问:
WPF Datagrid columnheader backgroung change, when the cell that belong the column header line is selected

i want to change columnheader background when i select the cell that belong into column

so i try binding the columnheaderm but it was not working

this is my code form

```<code><Grid Margin="0,0,2,81">

        <DataGrid AutoGenerateColumns="False"  CanUserResizeColumns="False" RowHeaderWidth="0"
                                          HorizontalAlignment="Left" VerticalScrollBarVisibility="Visible"
                                          CanUserReorderColumns ="False" x:Name="dgvBinResult_Slot" IsReadOnly="True"
                                            ItemsSource="{Binding Right_data}" CurrentCellChanged="dgvBinResult_Slot_CurrentCellChanged">

            <DataGrid.Columns>

                <DataGridTextColumn Header="Bin" Width="*" CanUserSort="False"  Binding="{Binding Bin}"/>
                <DataGridTextColumn Header="EA" Width="*" CanUserSort="False" Binding="{Binding EA}"/>
                <DataGridTextColumn Header="Yield" Width="*" CanUserSort="False" Binding="{Binding Yield}"/>
            </DataGrid.Columns>

        </DataGrid>

    </Grid>

</code>```

i try bindding but it was not working

this code my datagrid

```<code><Grid Margin="0,0,2,81">

        <DataGrid AutoGenerateColumns="False"  CanUserResizeColumns="False" RowHeaderWidth="0"
                                          HorizontalAlignment="Left" VerticalScrollBarVisibility="Visible"
                                          CanUserReorderColumns ="False" x:Name="dgvBinResult_Slot" IsReadOnly="True"
                                            ItemsSource="{Binding Right_data}" CurrentCellChanged="dgvBinResult_Slot_CurrentCellChanged">

            <DataGrid.Columns>

                <DataGridTextColumn Header="Bin" Width="*" CanUserSort="False"  Binding="{Binding Bin}"/>
                <DataGridTextColumn Header="EA" Width="*" CanUserSort="False" Binding="{Binding EA}"/>
                <DataGridTextColumn Header="Yield" Width="*" CanUserSort="False" Binding="{Binding Yield}"/>
            </DataGrid.Columns>

        </DataGrid>

    </Grid>
</code>```

Body:
i want to change columnheader background when i select the cell that belong into column

so i try binding the columnheaderm but it was not working

this is my code form

<Grid Margin="0,0,2,81">

        <DataGrid AutoGenerateColumns="False"  CanUserResizeColumns="False" RowHeaderWidth="0"
                                          HorizontalAlignment="Left" VerticalScrollBarVisibility="Visible"
                                          CanUserReorderColumns ="False" x:Name="dgvBinResult_Slot" IsReadOnly="True"
                                            ItemsSource="{Binding Right_data}" CurrentCellChanged="dgvBinResult_Slot_CurrentCellChanged">

            <DataGrid.Columns>

                <DataGridTextColumn Header="Bin" Width="*" CanUserSort="False"  Binding="{Binding Bin}"/>
                <DataGridTextColumn Header="EA" Width="*" CanUserSort="False" Binding="{Binding EA}"/>
                <DataGridTextColumn Header="Yield" Width="*" CanUserSort="False" Binding="{Binding Yield}"/>
            </DataGrid.Columns>

        </DataGrid>

    </Grid>

i try bindding but it was not working

this code my datagrid

<Grid Margin="0,0,2,81">

        <DataGrid AutoGenerateColumns="False"  CanUserResizeColumns="False" RowHeaderWidth="0"
                                          HorizontalAlignment="Left" VerticalScrollBarVisibility="Visible"
                                          CanUserReorderColumns ="False" x:Name="dgvBinResult_Slot" IsReadOnly="True"
                                            ItemsSource="{Binding Right_data}" CurrentCellChanged="dgvBinResult_Slot_CurrentCellChanged">

            <DataGrid.Columns>

                <DataGridTextColumn Header="Bin" Width="*" CanUserSort="False"  Binding="{Binding Bin}"/>
                <DataGridTextColumn Header="EA" Width="*" CanUserSort="False" Binding="{Binding EA}"/>
                <DataGridTextColumn Header="Yield" Width="*" CanUserSort="False" Binding="{Binding Yield}"/>
            </DataGrid.Columns>

        </DataGrid>

    </Grid>


问:
mapping through an array of object that has an inner array and passing as prop to a child component
using react I created an array of objects, mapped through it displaying it using a child component, now I want to also create a mapped object inside each instance of the outer array and pass it down to the child component like the outer array.....actually the way I have done it was to create the outer array of the object first and then in the child component...I set another state to create the inner array I want to create in each...

after doing this I realized I am not able to delete from the inner array of objects set in the child component

this is what the parent and child component looks like....

for the parent....

```<code>import React, { useEffect, useRef } from "react";
import Column from "./components/column";
</code>```

function App(){

```<code>const [columns, setColumns] = React.useState([]);

  useEffect(() => {
    let columns = [
      {
        id: 1,
        name: "Todo",
      },
      {
        id: 2,
        name: "In Progress",
      },
      {
        id: 3,
        name: "Done",
      },
    ];
    setColumns(
      columns.map((d) => {
        return {
          id: d.id,
          name: d.name,

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

return

```<code>  <div ref={menuRef} className='total-column'>
        {columns.map((column) => {
          return (
            <Column
              key={column.id}
              id={column.id}
              name={column.name}
            />
          );
        })}
        </div>
}
export default App;
</code>```

now in the child component, another state is defined that would hold an array of object.....

```<code>import { nanoid } from "nanoid";
import React, { useEffect, useRef } from "react";
import Issues from "./Issues";
</code>```

function Column(props){

```<code>  const [issue, setIssue] = React.useState([]);

  function newIssue(valueCollected) {
    const newIssue = {
      pick: false,
      id:nanoid(),
      selection: false,
      tables: valueCollected,
      selection2: false,
    };

    setIssue([...issue, newIssue]);
  }
</code>```

return (

```<code> <div>
            {issue.map((issue) => {
              return (
                <Issues
                  key={issue.id}
                  id={issue.id}

                />
              );
            })}
</div>
}
export default Column;

Now ..the array in the child component column, also mapped through the array defined in it, displaying with it own child component....so the question is how do i write a function to delete from the inner array in the column component

tried deleting an object from the inner array but all to no avail
</code>```

Body:
using react I created an array of objects, mapped through it displaying it using a child component, now I want to also create a mapped object inside each instance of the outer array and pass it down to the child component like the outer array.....actually the way I have done it was to create the outer array of the object first and then in the child component...I set another state to create the inner array I want to create in each...

after doing this I realized I am not able to delete from the inner array of objects set in the child component

this is what the parent and child component looks like....

for the parent....

import React, { useEffect, useRef } from "react";
import Column from "./components/column";

function App(){

const [columns, setColumns] = React.useState([]);

  useEffect(() => {
    let columns = [
      {
        id: 1,
        name: "Todo",
      },
      {
        id: 2,
        name: "In Progress",
      },
      {
        id: 3,
        name: "Done",
      },
    ];
    setColumns(
      columns.map((d) => {
        return {
          id: d.id,
          name: d.name,

        };
      })
    );
  }, []);

return

        {columns.map((column) => {
          return (
            <Column
              key={column.id}
              id={column.id}
              name={column.name}
            />
          );
        })}

}
export default App;

now in the child component, another state is defined that would hold an array of object.....

import { nanoid } from "nanoid";
import React, { useEffect, useRef } from "react";
import Issues from "./Issues";

function Column(props){

  const [issue, setIssue] = React.useState([]);

  function newIssue(valueCollected) {
    const newIssue = {
      pick: false,
      id:nanoid(),
      selection: false,
      tables: valueCollected,
      selection2: false,
    };

    setIssue([...issue, newIssue]);
  }

return (

            {issue.map((issue) => {
              return (
                <Issues
                  key={issue.id}
                  id={issue.id}

                />
              );
            })}

}
export default Column;

Now ..the array in the child component column, also mapped through the array defined in it, displaying with it own child component....so the question is how do i write a function to delete from the inner array in the column component

tried deleting an object from the inner array but all to no avail


问:
How can I use multiple Google API keys in one project angular 14
Can we use multiple Google API keys in a single project, so that one API key is used for Google Maps and another for Google Places.</p>


问:
I clearly wrote the session delegate and delegated self, but the session proxy does not call back
```<code>import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate, URLSessionDelegate {

    private lazy var session: URLSession = {
        let configuration = URLSessionConfiguration.default
        configuration.waitsForConnectivity = true
        return URLSession(configuration: configuration,
                          delegate: self, delegateQueue: nil)
    }()
    var receivedData: Data?
    var webView: WKWebView!

    func startLoad() {
        let url = URL(string: "https://www.example.com/")!
        receivedData = Data()
        let task = session.dataTask(with: url)
        task.resume()
    }

    // delegate methods

    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) {
        print ("didReceiveResponse")
        guard let response = response as? HTTPURLResponse,
            (200...299).contains(response.statusCode),
            let mimeType = response.mimeType,
            mimeType == "text/html" else {
            completionHandler(.cancel)
            return
        }
        completionHandler(.allow)
    }

    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        self.receivedData?.append(data)
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        DispatchQueue.main.async {
            if error != nil {
                print("error")
            } else if let receivedData = self.receivedData,
                let string = String(data: receivedData, encoding: .utf8) {
                self.webView.loadHTMLString(string, baseURL: task.currentRequest?.url)
            }
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        webView = WKWebView()
        webView.navigationDelegate = self
        view = webView
        startLoad()
    }

}
</code>```

When I run in Xcode nothing happens.

I tried to use print to visually output it, but there was no result in the end. I would like to ask why I wrote the callback method of the delegate, but it was not called in the end. Is there any solution?

Body:
import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate, URLSessionDelegate {

    private lazy var session: URLSession = {
        let configuration = URLSessionConfiguration.default
        configuration.waitsForConnectivity = true
        return URLSession(configuration: configuration,
                          delegate: self, delegateQueue: nil)
    }()
    var receivedData: Data?
    var webView: WKWebView!

    func startLoad() {
        let url = URL(string: "https://www.example.com/")!
        receivedData = Data()
        let task = session.dataTask(with: url)
        task.resume()
    }

    // delegate methods

    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) {
        print ("didReceiveResponse")
        guard let response = response as? HTTPURLResponse,
            (200...299).contains(response.statusCode),
            let mimeType = response.mimeType,
            mimeType == "text/html" else {
            completionHandler(.cancel)
            return
        }
        completionHandler(.allow)
    }

    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        self.receivedData?.append(data)
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        DispatchQueue.main.async {
            if error != nil {
                print("error")
            } else if let receivedData = self.receivedData,
                let string = String(data: receivedData, encoding: .utf8) {
                self.webView.loadHTMLString(string, baseURL: task.currentRequest?.url)
            }
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        webView = WKWebView()
        webView.navigationDelegate = self
        view = webView
        startLoad()
    }

}

When I run in Xcode nothing happens.

I tried to use print to visually output it, but there was no result in the end. I would like to ask why I wrote the callback method of the delegate, but it was not called in the end. Is there any solution?


问:
How to prevent misdeletion during rollback?
Hi I'm having a problem with rollback routine for a function that creates an instance that consists of multiple unholding data. The problem is as follows.

Thread 0 creates or adds data A to data container (or manager).

Then, other thread coincidentally deletes or removes data A from the data container (or manager) right after creation or addition. And creates or adds different data A' with same key or ID, which will therefore be considered same as data A. Then, other thread creates or adds data B to data container (or manager).

Thread 0 then tries to create or add data B, but data B exists, so performs rollback routine, which means deletion or removal of previously created or added data A.

Thread 0 deletes or removes data A (actually data A').

If anyone knows a good way to prevent this misdeletion, or provide some guideline or rules for designing transactional operation, it will be great help. Thank you.


问:
Flutter run command is very slow on iPhone
Recently I noticed that the Flutter run command is very slow on iPhone.  I am using iPhone 14 Pro real device with iOS 16.2. My app is using Flutter with Firebase.  The build takes over 10 minutes to complete if I am lucky.  I have had times when I had to wait for 20 minutes or more. I have tried to use the release mode but did not help.

Does anyone know how to speed it up?
Thanks


问:
How to define a composite key, with EF 7, in F#
I want to replicate this, from C#:

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<VehicleFeature>().HasKey(vf=> new {vf.VehicleId, vf.FeatureId});
}
</code>```

to F#.

The one solution I had found on this site was:

```<code>fun x -> (x.VehicleId, x.FeatureId) :> obj)
</code>```

which doesn't work.

Body:
I want to replicate this, from C#:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<VehicleFeature>().HasKey(vf=> new {vf.VehicleId, vf.FeatureId});
}

to F#.

The one solution I had found on this site was:

fun x -> (x.VehicleId, x.FeatureId) :> obj)

which doesn't work.


问:
Error inflating class androidx.appcompat.widget.SearchView
I am making app and I used search view to filter data from recyclerview. Search bar run smoothly in my app with android 11 phone. However, When I change to Android 6.0 phone, my app crashed as below error:

```<code> Caused by: android.view.InflateException: Binary XML file line #58: Binary XML file line #58: Error inflating class androidx.appcompat.widget.SearchView
    at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
    at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:710)
    at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:195)
    at com.tonyapp.rabbitfarm.MainActivity.onCreate(MainActivity.java:57)
    at android.app.Activity.performCreate(Activity.java:6237)
</code>```

I created search bar in xml as below:

```<code> <androidx.appcompat.widget.SearchView
    android:id="@+id/searchView_home"
    android:textDirection="ltr"

    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:layout_below="@id/tlbar"

    android:layout_marginStart="8dp"
    android:layout_marginTop="@dimen/_8sdp"
    android:layout_marginEnd="8dp"

    android:background="@drawable/searchview"
    app:iconifiedByDefault="false"

    app:queryHint="@string/queryhint"
    app:searchHintIcon="@drawable/search_ic"
    app:searchIcon="@drawable/ic_timkiem">

</androidx.appcompat.widget.SearchView>
</code>```

I made search bar code in java as below:

```<code>    searchView_home= findViewById(R.id.searchView_home);
    EditText txtSearch = ((EditText)searchView_home.findViewById(androidx.appcompat.R.id.search_src_text));
    txtSearch.setHint(getResources().getString(R.string.queryhint));
    txtSearch.setHintTextColor(Color.BLACK);
    txtSearch.setTextColor(Color.BLACK);

    ((EditText) searchView_home.findViewById(androidx.appcompat.R.id.search_src_text))
            .setHintTextColor(getResources().getColor(R.color.black));

 searchView_home.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String newText) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            filter(newText);
            return true;
        }
    });
</code>```

I tried to migrate my app to androidx as a suggestion from solution of other people at menu bar/refactor/migrate to android X. Unfortunately, the crash still persist. Please help me fix this  error.

Body:
I am making app and I used search view to filter data from recyclerview. Search bar run smoothly in my app with android 11 phone. However, When I change to Android 6.0 phone, my app crashed as below error:

 Caused by: android.view.InflateException: Binary XML file line #58: Binary XML file line #58: Error inflating class androidx.appcompat.widget.SearchView
    at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
    at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:710)
    at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:195)
    at com.tonyapp.rabbitfarm.MainActivity.onCreate(MainActivity.java:57)
    at android.app.Activity.performCreate(Activity.java:6237)

I created search bar in xml as below:

 <androidx.appcompat.widget.SearchView
    android:id="@+id/searchView_home"
    android:textDirection="ltr"

    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:layout_below="@id/tlbar"

    android:layout_marginStart="8dp"
    android:layout_marginTop="@dimen/_8sdp"
    android:layout_marginEnd="8dp"

    android:background="@drawable/searchview"
    app:iconifiedByDefault="false"

    app:queryHint="@string/queryhint"
    app:searchHintIcon="@drawable/search_ic"
    app:searchIcon="@drawable/ic_timkiem">

</androidx.appcompat.widget.SearchView>

I made search bar code in java as below:

    searchView_home= findViewById(R.id.searchView_home);
    EditText txtSearch = ((EditText)searchView_home.findViewById(androidx.appcompat.R.id.search_src_text));
    txtSearch.setHint(getResources().getString(R.string.queryhint));
    txtSearch.setHintTextColor(Color.BLACK);
    txtSearch.setTextColor(Color.BLACK);

    ((EditText) searchView_home.findViewById(androidx.appcompat.R.id.search_src_text))
            .setHintTextColor(getResources().getColor(R.color.black));

 searchView_home.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String newText) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            filter(newText);
            return true;
        }
    });

I tried to migrate my app to androidx as a suggestion from solution of other people at menu bar/refactor/migrate to android X. Unfortunately, the crash still persist. Please help me fix this  error.