问:
Java SPI - Choosing a single implementation (using Java 17 modular system)
My question is based on this question

Java SPI - Choosing a single implementation

When we have multiple implementations is there any way (how to do it) to select one specific. From my standpoint it just doesn't make sense to do blindingly like this

```<code>ServiceLoader.load(SomeService.class)
    .forEach(service -> service.test());
</code>```

I.e.

if I have three implementations of SomeService

```<code>interface SomeService {
    public void test();
}

public class SomeInterfaceImpl1 implements SomeService {
 <...>
}

public class SomeInterfaceImpl2 implements SomeService {
 <...>
}

public class SomeInterfaceImpl3 implements SomeService {
 <...>
}
</code>```

How to select an implementation of SomeInterfaceImpl2?

Would doing something like this make any sense?

```<code>ServiceLoader.load(SomeService.class)
             .stream()
             .map(Provider::get)
             .filter( s -> s instanceof SomeInterfaceImp2)
             .limit(1)
             .forEach(s -> s.test())
         .
</code>```

Body:
My question is based on this question

Java SPI - Choosing a single implementation

When we have multiple implementations is there any way (how to do it) to select one specific. From my standpoint it just doesn't make sense to do blindingly like this

ServiceLoader.load(SomeService.class)
    .forEach(service -> service.test());

I.e.

if I have three implementations of SomeService

interface SomeService {
    public void test();
}

public class SomeInterfaceImpl1 implements SomeService {
 <...>
}

public class SomeInterfaceImpl2 implements SomeService {
 <...>
}

public class SomeInterfaceImpl3 implements SomeService {
 <...>
}

How to select an implementation of SomeInterfaceImpl2?

Would doing something like this make any sense?

ServiceLoader.load(SomeService.class)
             .stream()
             .map(Provider::get)
             .filter( s -> s instanceof SomeInterfaceImp2)
             .limit(1)
             .forEach(s -> s.test())
         .


来源: stackexchange

问:
Github Build Getting Failed for AWS EC2 Instance
I am try to Auto deploy My SpringBoot Code to EC2 and Have added Docker and Github actions as below I am getting error Below. I am fairly new to AWS. I have added secret keys in secret. Rest Yaml is doing. Please help me regarding this.

Below is the yaml file I added

I have used Below link to follow as a tutorial

https://medium.com/geekculture/deploy-your-spring-boot-java-application-to-aws-ec2-using-github-actions-and-docker-e28c456a4b1a

```<code>name: Deploy AWS EC2
on:
  push:
    branches:
      - master
      - main
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Get Github action IP
        id: ip
        uses: haythem/public-ip@v1.2

      - name: AWS configure
        uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID  }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: ${{ secrets.AWS_DEFAULT_REGION }}

      - name: Add github actions IP to security group
        env:
          AWS_SECURITY_GROUP: ${{ secrets.AWS_SECURITY_GROUP }}
        run: |
          aws ec2 authorize-security-group-ingress --group-id ${{ env.AWS_SECURITY_GROUP }} --protocol tcp --port 22 --cidr ${{ steps.ip.outputs.ipv4 }}/16
          sleep 10
      - name: Deploy on AWS EC2
        env:
          PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY  }}
          HOSTNAME: ${{ secrets.HOSTNAME  }}
          USER_NAME: ${{ secrets.USERNAME  }}
          ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
        run: |
          echo "$PRIVATE_KEY" > private_key.pem && chmod 600 private_key.pem
          ssh -o StrictHostKeyChecking=no -i private_key.pem ${USER_NAME}@${HOSTNAME} '
            rm -rf /home/ec2-user/https://github.com/cloudyape/metafy-back.git
            git clone https://github.com/cloudyape/metafy-back.git
            cd metafy_back
            git checkout main
            git pull origin main
            sudo chmod +x ./deploy.sh
            ./deploy.sh
          '
          rm -rf private_key.pem
      - name: Remove github actions IP from security group
        env:
          AWS_SECURITY_GROUP: ${{ secrets.AWS_SECURITY_GROUP }}
        run: |
          aws ec2 revoke-security-group-ingress --group-id ${{ env.AWS_SECURITY_GROUP }} --protocol tcp --port 22 --cidr ${{ steps.ip.outputs.ipv4 }}/16
        if: always()
</code>```

Below is the error I am getting in the actions panel.

```<code>s
2s
Run echo "$PRIVATE_KEY" > private_key.pem && chmod 600 private_key.pem
  echo "$PRIVATE_KEY" > private_key.pem && chmod 600 private_key.pem
  ssh -o StrictHostKeyChecking=no -i private_key.pem ${USER_NAME}@${HOSTNAME} '
    rm -rf /home/***/https://github.com/cloudyape/metafy-back.git
    git clone https://github.com/cloudyape/metafy-back.git
    cd metafy_back
    git checkout main
    git pull origin main
    sudo chmod +x ./deploy.sh
    ./deploy.sh
  '
  rm -rf private_key.pem
  shell: /usr/bin/bash -e {0}
  env:
    AWS_DEFAULT_REGION: ***
    AWS_REGION: ***
    AWS_ACCESS_KEY_ID: ***
    AWS_SECRET_ACCESS_KEY: ***
    PRIVATE_KEY: ***
    HOSTNAME: ***
    USER_NAME: ***
    ECR_REGISTRY:

Warning: Permanently added '***' (ED25519) to the list of known hosts.
Load key "private_key.pem": error in libcrypto
***@***: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
Error: Process completed with exit code 255.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am try to Auto deploy My SpringBoot Code to EC2 and Have added Docker and Github actions as below I am getting error Below. I am fairly new to AWS. I have added secret keys in secret. Rest Yaml is doing. Please help me regarding this.

Below is the yaml file I added

I have used Below link to follow as a tutorial

https://medium.com/geekculture/deploy-your-spring-boot-java-application-to-aws-ec2-using-github-actions-and-docker-e28c456a4b1a

name: Deploy AWS EC2
on:
  push:
    branches:
      - master
      - main
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Get Github action IP
        id: ip
        uses: haythem/public-ip@v1.2

      - name: AWS configure
        uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID  }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: ${{ secrets.AWS_DEFAULT_REGION }}

      - name: Add github actions IP to security group
        env:
          AWS_SECURITY_GROUP: ${{ secrets.AWS_SECURITY_GROUP }}
        run: |
          aws ec2 authorize-security-group-ingress --group-id ${{ env.AWS_SECURITY_GROUP }} --protocol tcp --port 22 --cidr ${{ steps.ip.outputs.ipv4 }}/16
          sleep 10
      - name: Deploy on AWS EC2
        env:
          PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY  }}
          HOSTNAME: ${{ secrets.HOSTNAME  }}
          USER_NAME: ${{ secrets.USERNAME  }}
          ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
        run: |
          echo "$PRIVATE_KEY" > private_key.pem && chmod 600 private_key.pem
          ssh -o StrictHostKeyChecking=no -i private_key.pem ${USER_NAME}@${HOSTNAME} '
            rm -rf /home/ec2-user/https://github.com/cloudyape/metafy-back.git
            git clone https://github.com/cloudyape/metafy-back.git
            cd metafy_back
            git checkout main
            git pull origin main
            sudo chmod +x ./deploy.sh
            ./deploy.sh
          '
          rm -rf private_key.pem
      - name: Remove github actions IP from security group
        env:
          AWS_SECURITY_GROUP: ${{ secrets.AWS_SECURITY_GROUP }}
        run: |
          aws ec2 revoke-security-group-ingress --group-id ${{ env.AWS_SECURITY_GROUP }} --protocol tcp --port 22 --cidr ${{ steps.ip.outputs.ipv4 }}/16
        if: always()

Below is the error I am getting in the actions panel.

s
2s
Run echo "$PRIVATE_KEY" > private_key.pem && chmod 600 private_key.pem
  echo "$PRIVATE_KEY" > private_key.pem && chmod 600 private_key.pem
  ssh -o StrictHostKeyChecking=no -i private_key.pem ${USER_NAME}@${HOSTNAME} '
    rm -rf /home/***/https://github.com/cloudyape/metafy-back.git
    git clone https://github.com/cloudyape/metafy-back.git
    cd metafy_back
    git checkout main
    git pull origin main
    sudo chmod +x ./deploy.sh
    ./deploy.sh
  '
  rm -rf private_key.pem
  shell: /usr/bin/bash -e {0}
  env:
    AWS_DEFAULT_REGION: ***
    AWS_REGION: ***
    AWS_ACCESS_KEY_ID: ***
    AWS_SECRET_ACCESS_KEY: ***
    PRIVATE_KEY: ***
    HOSTNAME: ***
    USER_NAME: ***
    ECR_REGISTRY:

Warning: Permanently added '***' (ED25519) to the list of known hosts.
Load key "private_key.pem": error in libcrypto
***@***: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
Error: Process completed with exit code 255.


问:
Automatic plate detection in real time
```<code>plate detection using webcam

`
</code>```

I am doing automatic plate detection using webcam, I have trained my model using colab and downloaded it as tflite file. After that, I run the following code and it works very well, So now i am able to detect plate number

```<code>`import os
import argparse
import cv2
import numpy as np
import sys
import time
from threading import Thread
import importlib.util

# Define VideoStream class to handle streaming of video from webcam in separate processing thread
# Source - Adrian Rosebrock, PyImageSearch: https://www.pyimagesearch.com/2015/12/28/increasing-raspberry-pi-fps-with-python-and-opencv/
class VideoStream:
    """Camera object that controls video streaming from the Picamera"""
    def _init_(self,resolution=(640,480),framerate=30):
        # Initialize the PiCamera and the camera image stream
        self.stream = cv2.VideoCapture(1)
        ret = self.stream.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))
        ret = self.stream.set(3,resolution[0])
        ret = self.stream.set(4,resolution[1])

        # Read first frame from the stream
        (self.grabbed, self.frame) = self.stream.read()

    # Variable to control when the camera is stopped
        self.stopped = False

    def start(self):
    # Start the thread that reads frames from the video stream
        Thread(target=self.update,args=()).start()
        return self

    def update(self):
        # Keep looping indefinitely until the thread is stopped
        while True:
            # If the camera is stopped, stop the thread
            if self.stopped:
                # Close camera resources
                self.stream.release()
                return

            # Otherwise, grab the next frame from the stream
            (self.grabbed, self.frame) = self.stream.read()

    def read(self):
    # Return the most recent frame
        return self.frame

    def stop(self):
    # Indicate that the camera and thread should be stopped
        self.stopped = True
# Define and parse input arguments
parser = argparse.ArgumentParser()
parser.add_argument('--modeldir', help='Folder the .tflite file is located in',
                    required=True)
parser.add_argument('--graph', help='Name of the .tflite file, if different than detect.tflite',
                    default='detect.tflite')
parser.add_argument('--labels', help='Name of the labelmap file, if different than label_map.pbtxt',
                    default='label_map.pbtxt')
parser.add_argument('--threshold', help='Minimum confidence threshold for displaying detected objects',
                    default=0.5)
parser.add_argument('--resolution', help='Desired webcam resolution in WxH. If the webcam does not support the resolution entered, errors may occur.',
                    default='1280x720')
parser.add_argument('--edgetpu', help='Use Coral Edge TPU Accelerator to speed up detection',
                    action='store_true')

args = parser.parse_args()

MODEL_NAME = args.modeldir
GRAPH_NAME = args.graph
LABELMAP_NAME = args.labels
min_conf_threshold = float(args.threshold)
resW, resH = args.resolution.split('x')
imW, imH = int(resW), int(resH)
use_TPU = args.edgetpu

# Import TensorFlow libraries
# If tflite_runtime is installed, import interpreter from tflite_runtime, else import from regular tensorflow
# If using Coral Edge TPU, import the load_delegate library
pkg = importlib.util.find_spec('tflite_runtime')
if pkg:
    from tflite_runtime.interpreter import Interpreter
    if use_TPU:
        from tflite_runtime.interpreter import load_delegate
else:
    from tensorflow.lite.python.interpreter import Interpreter
    if use_TPU:
        from tensorflow.lite.python.interpreter import load_delegate

# If using Edge TPU, assign filename for Edge TPU model
if use_TPU:
    # If user has specified the name of the .tflite file, use that name, otherwise use default 'edgetpu.tflite'
    if (GRAPH_NAME == 'detect.tflite'):
        GRAPH_NAME = 'edgetpu.tflite'

# Get path to current working directory
CWD_PATH = os.getcwd()

# Path to .tflite file, which contains the model that is used for object detection
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,GRAPH_NAME)

# Path to label map file
PATH_TO_LABELS = os.path.join(CWD_PATH,MODEL_NAME,LABELMAP_NAME)

# Load the label map
with open(PATH_TO_LABELS, 'r') as f:
    labels = [line.strip() for line in f.readlines()]

# Have to do a weird fix for label map if using the COCO "starter model" from
# https://www.tensorflow.org/lite/models/object_detection/overview
# First label is '???', which has to be removed.
if labels[0] == '???':
    del(labels[0])

# Load the Tensorflow Lite model.
# If using Edge TPU, use special load_delegate argument
if use_TPU:
    interpreter = Interpreter(model_path=PATH_TO_CKPT,
                              experimental_delegates=[load_delegate('libedgetpu.so.1.0')])
    print(PATH_TO_CKPT)
else:
    interpreter = Interpreter(model_path=PATH_TO_CKPT)

interpreter.allocate_tensors()

# Get model details
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
height = input_details[0]['shape'][1]
width = input_details[0]['shape'][2]

floating_model = (input_details[0]['dtype'] == np.float32)

input_mean = 127.5
input_std = 127.5

# Initialize frame rate calculation
frame_rate_calc = 1
freq = cv2.getTickFrequency()

# Initialize video stream
videostream = VideoStream(resolution=(imW,imH),framerate=30).start()
time.sleep(1)

#for frame1 in camera.capture_continuous(rawCapture, format="bgr",use_video_port=True):
while True:

    # Start timer (for calculating frame rate)
    t1 = cv2.getTickCount()

    # Grab frame from video stream
    frame1 = videostream.read()

    # Acquire frame and resize to expected shape [1xHxWx3]
    frame = frame1.copy()
    frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    frame_resized = cv2.resize(frame_rgb, (width, height))
    input_data = np.expand_dims(frame_resized, axis=0)

    # Normalize pixel values if using a floating model (i.e. if model is non-quantized)
    if floating_model:
        input_data = (np.float32(input_data) - input_mean) / input_std

    # Perform the actual detection by running the model with the image as input
    interpreter.set_tensor(input_details[0]['index'],input_data)
    interpreter.invoke()

    # Retrieve detection results
    boxes = interpreter.get_tensor(output_details[1]['index'])[0] # Bounding box coordinates of detected objects
    classes = interpreter.get_tensor(output_details[3]['index'])[0] # Class index of detected objects
    scores = interpreter.get_tensor(output_details[0]['index'])[0] # Confidence of detected objects
    #num = interpreter.get_tensor(output_details[3]['index'])[0]  # Total number of detected objects (inaccurate and not needed)

    # Loop over all detections and draw detection box if confidence is above minimum threshold
    for i in range(len(scores)):
        if ((scores[i] > min_conf_threshold) and (scores[i] <= 1.0)):

            # Get bounding box coordinates and draw box
            # Interpreter can return coordinates that are outside of image dimensions, need to force them to be within image using max() and min()
            ymin = int(max(1,(boxes[i][0] * imH)))
            xmin = int(max(1,(boxes[i][1] * imW)))
            ymax = int(min(imH,(boxes[i][2] * imH)))
            xmax = int(min(imW,(boxes[i][3] * imW)))

            cv2.rectangle(frame, (xmin,ymin), (xmax,ymax), (10, 255, 0), 2)

            # Draw label
            object_name = labels[int(classes[i])] # Look up object name from "labels" array using class index
            label = '%s: %d%%' % (object_name, int(scores[i]*100)) # Example: 'person: 72%'
            labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2) # Get font size
            label_ymin = max(ymin, labelSize[1] + 10) # Make sure not to draw label too close to top of window
            cv2.rectangle(frame, (xmin, label_ymin-labelSize[1]-10), (xmin+labelSize[0], label_ymin+baseLine-10), (255, 255, 255), cv2.FILLED) # Draw white box to put label text in
            cv2.putText(frame, label, (xmin, label_ymin-7), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2) # Draw label text

    # Draw framerate in corner of frame
    cv2.putText(frame,'FPS: {0:.2f}'.format(frame_rate_calc),(30,50),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,0),2,cv2.LINE_AA)
    # All the results have been drawn on the frame, so it's time to display it.
    cv2.imshow('Object detector', frame)

    # Calculate framerate
    t2 = cv2.getTickCount()
    time1 = (t2-t1)/freq
    frame_rate_calc= 1/time1

    # Press 'q' to quit
    if cv2.waitKey(1) == ord('q'):
        break

# Clean up
cv2.destroyAllWindows()
videostrea`your text`m.stop()
</code>```
```<code>
</code>```

my quastion is how can I apply ocr ( Optical Character Recognition ) to my code ? i tried too many times but I couldn't get it

i tried to add some lines and import ocr to this above code but I could not find a solution.

Title: Automatic plate detection in real time

Body:
plate detection using webcam

`

I am doing automatic plate detection using webcam, I have trained my model using colab and downloaded it as tflite file. After that, I run the following code and it works very well, So now i am able to detect plate number

`import os
import argparse
import cv2
import numpy as np
import sys
import time
from threading import Thread
import importlib.util

# Define VideoStream class to handle streaming of video from webcam in separate processing thread
# Source - Adrian Rosebrock, PyImageSearch: https://www.pyimagesearch.com/2015/12/28/increasing-raspberry-pi-fps-with-python-and-opencv/
class VideoStream:
    """Camera object that controls video streaming from the Picamera"""
    def _init_(self,resolution=(640,480),framerate=30):
        # Initialize the PiCamera and the camera image stream
        self.stream = cv2.VideoCapture(1)
        ret = self.stream.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))
        ret = self.stream.set(3,resolution[0])
        ret = self.stream.set(4,resolution[1])

        # Read first frame from the stream
        (self.grabbed, self.frame) = self.stream.read()

    # Variable to control when the camera is stopped
        self.stopped = False

    def start(self):
    # Start the thread that reads frames from the video stream
        Thread(target=self.update,args=()).start()
        return self

    def update(self):
        # Keep looping indefinitely until the thread is stopped
        while True:
            # If the camera is stopped, stop the thread
            if self.stopped:
                # Close camera resources
                self.stream.release()
                return

            # Otherwise, grab the next frame from the stream
            (self.grabbed, self.frame) = self.stream.read()

    def read(self):
    # Return the most recent frame
        return self.frame

    def stop(self):
    # Indicate that the camera and thread should be stopped
        self.stopped = True
# Define and parse input arguments
parser = argparse.ArgumentParser()
parser.add_argument('--modeldir', help='Folder the .tflite file is located in',
                    required=True)
parser.add_argument('--graph', help='Name of the .tflite file, if different than detect.tflite',
                    default='detect.tflite')
parser.add_argument('--labels', help='Name of the labelmap file, if different than label_map.pbtxt',
                    default='label_map.pbtxt')
parser.add_argument('--threshold', help='Minimum confidence threshold for displaying detected objects',
                    default=0.5)
parser.add_argument('--resolution', help='Desired webcam resolution in WxH. If the webcam does not support the resolution entered, errors may occur.',
                    default='1280x720')
parser.add_argument('--edgetpu', help='Use Coral Edge TPU Accelerator to speed up detection',
                    action='store_true')

args = parser.parse_args()

MODEL_NAME = args.modeldir
GRAPH_NAME = args.graph
LABELMAP_NAME = args.labels
min_conf_threshold = float(args.threshold)
resW, resH = args.resolution.split('x')
imW, imH = int(resW), int(resH)
use_TPU = args.edgetpu

# Import TensorFlow libraries
# If tflite_runtime is installed, import interpreter from tflite_runtime, else import from regular tensorflow
# If using Coral Edge TPU, import the load_delegate library
pkg = importlib.util.find_spec('tflite_runtime')
if pkg:
    from tflite_runtime.interpreter import Interpreter
    if use_TPU:
        from tflite_runtime.interpreter import load_delegate
else:
    from tensorflow.lite.python.interpreter import Interpreter
    if use_TPU:
        from tensorflow.lite.python.interpreter import load_delegate

# If using Edge TPU, assign filename for Edge TPU model
if use_TPU:
    # If user has specified the name of the .tflite file, use that name, otherwise use default 'edgetpu.tflite'
    if (GRAPH_NAME == 'detect.tflite'):
        GRAPH_NAME = 'edgetpu.tflite'

# Get path to current working directory
CWD_PATH = os.getcwd()

# Path to .tflite file, which contains the model that is used for object detection
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,GRAPH_NAME)

# Path to label map file
PATH_TO_LABELS = os.path.join(CWD_PATH,MODEL_NAME,LABELMAP_NAME)

# Load the label map
with open(PATH_TO_LABELS, 'r') as f:
    labels = [line.strip() for line in f.readlines()]

# Have to do a weird fix for label map if using the COCO "starter model" from
# https://www.tensorflow.org/lite/models/object_detection/overview
# First label is '???', which has to be removed.
if labels[0] == '???':
    del(labels[0])

# Load the Tensorflow Lite model.
# If using Edge TPU, use special load_delegate argument
if use_TPU:
    interpreter = Interpreter(model_path=PATH_TO_CKPT,
                              experimental_delegates=[load_delegate('libedgetpu.so.1.0')])
    print(PATH_TO_CKPT)
else:
    interpreter = Interpreter(model_path=PATH_TO_CKPT)

interpreter.allocate_tensors()

# Get model details
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
height = input_details[0]['shape'][1]
width = input_details[0]['shape'][2]

floating_model = (input_details[0]['dtype'] == np.float32)

input_mean = 127.5
input_std = 127.5

# Initialize frame rate calculation
frame_rate_calc = 1
freq = cv2.getTickFrequency()

# Initialize video stream
videostream = VideoStream(resolution=(imW,imH),framerate=30).start()
time.sleep(1)

#for frame1 in camera.capture_continuous(rawCapture, format="bgr",use_video_port=True):
while True:

    # Start timer (for calculating frame rate)
    t1 = cv2.getTickCount()

    # Grab frame from video stream
    frame1 = videostream.read()

    # Acquire frame and resize to expected shape [1xHxWx3]
    frame = frame1.copy()
    frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    frame_resized = cv2.resize(frame_rgb, (width, height))
    input_data = np.expand_dims(frame_resized, axis=0)

    # Normalize pixel values if using a floating model (i.e. if model is non-quantized)
    if floating_model:
        input_data = (np.float32(input_data) - input_mean) / input_std

    # Perform the actual detection by running the model with the image as input
    interpreter.set_tensor(input_details[0]['index'],input_data)
    interpreter.invoke()

    # Retrieve detection results
    boxes = interpreter.get_tensor(output_details[1]['index'])[0] # Bounding box coordinates of detected objects
    classes = interpreter.get_tensor(output_details[3]['index'])[0] # Class index of detected objects
    scores = interpreter.get_tensor(output_details[0]['index'])[0] # Confidence of detected objects
    #num = interpreter.get_tensor(output_details[3]['index'])[0]  # Total number of detected objects (inaccurate and not needed)

    # Loop over all detections and draw detection box if confidence is above minimum threshold
    for i in range(len(scores)):
        if ((scores[i] > min_conf_threshold) and (scores[i] <= 1.0)):

            # Get bounding box coordinates and draw box
            # Interpreter can return coordinates that are outside of image dimensions, need to force them to be within image using max() and min()
            ymin = int(max(1,(boxes[i][0] * imH)))
            xmin = int(max(1,(boxes[i][1] * imW)))
            ymax = int(min(imH,(boxes[i][2] * imH)))
            xmax = int(min(imW,(boxes[i][3] * imW)))

            cv2.rectangle(frame, (xmin,ymin), (xmax,ymax), (10, 255, 0), 2)

            # Draw label
            object_name = labels[int(classes[i])] # Look up object name from "labels" array using class index
            label = '%s: %d%%' % (object_name, int(scores[i]*100)) # Example: 'person: 72%'
            labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2) # Get font size
            label_ymin = max(ymin, labelSize[1] + 10) # Make sure not to draw label too close to top of window
            cv2.rectangle(frame, (xmin, label_ymin-labelSize[1]-10), (xmin+labelSize[0], label_ymin+baseLine-10), (255, 255, 255), cv2.FILLED) # Draw white box to put label text in
            cv2.putText(frame, label, (xmin, label_ymin-7), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2) # Draw label text

    # Draw framerate in corner of frame
    cv2.putText(frame,'FPS: {0:.2f}'.format(frame_rate_calc),(30,50),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,0),2,cv2.LINE_AA)
    # All the results have been drawn on the frame, so it's time to display it.
    cv2.imshow('Object detector', frame)

    # Calculate framerate
    t2 = cv2.getTickCount()
    time1 = (t2-t1)/freq
    frame_rate_calc= 1/time1

    # Press 'q' to quit
    if cv2.waitKey(1) == ord('q'):
        break

# Clean up
cv2.destroyAllWindows()
videostrea`your text`m.stop()

my quastion is how can I apply ocr ( Optical Character Recognition ) to my code ? i tried too many times but I couldn't get it

i tried to add some lines and import ocr to this above code but I could not find a solution.


问:
System.Data.DataRowView in combobox
The code initially retrieves data from the database, but as soon as I choose 1 option from the combobox dropdown, it prints System.Data.DataRowView there. Kindly, help me with it.

Here's my code:

```<code>private void getRooms()
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from RoomTbl where RStatus = 'Available'", con);
            SqlDataReader rdr;
            rdr = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Columns.Add("RNum", typeof(int));
            dt.Load(rdr);
            BRoomCB.ValueMember = "RNum";
            BRoomCB.DataSource = dt;
            con.Close();
        }
</code>```

Title: System.Data.DataRowView in combobox

Body:
The code initially retrieves data from the database, but as soon as I choose 1 option from the combobox dropdown, it prints System.Data.DataRowView there. Kindly, help me with it.

Here's my code:

private void getRooms()
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from RoomTbl where RStatus = 'Available'", con);
            SqlDataReader rdr;
            rdr = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Columns.Add("RNum", typeof(int));
            dt.Load(rdr);
            BRoomCB.ValueMember = "RNum";
            BRoomCB.DataSource = dt;
            con.Close();
        }


问:
GCP Dataproc : Scala SSH Tunnel Oracle database
I'm trying to run the Spark job from GCP Dataproc. It's mainly reading data from AWS Oracle databases, so it connects to them via SSH. It's working fine locally, but not in the GCP Dataproc cluster.

```<code>import com.jcraft.jsch.Session
import org.apache.log4j.{Level, Logger}

object SSHTunnelService {
  def connectSession(rhost: String): Unit = {
    import com.jcraft.jsch.JSch
    var session: Session = null
    val user = "xxxx"

    val host = "xxxxxxx"
    val port = 22
    val lport = 1521
    val rport = 1521
    val pemFile = "src/main/resources/private_key.pem"
    try {
      val jsch = new JSch
      jsch.addIdentity(pemFile)
      session = jsch.getSession(user, host, port)
      session.setConfig("StrictHostKeyChecking", "no")
      println("Establishing Connection")
      session.connect
      val assinged_port = session.setPortForwardingL(lport, rhost, rport)
      println("assinged_port" + assinged_port)
    } catch {
      case e: Exception => println("Message :" + e.getMessage)
    }
  }

   def main(args: Array[String]): Unit = {
    val rhost = "xxxx"
    connectSession(rhost)
    }
}
</code>```

Getting the below exception

```<code>Message :java.io.FileNotFoundException: src/main/resources/private_key.pem (No such file or directory)
</code>```

Note: The above code is working fine in microservice(GKE cluster) but it's not establishing the SSH connection in GCP Dataproc.

Body:
I'm trying to run the Spark job from GCP Dataproc. It's mainly reading data from AWS Oracle databases, so it connects to them via SSH. It's working fine locally, but not in the GCP Dataproc cluster.

import com.jcraft.jsch.Session
import org.apache.log4j.{Level, Logger}

object SSHTunnelService {
  def connectSession(rhost: String): Unit = {
    import com.jcraft.jsch.JSch
    var session: Session = null
    val user = "xxxx"

    val host = "xxxxxxx"
    val port = 22
    val lport = 1521
    val rport = 1521
    val pemFile = "src/main/resources/private_key.pem"
    try {
      val jsch = new JSch
      jsch.addIdentity(pemFile)
      session = jsch.getSession(user, host, port)
      session.setConfig("StrictHostKeyChecking", "no")
      println("Establishing Connection")
      session.connect
      val assinged_port = session.setPortForwardingL(lport, rhost, rport)
      println("assinged_port" + assinged_port)
    } catch {
      case e: Exception => println("Message :" + e.getMessage)
    }
  }

   def main(args: Array[String]): Unit = {
    val rhost = "xxxx"
    connectSession(rhost)
    }
}

Getting the below exception

Message :java.io.FileNotFoundException: src/main/resources/private_key.pem (No such file or directory)

Note: The above code is working fine in microservice(GKE cluster) but it's not establishing the SSH connection in GCP Dataproc.


问:
Cookies are not visible on front-end
I attach and clear cookies with folllowing functions

const attachCookies = async ({ res, token }) => {
    const oneDay = 1000 * 60 * 60 * 24
    res.cookie("token", token, {
        expires: new Date(Date.now() + oneDay),
        httpOnly: false,
        sameSite: "none",
        secure: true,
    })
}

const clearCookies = async ({ res }) => {
    res.clearCookie("token")
}
```
<p>Such a config for attaching cookies was chosen so cookies don't fly away when i access not <code>/</code> but <code>/products</code>. Right logic?
But now, on front-end (React + axios) I don't see cookies in Developer Console (there's just no such a field as <code>token</code>), although cookies work and i can access <code>/products</code>, <code>/bookmarks</code>, etc.
How to set cookies visible on React front-end side and then how to clear them when logging user out?</p>
<p>tried different configs for cookies, can't find the right one</p>
<p>my cors config btw:</p>
<pre class="lang-js prettyprint-override"><code>app.use(
    cors({
        credentials: true,
        // origin: ["http://localhost:5173"],
        origin: true,
        methods: ["GET", "POST", "PATCH", "DELETE"],
        allowedHeaders: ["Content-Type", "Authorization"],
    })
)
</code>```

update:

Attaching cookies:

const login = async (req, res) => {
    const token = createUserToken({ user: foundUser })
    attachCookies({ res, token })
    res.status(StatusCodes.OK).json({
        msg: "welcome back",
        user: foundUser,
    })
}
```
<ol start="2">
<li>making request with 'custom' axios instance</li>
</ol>
<pre class="lang-js prettyprint-override"><code>export const ozonAPI = axios.create({
    baseURL: "http://localhost:3000/api/v1",
    withCredentials: true,
})
</code>```

The request is in redux thunk, but I don't think it really matters

export const login = createAsyncThunk(
    "auth/login",
    async (credentials: dataType, thunkAPI) => {
        try {
            const resp = await ozonAPI("/auth/login", {
                method: "post",
                data: credentials,
            })
            return resp.data
        } catch (error: any) {
            return thunkAPI.rejectWithValue(error)
        }
    }
)
```

Title: Cookies are not visible on front-end

Body:
I attach and clear cookies with folllowing functions

const attachCookies = async ({ res, token }) => {
    const oneDay = 1000 * 60 * 60 * 24
    res.cookie("token", token, {
        expires: new Date(Date.now() + oneDay),
        httpOnly: false,
        sameSite: "none",
        secure: true,
    })
}

const clearCookies = async ({ res }) => {
    res.clearCookie("token")
}

Such a config for attaching cookies was chosen so cookies don't fly away when i access not / but /products. Right logic?
But now, on front-end (React + axios) I don't see cookies in Developer Console (there's just no such a field as token), although cookies work and i can access /products, /bookmarks, etc.
How to set cookies visible on React front-end side and then how to clear them when logging user out?

tried different configs for cookies, can't find the right one

my cors config btw:

app.use(
    cors({
        credentials: true,
        // origin: ["http://localhost:5173"],
        origin: true,
        methods: ["GET", "POST", "PATCH", "DELETE"],
        allowedHeaders: ["Content-Type", "Authorization"],
    })
)

update:

Attaching cookies:

const login = async (req, res) => {
    const token = createUserToken({ user: foundUser })
    attachCookies({ res, token })
    res.status(StatusCodes.OK).json({
        msg: "welcome back",
        user: foundUser,
    })
}

making request with 'custom' axios instance

export const ozonAPI = axios.create({
    baseURL: "http://localhost:3000/api/v1",
    withCredentials: true,
})

The request is in redux thunk, but I don't think it really matters

export const login = createAsyncThunk(
    "auth/login",
    async (credentials: dataType, thunkAPI) => {
        try {
            const resp = await ozonAPI("/auth/login", {
                method: "post",
                data: credentials,
            })
            return resp.data
        } catch (error: any) {
            return thunkAPI.rejectWithValue(error)
        }
    }
)


问:
Haskell: What is "!" in this definition of a Datatype using data

Background

I came across this syntax here. (lines 43-44 and 65-71)
I will adapt this to a minimally reproducible example like so:

data Bar = X | Y
data Baz = A | B

data Foo = Foo !Bar !Baz
```
<p>Here is an implementation for <code>Show</code>, if you desire one.</p>
<pre class="lang-hs prettyprint-override"><code>instance Show Bar where
  show X = "x"
  show Y = "y"

instance Show Baz where
  show A = "a"
  show B = "b"

instance Show Foo where
  show (Foo X t) = map C.toUpper $ show t
  show (Foo Y t) = show t
</code>```

Problem

Notice the definition of Foo. The sigil ! precedes its fields Bar and Baz. I do not understand what this signifies and am unable to find related documentation either. What does that mean?

Body:
Background

I came across this syntax here. (lines 43-44 and 65-71)
I will adapt this to a minimally reproducible example like so:

data Bar = X | Y
data Baz = A | B

data Foo = Foo !Bar !Baz

Here is an implementation for Show, if you desire one.

instance Show Bar where
  show X = "x"
  show Y = "y"

instance Show Baz where
  show A = "a"
  show B = "b"

instance Show Foo where
  show (Foo X t) = map C.toUpper $ show t
  show (Foo Y t) = show t

Problem

Notice the definition of Foo. The sigil ! precedes its fields Bar and Baz. I do not understand what this signifies and am unable to find related documentation either. What does that mean?


问:
Wordpress Autocomplete input field from custom non wordpress database table?
i have created custom table in my wordpress phpmyadmin, table structure is like below.
I dont want to modify my theme, so i have created templete searchpage in child theme directory.
I have searched many question to autocomplete data from custom database, but didn't find solution.
inspired from this answer as it has one/same page solution code i have tried searchbox.php in my child theme directory, i am getting data in json_encode but input field does not show any suggestion.

when i remove if else line of code, i am getting data from table but query always say false.
Any workable solution are appreciated. Thanks in advance.

Table Structure

```<code>CREATE TABLE IF NOT EXISTS `places` (
  `Place_Name` varchar(50) DEFAULT NULL,
  `Place_Code` varchar(5) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `places`
--

INSERT INTO `places` (`Place_Name`, `Place_Code`) VALUES
('COOPERS HALT', 'CPHT'),
('RANAGHAT JN', 'RHA'),
('RANAGHAT JN', 'RHA'),
('COOPERS HALT', 'CPHT'),
('NABA RAYNAGAR H', 'NBRN'),
('GANGNAPUR F', 'GGP'),
('MAJHERGRAM', 'MAJ'),
('AKAIPUR H', 'AKIP'),
('GOPALNAGAR F', 'GN'),
('SATBERIA H', 'STBB'),
('BANGAON JN', 'BNJ'),
('RANAGHAT JN', 'RHA'),
('BANKIMNAGAR H', 'BNKA'),
('PANCHBERIA H', 'PNCB'),
('ARANGHATA', 'AG'),
('BAHIRGACHHI H', 'BHGH'),
('BHAYNA H', 'BHNA');
COMMIT;
</code>```

Searchbox.php

```<code><?php /* Template Name: searchpage */ ?>
<?php get_header(); ?>

<?php

$query = isset($_GET['term']) ? $_GET['term'] : FALSE;

if ($query) {
    global $wpdb;
    // escape values passed to db to avoid sql-injection
    $depts = $wpdb->get_results( "SELECT DISTINCT Place_Name, Place_Code FROM places WHERE Place_Name LIKE '".$query."%'" );

    $suggestions = array();
    $data = array();
    foreach($depts as $row) {
        $suggestions[] = $row->Place_Name;
        $data[] = $row->Place_Code;
    }
    $response = array(
        'query' => $query,
        'suggestions' => $suggestions,
        'data' => $data,
    );
    echo json_encode($response);
} else {
?>
<html>
<body>
<input type="text" name="" id="box" />

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="http://www.devbridge.com/projects/autocomplete/jquery/local/scripts/jquery.autocomplete.js"></script>

<script type="text/javascript">

$(document).ready(function(){
    $('#box').autocomplete({
        serviceUrl:'/',
        // callback function:
        onSelect: function(value, data){ alert('You selected: ' + value + ', ' + data); },
    });
});
</script>
</body>
<html>
<?php } ?>

<?php get_header(); ?>
</code>```

what i am getting

Body:
i have created custom table in my wordpress phpmyadmin, table structure is like below.
I dont want to modify my theme, so i have created templete searchpage in child theme directory.
I have searched many question to autocomplete data from custom database, but didn't find solution.
inspired from this answer as it has one/same page solution code i have tried searchbox.php in my child theme directory, i am getting data in json_encode but input field does not show any suggestion.

when i remove if else line of code, i am getting data from table but query always say false.
Any workable solution are appreciated. Thanks in advance.

Table Structure

CREATE TABLE IF NOT EXISTS `places` (
  `Place_Name` varchar(50) DEFAULT NULL,
  `Place_Code` varchar(5) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `places`
--

INSERT INTO `places` (`Place_Name`, `Place_Code`) VALUES
('COOPERS HALT', 'CPHT'),
('RANAGHAT JN', 'RHA'),
('RANAGHAT JN', 'RHA'),
('COOPERS HALT', 'CPHT'),
('NABA RAYNAGAR H', 'NBRN'),
('GANGNAPUR F', 'GGP'),
('MAJHERGRAM', 'MAJ'),
('AKAIPUR H', 'AKIP'),
('GOPALNAGAR F', 'GN'),
('SATBERIA H', 'STBB'),
('BANGAON JN', 'BNJ'),
('RANAGHAT JN', 'RHA'),
('BANKIMNAGAR H', 'BNKA'),
('PANCHBERIA H', 'PNCB'),
('ARANGHATA', 'AG'),
('BAHIRGACHHI H', 'BHGH'),
('BHAYNA H', 'BHNA');
COMMIT;

Searchbox.php

<?php /* Template Name: searchpage */ ?>
<?php get_header(); ?>

<?php

$query = isset($_GET['term']) ? $_GET['term'] : FALSE;

if ($query) {
    global $wpdb;
    // escape values passed to db to avoid sql-injection
    $depts = $wpdb->get_results( "SELECT DISTINCT Place_Name, Place_Code FROM places WHERE Place_Name LIKE '".$query."%'" );

    $suggestions = array();
    $data = array();
    foreach($depts as $row) {
        $suggestions[] = $row->Place_Name;
        $data[] = $row->Place_Code;
    }
    $response = array(
        'query' => $query,
        'suggestions' => $suggestions,
        'data' => $data,
    );
    echo json_encode($response);
} else {
?>

<input type="text" name="" id="box" />

<?php } ?>

<?php get_header(); ?>

what i am getting


问:
After switching out bottom navigation fragments, LinearProgressIndicator immediately changes to 0 progress in Android
I am using the below library for bottom navigation in Android using Kotlin.

implementation 'com.github.ibrahimsn98:SmoothBottomBar:1.7.9'

I have three fragments, the first of which has a LinearProgressIndicator with some progress. However, when switching to a different tab in the bottom navigation and returning to the same screen, the LinearProgressIndicator shows zero progress.

Any help will be appreciated.

Thanks in Advance.


问:
Hibernate LazyInitializationException
I am trying to get the versions field within my MachineGroup Entity that is ManyToMany relationship. I am trying to fetch it in a custom serializer using ObjectMapper but for some reason I always get the LazyInitializationException - org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.altair.autoTester.entities.machinegroup.MachineGroup.versions, could not initialize proxy - no Session.

MachineGroup

```<code>@Entity
@Table(name="machine_groups")
@Getter
@Setter
@AllArgsConstructor(access = AccessLevel.PUBLIC)
@NoArgsConstructor
public class MachineGroup {
@Id
    @GeneratedValue(strategy= GenerationType.AUTO, generator = "machine_groups_seq")
    @SequenceGenerator(name = "machine_groups_seq", allocationSize = 1, initialValue = 2)
    @Column(name = "id")
    private long id;
@ManyToMany(cascade = CascadeType.MERGE)
    @JoinTable(name = "machine_groups_to_versions",
            joinColumns = @JoinColumn(name = "machine_group_id"),
            inverseJoinColumns = @JoinColumn(name = "version_id"))
    @JsonManagedReference(value="machineGroups-versions")
    private Set<Version> versions = new HashSet<>();
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "machine_groups_to_tr_types",
            joinColumns = @JoinColumn(name = "machine_group_id"),
            inverseJoinColumns = @JoinColumn(name = "tr_type_id"))
    private Set<TrType> trTypes = new HashSet<>();
}
</code>```

Version.java

```<code>@Entity
@Table(name="versions")
@Getter
@Setter
public class Version {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "versions_seq")
    @SequenceGenerator(name = "versions_seq", allocationSize = 1)
    @Column(name = "id")
    private long id;
    @Column(name = "name", unique = true)
    private String name;
    @Column(name = "creation_time")
    private Date creationTime;
    @Column(name = "exe_file")
    @Lob
    private Blob exeFile;
    @JsonBackReference(value="machineGroups-versions")
    @ManyToMany(mappedBy = "versions", cascade = CascadeType.MERGE)
    private Set<MachineGroup> machineGroups = new HashSet<>();

    public Version(){};

    public Version(String name) {
        this.name = name;
    }
}
</code>```

MachineGroupSerializer.java

```<code>public class MachineGroupSerializer extends StdSerializer<MachineGroup> {

    public MachineGroupSerializer() {
        this(null);
    }

    public MachineGroupSerializer(Class<MachineGroup> t) {
        super(t);
    }

@Transactional
    @Override
    public void serialize(MachineGroup machineGroup,
                          JsonGenerator jsonGenerator,
                          SerializerProvider serializerProvider) throws IOException {

        jsonGenerator.writeStartObject();
        jsonGenerator.writeNumberField("id",machineGroup.getId());
        jsonGenerator.writeObjectField("versions", machineGroup.getVersions().stream().map(Version::getId).collect(Collectors.toSet()));
      jsonGenerator.writeObjectField("trTypes", machineGroup.getTrTypes().stream().map(TrType::getId).collect(Collectors.toSet()));

        jsonGenerator.writeEndObject();
    }
}

</code>```

TrTypes.java

```<code>@Table(name = "tr_types", indexes = {
        @Index(name = "tr_types_type_name_uindex", columnList = "type_name", unique = true)
})
@Entity
@AllArgsConstructor(access = AccessLevel.PUBLIC)
@NoArgsConstructor
public class TrType {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long id;

    @Column(name = "type_name", nullable = false)
    private String typeName;
}
</code>```

I put the JsonManagedReference and JsonBackReference so I won't have infinite loop calling one another, not sure if it's causing any issues.

Calling the getTrTypes() function works but has the EAGER fetchType which I do not want to add to the versions collection.

What can cause this lazy exception to occur and how can I prevent it?

Also the function calling the serialzier within my MachineGroupService has the @Transactional annotation, I saw something that is related to the hibernate session that might be close at the serializer level.

Title: Hibernate LazyInitializationException

Body:
I am trying to get the versions field within my MachineGroup Entity that is ManyToMany relationship. I am trying to fetch it in a custom serializer using ObjectMapper but for some reason I always get the LazyInitializationException - org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.altair.autoTester.entities.machinegroup.MachineGroup.versions, could not initialize proxy - no Session.

MachineGroup

@Entity
@Table(name="machine_groups")
@Getter
@Setter
@AllArgsConstructor(access = AccessLevel.PUBLIC)
@NoArgsConstructor
public class MachineGroup {
@Id
    @GeneratedValue(strategy= GenerationType.AUTO, generator = "machine_groups_seq")
    @SequenceGenerator(name = "machine_groups_seq", allocationSize = 1, initialValue = 2)
    @Column(name = "id")
    private long id;
@ManyToMany(cascade = CascadeType.MERGE)
    @JoinTable(name = "machine_groups_to_versions",
            joinColumns = @JoinColumn(name = "machine_group_id"),
            inverseJoinColumns = @JoinColumn(name = "version_id"))
    @JsonManagedReference(value="machineGroups-versions")
    private Set<Version> versions = new HashSet<>();
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "machine_groups_to_tr_types",
            joinColumns = @JoinColumn(name = "machine_group_id"),
            inverseJoinColumns = @JoinColumn(name = "tr_type_id"))
    private Set<TrType> trTypes = new HashSet<>();
}

Version.java

@Entity
@Table(name="versions")
@Getter
@Setter
public class Version {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "versions_seq")
    @SequenceGenerator(name = "versions_seq", allocationSize = 1)
    @Column(name = "id")
    private long id;
    @Column(name = "name", unique = true)
    private String name;
    @Column(name = "creation_time")
    private Date creationTime;
    @Column(name = "exe_file")
    @Lob
    private Blob exeFile;
    @JsonBackReference(value="machineGroups-versions")
    @ManyToMany(mappedBy = "versions", cascade = CascadeType.MERGE)
    private Set<MachineGroup> machineGroups = new HashSet<>();

    public Version(){};

    public Version(String name) {
        this.name = name;
    }
}

MachineGroupSerializer.java

public class MachineGroupSerializer extends StdSerializer<MachineGroup> {

    public MachineGroupSerializer() {
        this(null);
    }

    public MachineGroupSerializer(Class<MachineGroup> t) {
        super(t);
    }

@Transactional
    @Override
    public void serialize(MachineGroup machineGroup,
                          JsonGenerator jsonGenerator,
                          SerializerProvider serializerProvider) throws IOException {

        jsonGenerator.writeStartObject();
        jsonGenerator.writeNumberField("id",machineGroup.getId());
        jsonGenerator.writeObjectField("versions", machineGroup.getVersions().stream().map(Version::getId).collect(Collectors.toSet()));
      jsonGenerator.writeObjectField("trTypes", machineGroup.getTrTypes().stream().map(TrType::getId).collect(Collectors.toSet()));

        jsonGenerator.writeEndObject();
    }
}

TrTypes.java

@Table(name = "tr_types", indexes = {
        @Index(name = "tr_types_type_name_uindex", columnList = "type_name", unique = true)
})
@Entity
@AllArgsConstructor(access = AccessLevel.PUBLIC)
@NoArgsConstructor
public class TrType {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long id;

    @Column(name = "type_name", nullable = false)
    private String typeName;
}

I put the JsonManagedReference and JsonBackReference so I won't have infinite loop calling one another, not sure if it's causing any issues.

Calling the getTrTypes() function works but has the EAGER fetchType which I do not want to add to the versions collection.

What can cause this lazy exception to occur and how can I prevent it?

Also the function calling the serialzier within my MachineGroupService has the @Transactional annotation, I saw something that is related to the hibernate session that might be close at the serializer level.


问:
Visual Studio IDE 2022 - how to disable navigation to decompiled sources
I've enabled 'navigation to decompiled sources' in my Visual Studio IDE according to this answer.

Now I can't disable it. Turning off Enable navigation to decompiled sources option does not helps.

Please help me! I want to see metadata instead of decompiled source definitions again.


问:
How to extract images from in Photoshop pdf in Linux?
More and more designers using Photoshop are saving images in pdf format.

I tried Gimp but it doesn't see the layers and other format details.

Any solutions ?

The basic thing I try to do is to get the original images from the pdf with all layers not flatten.

ContentLicense: CC BY-SA 3.0


问:
I want an MS TOC entry which is different from the text it points to - like an Epigram - I want the word 'Epigram' not the actual Epigram
I want an entry in my TOC (that was created with Headings 1, 2 & 3) that is not the same as the text it points to. So I want to have the word 'Epigram' in the TOC but I want some text like; 'For Joey and Suzy, thanks for all the help' to appear on the page as the 'target' for the 'Epigram' entry in the TOC.

Hope that is clear ! Thanks for any help, much appreciated.

Have only tried googling this but difficult to describe in a 'searchy' way.


问:
Does C execute printf() statements past scanf() statements in a program?
The C syntax question is: does C execute printf() statements past scanf() statements below it? I have learned about the concept of side effects and sequence points. Could side effects of scanf() be delayed behind the side effects of printf() which are actually further down the code?

To illustrate the question above, here is some context:
I am working on a simple guessing game C program, where the program tries to guess the number the user has in mind between 1-100. Currently, my program looks like this and is erroneous:

#include <stdio.h>
#include <stdbool.h>    // bool

int higherBound = 100;  // global variables for nextGuess
int lowerBound = 1;

int nextGuess(int prevGuess, bool isHigher)
{
    /*if the feedback is that truth isHigher, then the program
    takes the mid point between prevGuess and higherBound. Otherwise,
    take the mid point between prevGuess and lowerBound.*/
    int newGuess;
    if (isHigher){
        newGuess = (prevGuess + higherBound) / 2;   // integer divide will truncate
    } else {
        newGuess = (prevGuess + lowerBound) / 2;
    }
    return newGuess;
}

int main(void)
{
    int guess = 50;
    printf("Pick an integer from 1 to 100. I will try to guess ");
    printf("it.\nRespond with a y if my guess is right and with");
    printf("\nan n if it is wrong.\n");
    printf("Uh...is your number %d?\n", guess);
    bool isHigher = false;
    char answerToGuess;
    char answerToHigher;
    scanf("%c",&answerToGuess);
    while (answerToGuess != 'y'){
        answerToHigher = ' ';   // reset user answer
        do {
            printf("Okay, is your number higher than my guess? (y/n)\n");
            scanf("%c", &answerToHigher);
        } while (answerToHigher != 'y' && answerToHigher != 'n');
        if (answerToHigher == 'y'){
            isHigher = true;
            lowerBound = guess; // update lower bound
        }
        else if (answerToHigher == 'n'){
            isHigher = false;
            higherBound = guess;
        }
        printf("Well, then, is it %d?\n", guess = nextGuess(guess, isHigher));
        scanf("%c",&answerToGuess);
    }
    printf("I knew I could do it!\n");
    return 0;
}
```
<p>When I run it, what I did not expect to happen was that the line <code>Okay, is your number higher than my guess?</code> always gets printed twice (say the number I have in mind is 60) as if the side effect of printf() penetrated the scanf() line atthe end of the outer while loop:</p>
```Pick an integer from 1 to 100. I will try to guess it.
Respond with a y if my guess is right and with
an n if it is wrong.
Uh...is your number 50?
n
Okay, is your number higher than my guess? (y/n)
Okay, is your number higher than my guess? (y/n)
y
Well, then, is it 75?
Okay, is your number higher than my guess? (y/n)
n
Well, then, is it 50?
Okay, is your number higher than my guess? (y/n)
n
Well, then, is it 50?
Okay, is your number higher than my guess? (y/n)
Okay, is your number higher than my guess? (y/n)
```
<p>So what is the reason that this line gets printed twice every time?</p>
<p>I have tried to debug using the VS code built-in debugger, but the behavior is different from the terminal execution.</p>
<p>EDIT:
problem solved thanks to a suggestion by @Retired_Ninja: add a whitespace inside the format strings of <code>scanf()</code>. So after I modify <code>scanf("%c", &answerToHigher);</code> into <code>scanf("% c", &answerToHigher);</code> and modify <code>scanf("%c", &answerToGuess);</code> into <code>scanf("% c", &answerToGuess);</code>, the program runs as intended.</p>
<p>The root cause, however, is not what I thought. This problem has nothing to do with side effects and sequence points. The root cause was that <code>scanf()</code> took something left over in the buffer (the <code>\n</code> from previous <code>scanf()</code> operations), and it looks as if <code>scanf()</code> was skipped. It was not; it was simply consuming the <code>\n</code>'s "hidden" from my eyes and awareness.</p>
<p>The problem could have been avoided if I had followed some of the best practices for using <code>scanf()</code> or, in general, using <code>stdin</code> buffer. The <code>scanf()</code> best practice is that you should check the return value of <code>scanf()</code> and make sure it is not zero (zero indicates matching failure).</p>
<p>My elevated understanding:</p>
<ol>
<li><p><code>scanf()</code> paired with <code>%c</code> as its format string will NOT automatically skip leading whitespace characters (<code>' '</code>, <code>\n</code>, <code>\t</code>, <code>\r</code>) in the <code>stdin</code> buffer. As a result, if there are indeed leftover whitespaces from previous keyboard inputs (such as <code>\n</code> which are very common), then these whitespaces will be accidentally taken by <code>scanf()</code> and assigned to variables specified during the <code>scanf()</code> call.</p>
</li>
<li><p>This not-automatically-skipping-leading-whitespace behavior happens only with <code>%c</code>, <code>%n</code>, <code>%[scanset]</code> format strings. For other format strings (e.g., <code>%d</code>, <code>%f</code>), <code>scanf()</code> WILL automatically skip leading whitespaces.</p>
</li>
<li><p>Best practice: in fact, the best practice is NOT what the answer suggested (using <code>"% c"</code> instead of <code>"%c</code>). The best practice is to always clean up the <code>stdin</code> buffer of leftover "garbage" immediately after some keyboard operation. For example, in the code above, after ANY <code>scanf()</code> call, there should be a BUFFER-CLEANUP section of code:</p>
</li>
</ol>
<pre class="lang-c prettyprint-override"><code>// consume all trailing buffer contents up to a '\n' character
// (including the '\n') and dispose of them from the buffer
while (getchar() != '\n')
    continue;
</code>```

For double security, you can combine the above buffer-cleaning code with scanf(" %c", &ch);. More typing but this gets you double safety.

Another best practice (often not followed) is to always check the return value of scanf() and verify if the variable gets assigned (i.e., verify if matching failure occured):

```<code>char ch;
if (scanf("%c", &ch) == 0){
    perror("scanf() failed to assign value.");
    exit(-1);
}
</code>```

Body:
The C syntax question is: does C execute printf() statements past scanf() statements below it? I have learned about the concept of side effects and sequence points. Could side effects of scanf() be delayed behind the side effects of printf() which are actually further down the code?

To illustrate the question above, here is some context:
I am working on a simple guessing game C program, where the program tries to guess the number the user has in mind between 1-100. Currently, my program looks like this and is erroneous:

#include <stdio.h>
#include <stdbool.h>    // bool

int higherBound = 100;  // global variables for nextGuess
int lowerBound = 1;

int nextGuess(int prevGuess, bool isHigher)
{
    /*if the feedback is that truth isHigher, then the program
    takes the mid point between prevGuess and higherBound. Otherwise,
    take the mid point between prevGuess and lowerBound.*/
    int newGuess;
    if (isHigher){
        newGuess = (prevGuess + higherBound) / 2;   // integer divide will truncate
    } else {
        newGuess = (prevGuess + lowerBound) / 2;
    }
    return newGuess;
}

int main(void)
{
    int guess = 50;
    printf("Pick an integer from 1 to 100. I will try to guess ");
    printf("it.\nRespond with a y if my guess is right and with");
    printf("\nan n if it is wrong.\n");
    printf("Uh...is your number %d?\n", guess);
    bool isHigher = false;
    char answerToGuess;
    char answerToHigher;
    scanf("%c",&answerToGuess);
    while (answerToGuess != 'y'){
        answerToHigher = ' ';   // reset user answer
        do {
            printf("Okay, is your number higher than my guess? (y/n)\n");
            scanf("%c", &answerToHigher);
        } while (answerToHigher != 'y' && answerToHigher != 'n');
        if (answerToHigher == 'y'){
            isHigher = true;
            lowerBound = guess; // update lower bound
        }
        else if (answerToHigher == 'n'){
            isHigher = false;
            higherBound = guess;
        }
        printf("Well, then, is it %d?\n", guess = nextGuess(guess, isHigher));
        scanf("%c",&answerToGuess);
    }
    printf("I knew I could do it!\n");
    return 0;
}

When I run it, what I did not expect to happen was that the line Okay, is your number higher than my guess? always gets printed twice (say the number I have in mind is 60) as if the side effect of printf() penetrated the scanf() line atthe end of the outer while loop:

Pick an integer from 1 to 100. I will try to guess it.
Respond with a y if my guess is right and with
an n if it is wrong.
Uh...is your number 50?
n
Okay, is your number higher than my guess? (y/n)
Okay, is your number higher than my guess? (y/n)
y
Well, then, is it 75?
Okay, is your number higher than my guess? (y/n)
n
Well, then, is it 50?
Okay, is your number higher than my guess? (y/n)
n
Well, then, is it 50?
Okay, is your number higher than my guess? (y/n)
Okay, is your number higher than my guess? (y/n)

So what is the reason that this line gets printed twice every time?

I have tried to debug using the VS code built-in debugger, but the behavior is different from the terminal execution.

EDIT:
problem solved thanks to a suggestion by @Retired_Ninja: add a whitespace inside the format strings of scanf(). So after I modify scanf("%c", &answerToHigher); into scanf("% c", &answerToHigher); and modify scanf("%c", &answerToGuess); into scanf("% c", &answerToGuess);, the program runs as intended.

The root cause, however, is not what I thought. This problem has nothing to do with side effects and sequence points. The root cause was that scanf() took something left over in the buffer (the \n from previous scanf() operations), and it looks as if scanf() was skipped. It was not; it was simply consuming the \n's "hidden" from my eyes and awareness.

The problem could have been avoided if I had followed some of the best practices for using scanf() or, in general, using stdin buffer. The scanf() best practice is that you should check the return value of scanf() and make sure it is not zero (zero indicates matching failure).

My elevated understanding:

scanf() paired with %c as its format string will NOT automatically skip leading whitespace characters (' ', \n, \t, \r) in the stdin buffer. As a result, if there are indeed leftover whitespaces from previous keyboard inputs (such as \n which are very common), then these whitespaces will be accidentally taken by scanf() and assigned to variables specified during the scanf() call.

This not-automatically-skipping-leading-whitespace behavior happens only with %c, %n, %[scanset] format strings. For other format strings (e.g., %d, %f), scanf() WILL automatically skip leading whitespaces.

Best practice: in fact, the best practice is NOT what the answer suggested (using "% c" instead of "%c). The best practice is to always clean up the stdin buffer of leftover "garbage" immediately after some keyboard operation. For example, in the code above, after ANY scanf() call, there should be a BUFFER-CLEANUP section of code:

// consume all trailing buffer contents up to a '\n' character
// (including the '\n') and dispose of them from the buffer
while (getchar() != '\n')
    continue;

For double security, you can combine the above buffer-cleaning code with scanf(" %c", &ch);. More typing but this gets you double safety.

Another best practice (often not followed) is to always check the return value of scanf() and verify if the variable gets assigned (i.e., verify if matching failure occured):

char ch;
if (scanf("%c", &ch) == 0){
    perror("scanf() failed to assign value.");
    exit(-1);
}


问:
I want to draw a moving line that will fill all 4 sides of a text in 2 seconds with css, but it didn't work, how can I do it?
Case 1

Case 2

This way it goes all the way to the end of the article. I managed to do it horizontally, but I couldn't manage to make all 4 sides. Is there anyone who can help?

I planned to make a line that fills all 4 sides of the text in 2 seconds, but I was only able to make horizontal down and up. I couldn't make the right and left edges

the code is like tenter code herehis

#hayati::before {
  content: "";
  position: absolute;
  bottom: 0;
  width: 0;
  height: 2px;
  box-shadow: 2px 2px 2px;
  transition: 2s;
  background-color: rgb(111, 241, 71);}

#hayati:hover::before {
  box-shadow: 2px 2px 2px;
  width: 100%;
}

#hayati::after {
  content: "";
  position: absolute;
  right: 0;
  top: -4px;
  width: 0;
  height: 2px;
  transition: width 1.5s ease-out;
  box-shadow: 2px 2px 2px;
  background-color: rgb(111, 241, 71);
}

#hayati:hover::after {
  width: 100%;
}
```


问:
How do I make an object follow a rectangular path at a constant speed in pygame?
I have tried multiple ways, but none seem to work
I have a list called route which contains tiles and an enemy
eg route = [(200,100), (300,100), (400,100), (400,200), (400,300)]
and i want the rectangle enemy to go to the first location, and once its there go to the next one until the last position, all doing that at a constant speed

i = 0 # global variable outside of class
if len(route) > 0:

```<code>change_x = route[i].tile_rect.x - self.enemy_rect.x
change_y = route[i].tile_rect.y - self.enemy_rect.y
for x in range(change_x):

    if self.enemy_rect.x < route[i].tile_rect.x:
        diff_x += 1

    if self.enemy_rect.x > route[i].tile_rect.x:
        diff_x -= 1

for y in range(change_y):

    if self.enemy_rect.y < route[i].tile_rect.y:
        diff_y += 1

    if self.enemy_rect.y > route[i].tile_rect.y:
        diff_y -= 1
</code>```

self.enemy_rect.x += diff_x
self.enemy_rect.y += diff_y

```<code>the problem here is it does what is expected, but moves way too quickly. If i try to change the amount it is incrementing by, it doesnt reach the next target
i tried using a while loop, but it the window just stops responding

maybe i could do it using a the Vector2, but i just dont know how to
</code>```

Body:
I have tried multiple ways, but none seem to work
I have a list called route which contains tiles and an enemy
eg route = [(200,100), (300,100), (400,100), (400,200), (400,300)]
and i want the rectangle enemy to go to the first location, and once its there go to the next one until the last position, all doing that at a constant speed

i = 0 # global variable outside of class
if len(route) > 0:

change_x = route[i].tile_rect.x - self.enemy_rect.x
change_y = route[i].tile_rect.y - self.enemy_rect.y
for x in range(change_x):

    if self.enemy_rect.x < route[i].tile_rect.x:
        diff_x += 1

    if self.enemy_rect.x > route[i].tile_rect.x:
        diff_x -= 1

for y in range(change_y):

    if self.enemy_rect.y < route[i].tile_rect.y:
        diff_y += 1

    if self.enemy_rect.y > route[i].tile_rect.y:
        diff_y -= 1

self.enemy_rect.x += diff_x
self.enemy_rect.y += diff_y

the problem here is it does what is expected, but moves way too quickly. If i try to change the amount it is incrementing by, it doesnt reach the next target
i tried using a while loop, but it the window just stops responding

maybe i could do it using a the Vector2, but i just dont know how to


问:
Convert google colab file running Omnizart to Jupyter Notebook file
A google colab file runs the Omnizart python package which converts mp3/youtube songs to MIDI files. Although I was able to run the Environment Setup portion of the google colab file, but it runs for a long time without ending when I run the Choose from Youtube portion.

Would it possible to convert the code in the google colab file so that it runs on the Jupyter Notebook in Windows?


问:
QWebEngineView and leaflet.js slow performance
I am making desktop app in Python (3.8.10) using QML frontend (Qt 6.4.1)

The principle is that I take data from a CSV file and load it into a pandas dataframe. The data contains coordinates that I want to display on a map using the folium library. Since I also want to display all the data, which can have thousands of records, I need to use clusters (folium.plugins.FasterMarkerCluster)
https://deparkes.co.uk/2016/06/24/folium-marker-clusters/

I create a map instance in a python class, insert points and create clusters

```<code>@staticmethod
def add_all_crime_types(map: MapObject, df: pd.DataFrame) -> None:
    # Removing duplicates
    df_filtered = df.drop_duplicates(subset='id', keep='first')
    # Adding points to MarkerClusters and then adding MarkerClusters to the map
    folium.plugins.FastMarkerCluster(data=list(zip(df_filtered['x'], df_filtered['y'])), callback=DEFAULT_CALLBACK).add_to(map.m)
</code>```

Then I convert the map instance into a string and send it to the frontend, where I load it using the webView.loadHTML(string) method

```<code>Item {
    id: item_showMap

    Connections {
        target: backend

        function onGetHTML(html) { webView.loadHtml(html) }
    }

    Rectangle {
        id: rectangle
        color: "#d4d4d4"
        anchors.fill: parent
        anchors.rightMargin: -320
        anchors.bottomMargin: 0
        anchors.leftMargin: -320
        anchors.topMargin: 1

        WebEngineView {
            id: webView
            anchors.fill: parent
        }

        Component.onCompleted: backend.create_default_map()
    }
}
</code>```

Unfortunately, despite using clusters, performance is very poor, especially when scrolling. It is possible that hardware acceleration is disabled? Or some other feature? Maybe If there is another, more performance friendly, way to render the points.

I have tried another marker styling, using marker clusters and faster marker clusters.

Body:
I am making desktop app in Python (3.8.10) using QML frontend (Qt 6.4.1)

The principle is that I take data from a CSV file and load it into a pandas dataframe. The data contains coordinates that I want to display on a map using the folium library. Since I also want to display all the data, which can have thousands of records, I need to use clusters (folium.plugins.FasterMarkerCluster)
https://deparkes.co.uk/2016/06/24/folium-marker-clusters/

I create a map instance in a python class, insert points and create clusters

@staticmethod
def add_all_crime_types(map: MapObject, df: pd.DataFrame) -> None:
    # Removing duplicates
    df_filtered = df.drop_duplicates(subset='id', keep='first')
    # Adding points to MarkerClusters and then adding MarkerClusters to the map
    folium.plugins.FastMarkerCluster(data=list(zip(df_filtered['x'], df_filtered['y'])), callback=DEFAULT_CALLBACK).add_to(map.m)

Then I convert the map instance into a string and send it to the frontend, where I load it using the webView.loadHTML(string) method

Item {
    id: item_showMap

    Connections {
        target: backend

        function onGetHTML(html) { webView.loadHtml(html) }
    }

    Rectangle {
        id: rectangle
        color: "#d4d4d4"
        anchors.fill: parent
        anchors.rightMargin: -320
        anchors.bottomMargin: 0
        anchors.leftMargin: -320
        anchors.topMargin: 1

        WebEngineView {
            id: webView
            anchors.fill: parent
        }

        Component.onCompleted: backend.create_default_map()
    }
}

Unfortunately, despite using clusters, performance is very poor, especially when scrolling. It is possible that hardware acceleration is disabled? Or some other feature? Maybe If there is another, more performance friendly, way to render the points.

I have tried another marker styling, using marker clusters and faster marker clusters.


问:
Installation process in MongoDB database
installation error while starting my mongodb server..

```<code>Ensure the user executing mongod is the owner of the lock file
and has the appropriate permissions. Also make sure that another
mongod instance is not already running on the C:\\data\\db\\ directory
</code>```

how to start a server in my windows mongodb version--6.0.3

Body:
installation error while starting my mongodb server..

Ensure the user executing mongod is the owner of the lock file
and has the appropriate permissions. Also make sure that another
mongod instance is not already running on the C:\\data\\db\\ directory

how to start a server in my windows mongodb version--6.0.3


问:
Routing CxDx messages in FreeDiameter?
I am trying to send CxDx Messages from Kamailio(I-CSCF) to our HSS in production, the issue is that HSS accepts SCTP whilst the Kamailio Diameter module (CDP) only supports TCP (grrr).....

I came up with the great idea of using freeDiameter as a DRA in between, the problem is that I can't seem to find a working CxDx extension. there seems to be one in the contrib folder but I spent a day trying to compile it on debian 22.04 to no avail,

Is there a way to compile the extension or create the application using another extension?

thanks

Title: Routing CxDx messages in FreeDiameter?


问:
My ThreeJS code is not working, can someone help me?
It doesn't show me any problem, but unfortunately my code doesn't work at all and I can't figure out what the error is.

I tried every way, I looked for an error everywhere but it didn't show me any error anywhere. I have everything connected as it should.

```<code><html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/three@0.117.1/build/three.min.js"></script>
  </head>
  <body>
    <script>
      // create a scene
      var scene = new THREE.Scene();

      // create a camera
      var camera = new THREE.PerspectiveCamera(
        75,
        window.innerWidth / window.innerHeight,
        0.1,
        1000
      );
      camera.aspect = window.innerWidth / window.innerHeight;

      camera.position.set(0, 0, 100);

      // create a renderer
      var renderer = new THREE.WebGLRenderer();
      renderer.setSize(window.innerWidth, window.innerHeight);
      document.body.appendChild(renderer.domElement);

      // create a plane geometry
      var geometry = new THREE.PlaneGeometry(100, 100, 1, 1);

      // create a shiny, glossy material for the floor
      var material = new THREE.MeshPhongMaterial({
        color: 0xffffff,
        shininess: 100,
      });

      // create a mesh using the plane geometry and material
      var floor = new THREE.Mesh(geometry, material);

      // set the position of the floor
      floor.position.set(0, 0, 0);

      // add the floor to the scene
      scene.add(floor);

      // render the scene
      function render() {
        requestAnimationFrame(render);
        renderer.render(scene, camera);
      }
      render();
    </script>
  </body>
</html>
</code>```

Body:
It doesn't show me any problem, but unfortunately my code doesn't work at all and I can't figure out what the error is.

I tried every way, I looked for an error everywhere but it didn't show me any error anywhere. I have everything connected as it should.

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>


问:
How do I parse the custom html widget in cheerio?
I'm trying to scrape the data from a website using Axios and cheerio in nodejs but the problem is I couldn't get the desired value as the HTML is different here, The HTML is given below

```<code><div id="cars">
    <new-chart-modal
      :template-widgets-json='[{id: 1, Value: "10000"},{id: 2, Value: "20000"}]'
      @close-widget-modal="closeWidgetModal"
      @loaded-widget-template="loadedWidgetTemplate"
      ref="newWidgetModal"
    >
    </new-chart-modal>
    <dashboard-grid
      :widgets-json='[{id: 1, name: "Volvo"}, {id: 2, name: "BMW"}]'
      @edit-in-tab="editWidgetInTab"
      ref="grid"
    >
    </dashboard-grid>
  </div>
</code>```

In the above HTML, I need to get the value of :widgets-json inside the dashboard-grid tag alone, but I'm unable to do it. I looking for some answers or tips to get the value of :widgets-json inside the  which is [{id: 1, name: "Volvo"}, {id: 2, name: "BMW"}]. can somebody please help me out? Thanks in advance.

Body:
I'm trying to scrape the data from a website using Axios and cheerio in nodejs but the problem is I couldn't get the desired value as the HTML is different here, The HTML is given below

    <new-chart-modal
      :template-widgets-json='[{id: 1, Value: "10000"},{id: 2, Value: "20000"}]'
      @close-widget-modal="closeWidgetModal"
      @loaded-widget-template="loadedWidgetTemplate"
      ref="newWidgetModal"
    >
    </new-chart-modal>
    <dashboard-grid
      :widgets-json='[{id: 1, name: "Volvo"}, {id: 2, name: "BMW"}]'
      @edit-in-tab="editWidgetInTab"
      ref="grid"
    >
    </dashboard-grid>

In the above HTML, I need to get the value of :widgets-json inside the dashboard-grid tag alone, but I'm unable to do it. I looking for some answers or tips to get the value of :widgets-json inside the  which is [{id: 1, name: "Volvo"}, {id: 2, name: "BMW"}]. can somebody please help me out? Thanks in advance.


问:
I want to create a VBA based on the template below
I want to create a VBA based on the template below, but i got an error and not what i expected.

```<code>MOD 001/DCO CHECKLIST PARTNERS

Version 5.22

PARTNER DATA

Company:____________________________________________________
Household:  __________________________________________________
Email:  ______________________________________@_______________________________
Contact: _______________________________
Manager: _______________________________
Number of Stores: _______________________________                                                                                Ref. SAP: _______________________________

KIT
SERVICE - DEMO BOX / COMMUNICATION APP
YES NO
CARD ID: _______________________________ POINT
FLY BANNERYES NO
CAS ID: POSTERS/LEAFLETS YES NO
STICKERSYES NO
HOLDER HOLDER YES NO
TV ON: YES/NO BANK
CHANNEL:____________ PACKAGE:____________ GAZEBO
 PAINTING
                                                                                OTHERS _____________

FULL HD TV: YES               APP AGENTS YES NO
NOT IN USE:  YES NO

ACTIVATION STATISTICAL DATA

NR. OF ACTIVATIONS IN THE MONTH OF: : DATE OF LAST PURCHASE:

 PRODUCTS
REFILL BOXES AND ACCESSORIES
                                ARP
HD+                 QTY____ NO____      QTY____ NO____
INSTALLATION KITS       QTY____ NO____      150 'S QTY____ NO____
COMMANDS            QTY____ NO____      300 'S QTY____ NO____
TRANSFORMERS                QTY____ NO____          600 'S QTY____ NO____
 CARDS              QTY____ NO____

COMPETITION

NOTE:_____________________________________

DSTV        QTY____ NO
GOTV        QTY____ NO
STARTIMES   QTY____ NO
TMT         QTY____ NO
OTHER       QTY____ NO
MERCHANDISING   NO
PAINTING        NO

BY : _______________________________ BY PARTNER: _______________________________

DATE: ________/_________/______________ DATE: ________/_________/______________

```

```
<p>I tried the VBA below</p>
<pre class="lang-vb prettyprint-override"><code>Sub Button1_Click()
'Call the FillTemplate function

' Declare variables to store the data from the template
Dim company As String
Dim address As String
Dim email As String
Dim contact As String
Dim manager As String
Dim numStores As Long
Dim SAPRef As String
Dim cardID As String
Dim CASID As String
Dim TVOn As String
Dim TVChannel As String
Dim TVPackage As String
Dim TVFullHD As String
Dim appAgents As String
Dim appInUse As String
Dim cardholders As Long
Dim webAgents As String
Dim webInUse As String
Dim signature As String

' Prompt the user to enter the data for each field
company = InputBox("Enter the company name:")
address = InputBox("Enter the address:")
email = InputBox("Enter the email address:")
contact = InputBox("Enter the contact:")
manager = InputBox("Enter the manager:")
numStores = Val(InputBox("Enter the number of stores:"))
SAPRef = InputBox("Enter the SAP reference:")
cardID = InputBox("Enter the CARD ID:")
CASID = InputBox("Enter the CAS ID:")
TVOn = InputBox("Is the TV on? (Yes/No)")
TVChannel = InputBox("Enter the TV channel:")
TVPackage = InputBox("Enter the TV package:")
TVFullHD = InputBox("Is the TV Full HD? (Yes/No)")
appAgents = InputBox("Is the APP AGENTS service in use? (Yes/No)")
appInUse = InputBox("Enter the APP in use:")
cardholders = Val(InputBox("Enter the number of CARDHOLDERS:"))
webAgents = InputBox("Is the WEB AGENTS service in use? (Yes/No)")
webInUse = InputBox("Enter the WEB in use:")
signature = InputBox("Enter the signage:")

' Read the data from the table
company = Worksheets("Data").Range("A2").Value
address = Worksheets("Data").Range("B2").Value
email = Worksheets("Data").Range("C2").Value
contact = Worksheets("Data").Range("D2").Value
manager = Worksheets("Data").Range("E2").Value
numStores = Worksheets("Data").Range("F2").Value
SAPRef = Worksheets("Data").Range("G2").Value
cardID = Worksheets("Data").Range("H2").Value
CASID = Worksheets("Data").Range("I2").Value
TVOn = Worksheets("Data").Range("J2").Value
TVChannel = Worksheets("Data").Range("K2").Value
TVPackage = Worksheets("Data").Range("L2").Value
TVFullHD = Worksheets("Data").Range("M2").Value
appAgents = Worksheets("Data").Range("N2").Value
appInUse = Worksheets("Data").Range("O2").Value
cardholders = Worksheets("Data").Range("P2").Value
webAgents = Worksheets("Data").Range("Q2").Value
webInUse = Worksheets("Data").Range("R2").Value
signature = Worksheets("Data").Range

' Fill out the template with the data entered by the user
Worksheets("Sheet1").Range("A8").Value = company
Worksheets("Sheet1").Range("A9").Value = address
Worksheets("Sheet1").Range("A10").Value = email
Worksheets("Sheet1").Range("A11").Value = contact
Worksheets("Sheet1").Range("A12").Value = manager
Worksheets("Sheet1").Range("A13").Value = numStores
Worksheets("Sheet1").Range("C13").Value = SAPRef
Worksheets("Sheet1").Range("A15").Value = cardID
Worksheets("Sheet1").Range("A16").Value = CASID
Worksheets("Sheet1").Range("A18").Value = TVOn
Worksheets("Sheet1").Range("B18").Value = TVChannel
Worksheets("Sheet1").Range("C18").Value = TVPackage
Worksheets("Sheet1").Range("A19").Value = TVFullHD
Worksheets("Sheet1").Range("A21").Value = appAgents
Worksheets("Sheet1").Range("B21").Value = appInUse
Worksheets("Sheet1").Range("A22").Value = cardholders
Worksheets("Sheet1").Range("A24").Value = webAgents
Worksheets("Sheet1").Range("B24").Value = webInUse
Worksheets("Sheet1").Range("A25").Value = signature

End Sub

</code>```

How ever i dont want to fill in each pop out windows. I want to be able to feel the form and execute. The form will copy all the information to a list and erase the previous information in the form.

Body:
I want to create a VBA based on the template below, but i got an error and not what i expected.

MOD 001/DCO CHECKLIST PARTNERS

Version 5.22

PARTNER DATA

Company:____________________________________________________
Household:  __________________________________________________
Email:  ______________________________________@_______________________________
Contact: _______________________________
Manager: _______________________________
Number of Stores: _______________________________                                                                                Ref. SAP: _______________________________

KIT
SERVICE - DEMO BOX / COMMUNICATION APP
YES NO
CARD ID: _______________________________ POINT
FLY BANNERYES NO
CAS ID: POSTERS/LEAFLETS YES NO
STICKERSYES NO
HOLDER HOLDER YES NO
TV ON: YES/NO BANK
CHANNEL:____________ PACKAGE:____________ GAZEBO
 PAINTING
                                                                                OTHERS _____________

FULL HD TV: YES               APP AGENTS YES NO
NOT IN USE:  YES NO

ACTIVATION STATISTICAL DATA

NR. OF ACTIVATIONS IN THE MONTH OF: : DATE OF LAST PURCHASE:

 PRODUCTS
REFILL BOXES AND ACCESSORIES
                                ARP
HD+                 QTY____ NO____      QTY____ NO____
INSTALLATION KITS       QTY____ NO____      150 'S QTY____ NO____
COMMANDS            QTY____ NO____      300 'S QTY____ NO____
TRANSFORMERS                QTY____ NO____          600 'S QTY____ NO____
 CARDS              QTY____ NO____

COMPETITION

NOTE:_____________________________________

DSTV        QTY____ NO
GOTV        QTY____ NO
STARTIMES   QTY____ NO
TMT         QTY____ NO
OTHER       QTY____ NO
MERCHANDISING   NO
PAINTING        NO

BY : _______________________________ BY PARTNER: _______________________________

DATE: ________/_________/______________ DATE: ________/_________/______________

```

I tried the VBA below

Sub Button1_Click()
'Call the FillTemplate function

' Declare variables to store the data from the template
Dim company As String
Dim address As String
Dim email As String
Dim contact As String
Dim manager As String
Dim numStores As Long
Dim SAPRef As String
Dim cardID As String
Dim CASID As String
Dim TVOn As String
Dim TVChannel As String
Dim TVPackage As String
Dim TVFullHD As String
Dim appAgents As String
Dim appInUse As String
Dim cardholders As Long
Dim webAgents As String
Dim webInUse As String
Dim signature As String

' Prompt the user to enter the data for each field
company = InputBox("Enter the company name:")
address = InputBox("Enter the address:")
email = InputBox("Enter the email address:")
contact = InputBox("Enter the contact:")
manager = InputBox("Enter the manager:")
numStores = Val(InputBox("Enter the number of stores:"))
SAPRef = InputBox("Enter the SAP reference:")
cardID = InputBox("Enter the CARD ID:")
CASID = InputBox("Enter the CAS ID:")
TVOn = InputBox("Is the TV on? (Yes/No)")
TVChannel = InputBox("Enter the TV channel:")
TVPackage = InputBox("Enter the TV package:")
TVFullHD = InputBox("Is the TV Full HD? (Yes/No)")
appAgents = InputBox("Is the APP AGENTS service in use? (Yes/No)")
appInUse = InputBox("Enter the APP in use:")
cardholders = Val(InputBox("Enter the number of CARDHOLDERS:"))
webAgents = InputBox("Is the WEB AGENTS service in use? (Yes/No)")
webInUse = InputBox("Enter the WEB in use:")
signature = InputBox("Enter the signage:")

' Read the data from the table
company = Worksheets("Data").Range("A2").Value
address = Worksheets("Data").Range("B2").Value
email = Worksheets("Data").Range("C2").Value
contact = Worksheets("Data").Range("D2").Value
manager = Worksheets("Data").Range("E2").Value
numStores = Worksheets("Data").Range("F2").Value
SAPRef = Worksheets("Data").Range("G2").Value
cardID = Worksheets("Data").Range("H2").Value
CASID = Worksheets("Data").Range("I2").Value
TVOn = Worksheets("Data").Range("J2").Value
TVChannel = Worksheets("Data").Range("K2").Value
TVPackage = Worksheets("Data").Range("L2").Value
TVFullHD = Worksheets("Data").Range("M2").Value
appAgents = Worksheets("Data").Range("N2").Value
appInUse = Worksheets("Data").Range("O2").Value
cardholders = Worksheets("Data").Range("P2").Value
webAgents = Worksheets("Data").Range("Q2").Value
webInUse = Worksheets("Data").Range("R2").Value
signature = Worksheets("Data").Range

' Fill out the template with the data entered by the user
Worksheets("Sheet1").Range("A8").Value = company
Worksheets("Sheet1").Range("A9").Value = address
Worksheets("Sheet1").Range("A10").Value = email
Worksheets("Sheet1").Range("A11").Value = contact
Worksheets("Sheet1").Range("A12").Value = manager
Worksheets("Sheet1").Range("A13").Value = numStores
Worksheets("Sheet1").Range("C13").Value = SAPRef
Worksheets("Sheet1").Range("A15").Value = cardID
Worksheets("Sheet1").Range("A16").Value = CASID
Worksheets("Sheet1").Range("A18").Value = TVOn
Worksheets("Sheet1").Range("B18").Value = TVChannel
Worksheets("Sheet1").Range("C18").Value = TVPackage
Worksheets("Sheet1").Range("A19").Value = TVFullHD
Worksheets("Sheet1").Range("A21").Value = appAgents
Worksheets("Sheet1").Range("B21").Value = appInUse
Worksheets("Sheet1").Range("A22").Value = cardholders
Worksheets("Sheet1").Range("A24").Value = webAgents
Worksheets("Sheet1").Range("B24").Value = webInUse
Worksheets("Sheet1").Range("A25").Value = signature

End Sub

How ever i dont want to fill in each pop out windows. I want to be able to feel the form and execute. The form will copy all the information to a list and erase the previous information in the form.


问:
Is there a way to open metamask without calling the "window.ethereum.request( method 'eth _request accounts' )" method in javascript?
Is there a way to open metamask without calling the "window.ethereum.request( method 'eth _request accounts' )" method in javascript?

I have tried using the web3.js API and I am able to get the count but I would like metamask to be displayed, is there a way to do this?


问:
useContext(context) value in Navbar component stays the same, after object in the provider changed
I have a UserProvider component. it return an <UserContext.Provider value={{ user, signOut, updateUser }}> {children} </UserContext.provider>

(user is an object witch has type of UserInterface:

```<code>    _id?: string;
    fullname?: string;
    following?: string[];
    username?: string;
    password?: string
    media?: string;
    email?: string;
    tokenCreatedAt?: any;
    created?: Date;
    __v?: any;`
</code>```

OR undefined. )

signOut and updateUser are functions witch using the setUser function hook and removing and setting 'user' in localStorage.

the scenario that leads to the problem:

after the user signout(), and login(data) again from the Login component I navigate the user to Feed component, the logic in UserProvider  succesfully updating the user with setUser(using useState), which I guess need to deliver a new user inside Provider --> <Provider value={{ user: NewUser, signOut, updateUser }}>
I export the component of UserProvider and import it in Navbar, in the latter I use "useContext" hook like that :
const {user} = useContext(UserContext), wrote a useEffect which has its dependancy list contains user and in the arrow function I console log the new user, but it doesnt.
Navbar Component being rendered all the time, before the user clicks on login():

```<code>    <UserProvider>
      <Header /> ******** Navbar sits under Header ********
      <Suspense>
      <Outlet></Outlet> ***** Feed sits here under Outlet *****
      </Suspense>
    </UserProvider>`
</code>```

I think the reason for this to happen, is that the object that being changed from undefined to the UserInterface type with values, is a nested object inside the contextProvider:
<Provider value={{ user<undefined|UserInterface>, signOut, updateUser }}>

I tried to use memoization for that but failed. I wrote window.location.reload everytime it git new user and I ended up in infinteLoop.
and also thought about using usereducer but didnt understood yet how to use it in this case.

in UserProvider component I tried pass user as an parameter to the arrow function, inside useMemo hook like that:

const memoizedUser = useMemo((user)=>{
return user }, [user])

passing memoizedUser to the provider:

```<code>   return (
    <UserContext.Provider value={{ user, signOut, updateUser }}>
      {children}
    </UserContext.Provider>
  )
</code>```

then, on Navbar component:

useEffect(()=>{window.location.reload},[memoizedUser])
to refresh the page when the values of the object (of type UserInterface) being changed,
but it ended up in infinite loop of refreshing the page.

I also tried to pass in the provider the regular user as written in the beginning of this question and import the context from navbar, using the useContext hool like that:
const {user} = useContext(userContext)

then from the navbar components I write:
const memoizedUser = const memoizedUser = useMemo((user)=>{
return user }, [user])

and did basicly the same thing, except memoizing user in the navbar and not in contextProvider.

Body:
I have a UserProvider component. it return an <UserContext.Provider value={{ user, signOut, updateUser }}> {children} </UserContext.provider>

(user is an object witch has type of UserInterface:

    _id?: string;
    fullname?: string;
    following?: string[];
    username?: string;
    password?: string
    media?: string;
    email?: string;
    tokenCreatedAt?: any;
    created?: Date;
    __v?: any;`

OR undefined. )

signOut and updateUser are functions witch using the setUser function hook and removing and setting 'user' in localStorage.

the scenario that leads to the problem:

after the user signout(), and login(data) again from the Login component I navigate the user to Feed component, the logic in UserProvider  succesfully updating the user with setUser(using useState), which I guess need to deliver a new user inside Provider --> <Provider value={{ user: NewUser, signOut, updateUser }}>
I export the component of UserProvider and import it in Navbar, in the latter I use "useContext" hook like that :
const {user} = useContext(UserContext), wrote a useEffect which has its dependancy list contains user and in the arrow function I console log the new user, but it doesnt.
Navbar Component being rendered all the time, before the user clicks on login():

    <UserProvider>
       ******** Navbar sits under Header ********
      <Suspense>
      <Outlet></Outlet> ***** Feed sits here under Outlet *****
      </Suspense>
    </UserProvider>`

I think the reason for this to happen, is that the object that being changed from undefined to the UserInterface type with values, is a nested object inside the contextProvider:
<Provider value={{ user<undefined|UserInterface>, signOut, updateUser }}>

I tried to use memoization for that but failed. I wrote window.location.reload everytime it git new user and I ended up in infinteLoop.
and also thought about using usereducer but didnt understood yet how to use it in this case.

in UserProvider component I tried pass user as an parameter to the arrow function, inside useMemo hook like that:

const memoizedUser = useMemo((user)=>{
return user }, [user])

passing memoizedUser to the provider:

   return (
    <UserContext.Provider value={{ user, signOut, updateUser }}>
      {children}
    </UserContext.Provider>
  )

then, on Navbar component:

useEffect(()=>{window.location.reload},[memoizedUser])
to refresh the page when the values of the object (of type UserInterface) being changed,
but it ended up in infinite loop of refreshing the page.

I also tried to pass in the provider the regular user as written in the beginning of this question and import the context from navbar, using the useContext hool like that:
const {user} = useContext(userContext)

then from the navbar components I write:
const memoizedUser = const memoizedUser = useMemo((user)=>{
return user }, [user])

and did basicly the same thing, except memoizing user in the navbar and not in contextProvider.


问:
Why is click requesting both __unix and __win?
I'm trying to conda build a Python project that uses the click package.
I'm getting a conflicts report from conda ending with:

```<code>The following specifications were found to be incompatible with your system:

  - feature:/osx-arm64::__unix==0=0
  - feature:|@/osx-arm64::__unix==0=0
  - click -> __unix
  - click -> __win
</code>```

Why is click requesting both __unix and __win?!

Body:
I'm trying to conda build a Python project that uses the click package.
I'm getting a conflicts report from conda ending with:

The following specifications were found to be incompatible with your system:

  - feature:/osx-arm64::__unix==0=0
  - feature:|@/osx-arm64::__unix==0=0
  - click -> __unix
  - click -> __win

Why is click requesting both __unix and __win?!


问:
React Native ReactNative:Unexpected empty result of running error
info JS server already running.
info Installing the app...
:ReactNative:Unexpected empty result of running '[node, C:\Users\kemal\OneDrive\Masaüstü\Native\AwesomeProject\node_modules@react-native-community\cli\build\bin.js, config]' command.
:ReactNative:Running '[node, C:\Users\kemal\OneDrive\Masaüstü\Native\AwesomeProject\node_modules@react-native-community\cli\build\bin.js, config]' command failed.

FAILURE: Build failed with an exception.

Where:
Script 'C:\Users\kemal\OneDrive\Masa�st�\Native\AwesomeProject\node_modules@react-native-community\cli-platform-android\native_modules.gradle' line: 413

What went wrong:
A problem occurred evaluating script.

node:internal/modules/cjs/loader:998  throw err;  ^Error: Cannot find module 'C:\Users\kemal\OneDrive\MasaÃ¼stÃ¼\Native\AwesomeProject\node_modules@react-native-community\cli\build\bin.js'    at Module._resolveFilename (node:internal/modules/cjs/loader:995:15)    at Module._load (node:internal/modules/cjs/loader:841:27)    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12)    at node:internal/main/run_main_module:23:47 {  code: 'MODULE_NOT_FOUND',  requireStack: []}Node.js v19.0.0

Try:

Run with --stacktrace option to get the stack trace.
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.

Get more help at https://help.gradle.org

B

when ı write run npm android


问:
Python Pip Install Pandas Stuck at Version 1.1.5 on CentOS7
For practical reason, I am forced to use CentOS 7 in my case. I have Python3.10 installed and as I tried pip3 install --upgrade pandas it just won't upgrade and it will get stuck at Version 1.1.5.

As I pip3 show pandas it however shows that the location is /usr/local/lib/python3.6/site-packages. Somehow even when I thought I am using python3.10, the pandas thing is actually in a python3.6 folder. I supposed this is because some time ago python was installed through dnf, and it seems for some reasons dnf can only install python3.6, and then the pip3 I used just identify itself with python3.6 rather than the python3.10 I have.

May I know what I can do in this case?


问:
Depiction and thumbnail relationships in DBpedia
I have an earlier 2022 extraction of DBPedia and I am having a hard time finding even a fraction of the images/depictions/thumbnails present on the dbpedia.org resource pages. For example: https://dbpedia.org/page/John_F._Kennedy# has a thumbnail relationship as well as many depiction relationships, but in the data when I grep for thumbnail/depicts/depiction I get maybe 50 items for the whole extraction, and none for JFK. I can (and plan to) download the absolute latest dump and compare, but am I just doing something wrong here? Thanks for your help.</p>


问:
Why blank space is not selectable using inspector from browser's devtools?
The HTML element is increasing based on the height of the messages, but somehow I can't figure out why is that happening.

I tried to select the DOM element on different browsers too, but I'm getting the same result.