问:
ValueError: Cannot set tensor: Dimension mismatch. Got 198 but expected 300 for dimension 1 of input 175
I am using tensorflow lite for object detection specifically the SSDLite-MobileNet-v2 object detection model from google. Along with object detection I am also performing color detection of that particular object using opencv.For that I am referring to this tutorial on youtube.

Simple color detection

Here first the frame read is converted into HSV format and the the HSV value of a pixel at the center of the object bounding box is found out and the color is estimated

For object detection I'm referring to the following GitHub code--
https://github.com/EdjeElectronics/TensorFlow-Lite-Object-Detection-on-Android-and-Raspberry-Pi

The code for object and color detection:-

```<code>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(0)
        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 labelmap.txt',
                    default='labelmap.txt')
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)
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[0]['index'])[0] ## Bounding box coordinates of detected objects
    classes = interpreter.get_tensor(output_details[1]['index'])[0] ## Class index of detected objects
    scores = interpreter.get_tensor(output_details[2]['index'])[0] ## Confidence of detected objects
    ##num = interpreter.get_tensor(output_details[3]['index'])[0]  # Total number of detected
    ## 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)))
            ## print(ymin,xmin,ymax,xmax)

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

            ## Draw label
            object_name = labels[int(classes[i])]
            print(object_name)

            ##colour detection
            hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
            height, width=(ymax-ymin),(xmax-xmin)

            cx = int(width / 2)
            cy = int(height / 2)

            ## Pick pixel value
            pixel_center = hsv_frame[cy+ymin, cx+xmin]
            hue_value = pixel_center[0]
            sat_value = pixel_center[1]
            val_value = pixel_center[2]
            print(hue_value,sat_value,val_value)
            color = "Undefined"
            if hue_value>166 and val_value<95:
                color="black"
            elif hue_value < 5:
                color = "RED"
            elif hue_value < 22:
                color = "ORANGE"
            elif hue_value < 33:
                color = "YELLOW"
            elif hue_value < 67:
                color = "GREEN"
            elif hue_value < 117:
                color = "BLUE"
            elif hue_value < 144:
                color = "VIOLET"
            elif hue_value < 160:
                color = "PINK"
            else:
                color = "RED"
            print(color)

            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)

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

## Clean up
cv2.destroyAllWindows()
videostream.stop()
</code>```

I am new to tensorflow lite. When I run this code it runs perfectly for the first iteration of the while loop and outputs-- (cup and the color orange) but then i get this error.

```<code>cup
20 215 197
ORANGE
Traceback (most recent call last):
  File "D:\download\TensorFlow-Lite-Object-Detection-on-Android-and-Raspberry-Pi-master\TFLite_detection_webcam.py", line 188,
in <module>
    interpreter.set_tensor(input_details[0]['index'],input_data)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\lite\python\interpreter.py", line 705, in set_tensor
    self._interpreter.SetTensor(tensor_index, value)
ValueError: Cannot set tensor: Dimension mismatch. Got 198 but expected 300 for dimension 1 of input 175.
</code>```

But if I remove the color detection code completely from the while loop (Colour detection code is mentioned below). It runs without any error and returns the object name

Color detection code in while loop:-

```<code>  ##colour detection
            hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
            height, width=(ymax-ymin),(xmax-xmin)

            cx = int(width / 2)
            cy = int(height / 2)

            ## Pick pixel value
            pixel_center = hsv_frame[cy+ymin, cx+xmin]
            hue_value = pixel_center[0]
            sat_value = pixel_center[1]
            val_value = pixel_center[2]
            print(hue_value,sat_value,val_value)
            color = "Undefined"
            if hue_value>166 and val_value<95:
                color="black"
            elif hue_value < 5:
                color = "RED"
            elif hue_value < 22:
                color = "ORANGE"
            elif hue_value < 33:
                color = "YELLOW"
            elif hue_value < 67:
                color = "GREEN"
            elif hue_value < 117:
                color = "BLUE"
            elif hue_value < 144:
                color = "VIOLET"
            elif hue_value < 160:
                color = "PINK"
            else:
                color = "RED"
        print(color)
</code>```

how do I solve this problem?

答:
The error is suggesting that the dimensions are wrong.

The cause is that you overwrite the variables width, height with the output dimensions of the network which is not same as input_dimensions of the network hence it breaks.

Solution Change the name of variable width, height in your color detection code.

Body:
I am using tensorflow lite for object detection specifically the SSDLite-MobileNet-v2 object detection model from google. Along with object detection I am also performing color detection of that particular object using opencv.For that I am referring to this tutorial on youtube.

Simple color detection

Here first the frame read is converted into HSV format and the the HSV value of a pixel at the center of the object bounding box is found out and the color is estimated

For object detection I'm referring to the following GitHub code--
https://github.com/EdjeElectronics/TensorFlow-Lite-Object-Detection-on-Android-and-Raspberry-Pi

The code for object and color detection:-

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(0)
        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 labelmap.txt',
                    default='labelmap.txt')
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)
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[0]['index'])[0] ## Bounding box coordinates of detected objects
    classes = interpreter.get_tensor(output_details[1]['index'])[0] ## Class index of detected objects
    scores = interpreter.get_tensor(output_details[2]['index'])[0] ## Confidence of detected objects
    ##num = interpreter.get_tensor(output_details[3]['index'])[0]  # Total number of detected
    ## 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)))
            ## print(ymin,xmin,ymax,xmax)

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

            ## Draw label
            object_name = labels[int(classes[i])]
            print(object_name)

            ##colour detection
            hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
            height, width=(ymax-ymin),(xmax-xmin)

            cx = int(width / 2)
            cy = int(height / 2)

            ## Pick pixel value
            pixel_center = hsv_frame[cy+ymin, cx+xmin]
            hue_value = pixel_center[0]
            sat_value = pixel_center[1]
            val_value = pixel_center[2]
            print(hue_value,sat_value,val_value)
            color = "Undefined"
            if hue_value>166 and val_value<95:
                color="black"
            elif hue_value < 5:
                color = "RED"
            elif hue_value < 22:
                color = "ORANGE"
            elif hue_value < 33:
                color = "YELLOW"
            elif hue_value < 67:
                color = "GREEN"
            elif hue_value < 117:
                color = "BLUE"
            elif hue_value < 144:
                color = "VIOLET"
            elif hue_value < 160:
                color = "PINK"
            else:
                color = "RED"
            print(color)

            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)

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

## Clean up
cv2.destroyAllWindows()
videostream.stop()

I am new to tensorflow lite. When I run this code it runs perfectly for the first iteration of the while loop and outputs-- (cup and the color orange) but then i get this error.

cup
20 215 197
ORANGE
Traceback (most recent call last):
  File "D:\download\TensorFlow-Lite-Object-Detection-on-Android-and-Raspberry-Pi-master\TFLite_detection_webcam.py", line 188,
in <module>
    interpreter.set_tensor(input_details[0]['index'],input_data)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\lite\python\interpreter.py", line 705, in set_tensor
    self._interpreter.SetTensor(tensor_index, value)
ValueError: Cannot set tensor: Dimension mismatch. Got 198 but expected 300 for dimension 1 of input 175.

But if I remove the color detection code completely from the while loop (Colour detection code is mentioned below). It runs without any error and returns the object name

Color detection code in while loop:-

  ##colour detection
            hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
            height, width=(ymax-ymin),(xmax-xmin)

            cx = int(width / 2)
            cy = int(height / 2)

            ## Pick pixel value
            pixel_center = hsv_frame[cy+ymin, cx+xmin]
            hue_value = pixel_center[0]
            sat_value = pixel_center[1]
            val_value = pixel_center[2]
            print(hue_value,sat_value,val_value)
            color = "Undefined"
            if hue_value>166 and val_value<95:
                color="black"
            elif hue_value < 5:
                color = "RED"
            elif hue_value < 22:
                color = "ORANGE"
            elif hue_value < 33:
                color = "YELLOW"
            elif hue_value < 67:
                color = "GREEN"
            elif hue_value < 117:
                color = "BLUE"
            elif hue_value < 144:
                color = "VIOLET"
            elif hue_value < 160:
                color = "PINK"
            else:
                color = "RED"
        print(color)

how do I solve this problem?


来源: stackexchange

问:
Java streaming options to merge the list of string on the same map object
I have use case to get the distinct value from the map. Is there any way using streams</p>
```<code>Sample Model data set = {"Ford":{"hatchback", "sedan", "TEST"}, "Honda":{"hatchback", "sedan"}, "Toyota":{"hatchback", "sedan", "TeST2"}}

for (Entry<String, Set<String>> model: models.entrySet()) {
modelList.addAll(model.getValue());
}

Final List: {"hatchback", "sedan", "TEST", "TeST2"}
</code>```

答:
```<code>        List<String> unique=set.stream().flatMap(map->map.values().stream()).flatMap(list->list.stream()).distinct().collect(Collectors.toList());
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have use case to get the distinct value from the map. Is there any way using streams

Sample Model data set = {"Ford":{"hatchback", "sedan", "TEST"}, "Honda":{"hatchback", "sedan"}, "Toyota":{"hatchback", "sedan", "TeST2"}}

for (Entry<String, Set<String>> model: models.entrySet()) {
modelList.addAll(model.getValue());
}

Final List: {"hatchback", "sedan", "TEST", "TeST2"}


问:
Firefox 3 adds spacing to spans with display:inline-block
In my test, I have 2 spans both set to display:inline-block with a border for visibility. Firefox renders space between each span. Even setting margin:0;padding:0; doesn't do anything to fix this. My expectation when setting the inline span element to display:inline-block is that the 2 spans render flush against each other, as if you floated 2 divs left or right. The only "fix" I have found is to add float:left or right to the spans, but that defeats my original purpose of trying not to use floats at all. Any ideas?

Test
Test2
```

答:
If you're rendering pure XHTML (and its highly likely you're not, even setting the doctype won't unless you serve the page to the user as XML, not HTML) then it would display as you are expecting.

However because of the above mentioned HTML / XHTML variances, it will be rendered as a single space.

OwnerDisplayName: Geuis

OwnerDisplayName: ck

ContentLicense: CC BY-SA 2.5


问:
React Navigation Authentication Flow: The action 'NAVIGATE' with payload {"name":"HomeScreen"} was not handled by any navigator
A beginner at React Native here, trying to combine this doc with AWS Amplify Authentication to implement React Navigation Authentication Flow but I can't seem to figure out what's wrong. Whenever I click on the login button,  this error  appears.

Navigation Code (excluding imports):

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

    const [user, setUser] = useState(undefined);

    const checkUser = async () => {
        try {
            const authUser = await Auth.currentAuthenticatedUser({bypassCache: true});
            setUser(authUser);
        } catch (e) {
            setUser(null);
        }
    }

    useEffect(() => {
        checkUser();
    }, []);

    if (user === undefined) {
        return (
            <View style = {{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                <ActivityIndicator />
            </View>
        )
    }

    return (
        <Stack.Navigator screenOptions={{headerShown: false}}>
            {user ? (
                <>
                    <Stack.Screen name = "Login" component = {LoginScreen} />
                    <Stack.Screen name = "SignUp" component = {SignUpScreen} />
                    <Stack.Screen name = "ConfirmEmail" component = {ConfirmEmailScreen} />
                    <Stack.Screen name = "ForgotPassword" component = {ForgotPasswordScreen} />
                    <Stack.Screen name = "NewPassword" component = {NewPasswordScreen} />
                </>
            ): (
                <Stack.Screen name = "HomeScreen" component = {HomeTabNavigator} />
            )}
        </Stack.Navigator>
    );
};

//* TAB NAVIGATOR FOR APP SCREENS
const HomeTabNavigator = () => {
    return (
        <Tab.Navigator
            initialRouteName="Home"
            screenOptions={{
                headerShown: false,
                tabBarStyle: {backgroundColor: '#0052cc'},
                tabBarInactiveTintColor: '#fff',
                tabBarActiveTintColor: '#fff',
                tabBarActiveBackgroundColor: '#006600'
            }}>
            <Tab.Screen
                name="Home"
                component={HomeScreen}
                options={{
                tabBarLabel: 'Home',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="home-outline" color={'#fff'} size={25} />
                ),
                }}
            />

            <Tab.Screen
                name="Courses"
                component={CourseScreen}
                options={{
                tabBarLabel: 'Courses',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="library-outline" color={'#fff'} size={25} />
                ),
                }}
            />

            <Tab.Screen
                name="Profile"
                component={ProfileScreen}
                options={{
                tabBarLabel: 'My Profile',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="person-outline" color={'#fff'} size={25} />
                ),
                }}
            />

            <Tab.Screen
                name="Forensic Tools"
                component={ForensicToolsScreen}
                options={{
                tabBarLabel: 'Tools List',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="list-outline" color={'#fff'} size={25} />
                ),
                }}
            />

            <Tab.Screen
                name="Leaderboard"
                component={LeaderboardScreen}
                options={{
                tabBarLabel: 'Leaderboard',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="podium-outline" color={'#fff'} size={25} />
                ),
                }}
            />

            <Tab.Screen
                name="Settings"
                component={SettingsScreen}
                options={{
                tabBarLabel: 'Settings',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="settings-outline" color={'#fff'} size={25} />
                ),
                }}
            />
        </Tab.Navigator>
    );
};

export default NavigationGeneral;
</code>```

LoginScreen.js code snippet:

```<code>const onLoginPressed = async data => {
        if (loading) {
            return;
        }

        setLoading(true);
        try {
            await Auth.signIn(data.username, data.password);
            navigation.navigate("HomeScreen");
            console.log("Login");
        } catch (e) {
            Alert.alert('Oops', e.message);
        }
        setLoading(false);
    };
</code>```

I understand that I'm not supposed to manually navigate using navigation.navigate() but rather to conditionally define the screens. But whenever I remove navigation.navigate("HomeScreen"); from the code, nothing happens when I press the login button. So I assume something is wrong with my conditioning in my NavigationGeneral code, I just can't seem to figure out the problem.

Some help or additional tips would be greatly appreciated, thanks in advance. Please let me know if more info is required.

答:
When you try to navigate to the HomeScreen I assume the user is not yet set in the state and therefore the screen with the name HomeScreen does not exist yet, so the navigator has nowhere to go.
Try setting the user in the NavigationGeneral upon login, it should event redirect automatically without using navigation.navigate.</p>

Body:
A beginner at React Native here, trying to combine this doc with AWS Amplify Authentication to implement React Navigation Authentication Flow but I can't seem to figure out what's wrong. Whenever I click on the login button,  this error  appears.

Navigation Code (excluding imports):

const NavigationGeneral = () => {

    const [user, setUser] = useState(undefined);

    const checkUser = async () => {
        try {
            const authUser = await Auth.currentAuthenticatedUser({bypassCache: true});
            setUser(authUser);
        } catch (e) {
            setUser(null);
        }
    }

    useEffect(() => {
        checkUser();
    }, []);

    if (user === undefined) {
        return (
            <View style = {{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                <ActivityIndicator />
            </View>
        )
    }

    return (
        <Stack.Navigator screenOptions={{headerShown: false}}>
            {user ? (
                <>
                    <Stack.Screen name = "Login" component = {LoginScreen} />
                    <Stack.Screen name = "SignUp" component = {SignUpScreen} />
                    <Stack.Screen name = "ConfirmEmail" component = {ConfirmEmailScreen} />
                    <Stack.Screen name = "ForgotPassword" component = {ForgotPasswordScreen} />
                    <Stack.Screen name = "NewPassword" component = {NewPasswordScreen} />
                </>
            ): (
                <Stack.Screen name = "HomeScreen" component = {HomeTabNavigator} />
            )}
        </Stack.Navigator>
    );
};

//* TAB NAVIGATOR FOR APP SCREENS
const HomeTabNavigator = () => {
    return (
        <Tab.Navigator
            initialRouteName="Home"
            screenOptions={{
                headerShown: false,
                tabBarStyle: {backgroundColor: '#0052cc'},
                tabBarInactiveTintColor: '#fff',
                tabBarActiveTintColor: '#fff',
                tabBarActiveBackgroundColor: '#006600'
            }}>
            <Tab.Screen
                name="Home"
                component={HomeScreen}
                options={{
                tabBarLabel: 'Home',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="home-outline" color={'#fff'} size={25} />
                ),
                }}
            />

            <Tab.Screen
                name="Courses"
                component={CourseScreen}
                options={{
                tabBarLabel: 'Courses',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="library-outline" color={'#fff'} size={25} />
                ),
                }}
            />

            <Tab.Screen
                name="Profile"
                component={ProfileScreen}
                options={{
                tabBarLabel: 'My Profile',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="person-outline" color={'#fff'} size={25} />
                ),
                }}
            />

            <Tab.Screen
                name="Forensic Tools"
                component={ForensicToolsScreen}
                options={{
                tabBarLabel: 'Tools List',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="list-outline" color={'#fff'} size={25} />
                ),
                }}
            />

            <Tab.Screen
                name="Leaderboard"
                component={LeaderboardScreen}
                options={{
                tabBarLabel: 'Leaderboard',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="podium-outline" color={'#fff'} size={25} />
                ),
                }}
            />

            <Tab.Screen
                name="Settings"
                component={SettingsScreen}
                options={{
                tabBarLabel: 'Settings',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="settings-outline" color={'#fff'} size={25} />
                ),
                }}
            />
        </Tab.Navigator>
    );
};

export default NavigationGeneral;

LoginScreen.js code snippet:

const onLoginPressed = async data => {
        if (loading) {
            return;
        }

        setLoading(true);
        try {
            await Auth.signIn(data.username, data.password);
            navigation.navigate("HomeScreen");
            console.log("Login");
        } catch (e) {
            Alert.alert('Oops', e.message);
        }
        setLoading(false);
    };

I understand that I'm not supposed to manually navigate using navigation.navigate() but rather to conditionally define the screens. But whenever I remove navigation.navigate("HomeScreen"); from the code, nothing happens when I press the login button. So I assume something is wrong with my conditioning in my NavigationGeneral code, I just can't seem to figure out the problem.

Some help or additional tips would be greatly appreciated, thanks in advance. Please let me know if more info is required.


问:
How we can bold some words in TextInput component React Native?
I want something feature in textInput like if we write hello then hello should be bold in the textinput and remaining words will be normal. Can someone help me out with it?

It's something different from Text Component, which mentioned in below link.

```<code>https://stackoverflow.com/questions/35718143/react-native-add-bold-or-italics-to-single-words-in-text-field
</code>```

答:
You will have to make custom textInput component, something like this:

```<code>const [txt,setTxt] = useState("");
        <Pressable>
            <TextInput placeholder="Type Something..." onChangeText={(value)=>setTxt(value)}/>
                <View style={{flexDirection: 'row'}}>
                    {txt.split(" ").map((text)=><Text style={{fontWeight:text == "bold"?'bold':null}}>{text+" "}</Text>)}
                </View>
        </Pressable>
</code>```

Replace text == "bold" with any value that you want to make bold.

Edit: if you want to make more than one word bold, group them in an array and update your condition like this:

```<code>const anArrayOfBoldStrings = ["bold","hello","stackoverflow"];

            <Pressable>
                <TextInput placeholder="Type Something..." onChangeText={(value)=>setTxt(value)}/>
                    <View style={{flexDirection: 'row'}}>
                        {txt.split(" ").map((text)=><Text style={{fontWeight:text == anArrayOfBoldStrings.includes(text?'bold':null}}>{text+" "}</Text>)}
                    </View>
            </Pressable>
</code>```

Body:
I want something feature in textInput like if we write hello then hello should be bold in the textinput and remaining words will be normal. Can someone help me out with it?

It's something different from Text Component, which mentioned in below link.

https://stackoverflow.com/questions/35718143/react-native-add-bold-or-italics-to-single-words-in-text-field

Body:
You will have to make custom textInput component, something like this:

const [txt,setTxt] = useState("");
        <Pressable>
            <TextInput placeholder="Type Something..." onChangeText={(value)=>setTxt(value)}/>
                <View style={{flexDirection: 'row'}}>
                    {txt.split(" ").map((text)=><Text style={{fontWeight:text == "bold"?'bold':null}}>{text+" "}</Text>)}
                </View>
        </Pressable>

Replace text == "bold" with any value that you want to make bold.

Edit: if you want to make more than one word bold, group them in an array and update your condition like this:

const anArrayOfBoldStrings = ["bold","hello","stackoverflow"];

            <Pressable>
                <TextInput placeholder="Type Something..." onChangeText={(value)=>setTxt(value)}/>
                    <View style={{flexDirection: 'row'}}>
                        {txt.split(" ").map((text)=><Text style={{fontWeight:text == anArrayOfBoldStrings.includes(text?'bold':null}}>{text+" "}</Text>)}
                    </View>
            </Pressable>


问:
Wordlist transfer for an anagram program
I'm almost finished with my program, but there's one last bug that I'm having problems ferreting out. The program is supposed to check about 10 scrambled words against a wordlist to see what the scrambled words are anagrams of. To do this, I alphabetized each word in the wordlist (apple would become aelpp), set that as the key of a map, and made the corresponding entry the original, unalphabetized word.

The program is messing up when it comes to the entries in the map. When the entry is six characters or less, the program tags a random character on the end of the string. I've narrowed down what can be causing the problem to a single loop:

```<code>while(myFile){
  myFile.getline(str, 30);
  int h=0;
  for (; str[h] != 0; h++)//setting the initial version of str
  {
      strInit[h]=str[h]; //strInit is what becomes the entry into the map.
  }
  strInit[h+1]='\0';    //I didn't know if the for loop would include the null char
  cout<<strInit; //Personal error-checking; not necessary for the program
 }
</code>```

And if it's necessary, here's the entire program:

Program

答:
Best not to use raw C arrays at all! Here's a version, using modern C++:</p>

```<code>#include <string>

std::string str;

while (std::getline(myFile, str))
{
  // do something useful with str
  // Example: mymap[str] = f(str);
  std::cout << str; //Personal error-checking; not necessary for the program
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm almost finished with my program, but there's one last bug that I'm having problems ferreting out. The program is supposed to check about 10 scrambled words against a wordlist to see what the scrambled words are anagrams of. To do this, I alphabetized each word in the wordlist (apple would become aelpp), set that as the key of a map, and made the corresponding entry the original, unalphabetized word.

The program is messing up when it comes to the entries in the map. When the entry is six characters or less, the program tags a random character on the end of the string. I've narrowed down what can be causing the problem to a single loop:

while(myFile){
  myFile.getline(str, 30);
  int h=0;
  for (; str[h] != 0; h++)//setting the initial version of str
  {
      strInit[h]=str[h]; //strInit is what becomes the entry into the map.
  }
  strInit[h+1]='\0';    //I didn't know if the for loop would include the null char
  cout<<strInit; //Personal error-checking; not necessary for the program
 }

And if it's necessary, here's the entire program:

Program

Body:
Best not to use raw C arrays at all! Here's a version, using modern C++:

#include <string>

std::string str;

while (std::getline(myFile, str))
{
  // do something useful with str
  // Example: mymap[str] = f(str);
  std::cout << str; //Personal error-checking; not necessary for the program
}


问:
Flutter: How do I disable scrolling for a GridView widget, but have scrolling enabled for the page as a whole?
I'm building an app where I have a page which gives information about a specific trading card. I want the page to be scrollable, but I also want to have a grid on the page, with each grid cell showing one data point. I made the grid using GridView.count().

My problem is that instead of have a page which I can scroll through, the top half of the page stays static, while the grid is scrollable. How do I make the grid static, while the rest of the page scrollable? I intend to have more data below this grid as well, and I want to user to be able to scroll to see all of it, with the grid being a static component of the page.

Here's my code:

```<code>import 'package:flutter/material.dart';
import 'package:pokehub/size_config.dart';
import 'package:pokemon_tcg/pokemon_tcg.dart';

class CardInfo extends StatefulWidget {
  PokemonCard card;

  CardInfo({required this.card});

  @override
  _CardInfoState createState() => _CardInfoState();
}

class _CardInfoState extends State<CardInfo> {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        backgroundColor: Colors.grey[900],
        appBar: AppBar(
          title: Text(
            "Card Profile",
            style: TextStyle(
                color: Colors.white,
                fontFamily: 'Blinker',
                fontSize: SizeConfig.blockSizeVertical * 3),
          ),
          backgroundColor: Colors.red,
          elevation: 0.0,
        ),
        body: Align(
          alignment: Alignment.center,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              SizedBox(
                height: SizeConfig.blockSizeVertical * 3,
              ),
              Text(
                "Set: " +
                    widget.card.set.name +
                    "  //  Number: " +
                    widget.card.number,
                style: TextStyle(
                    color: Colors.white,
                    fontFamily: 'Blinker',
                    fontSize: SizeConfig.blockSizeVertical * 2),
              ),
              SizedBox(
                height: SizeConfig.blockSizeVertical * 3,
              ),
              Hero(
                tag: 'card' + widget.card.id,
                child: Image.network(
                  widget.card.images.large,
                  height: SizeConfig.blockSizeVertical * 30,
                ),
              ),
              SizedBox(
                height: SizeConfig.blockSizeVertical * 2,
              ),
              Text(
                widget.card.name,
                style: TextStyle(
                  color: Colors.white,
                  fontFamily: 'Blinker',
                  fontSize: SizeConfig.blockSizeVertical * 5,
                ),
              ),
              SizedBox(
                height: SizeConfig.blockSizeVertical * 2,
              ),
              Expanded(
                child: GridView.count(
                  mainAxisSpacing: SizeConfig.blockSizeVertical * 4,
                  crossAxisSpacing: SizeConfig.blockSizeHorizontal * 4,
                  crossAxisCount: 3,
                  children: [
                    Container(
                      padding: EdgeInsets.symmetric(
                          vertical: SizeConfig.blockSizeVertical * 2,
                          horizontal: SizeConfig.blockSizeHorizontal * 2),
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Colors.white,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(20)),
                      ),
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              "Subtypes",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontFamily: 'Blinker',
                                  fontSize: SizeConfig.blockSizeVertical * 3,
                                  fontWeight: FontWeight.bold),
                            ),
                            Text(
                              widget.card.subtypes
                                  .map((e) => e.type)
                                  .join(", "),
                              style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'Blinker',
                                fontSize: SizeConfig.blockSizeVertical * 2,
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(
                          vertical: SizeConfig.blockSizeVertical * 2,
                          horizontal: SizeConfig.blockSizeHorizontal * 2),
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Colors.white,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(20)),
                      ),
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              "HP",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontFamily: 'Blinker',
                                  fontSize: SizeConfig.blockSizeVertical * 3,
                                  fontWeight: FontWeight.bold),
                            ),
                            Text(
                              widget.card.hp!,
                              style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'Blinker',
                                fontSize: SizeConfig.blockSizeVertical * 2,
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(
                          vertical: SizeConfig.blockSizeVertical * 2,
                          horizontal: SizeConfig.blockSizeHorizontal * 2),
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Colors.white,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(20)),
                      ),
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              "Type",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontFamily: 'Blinker',
                                  fontSize: SizeConfig.blockSizeVertical * 3,
                                  fontWeight: FontWeight.bold),
                            ),
                            Text(
                              widget.card.types.map((e) => e.type).join(", "),
                              style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'Blinker',
                                fontSize: SizeConfig.blockSizeVertical * 2,
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(
                          vertical: SizeConfig.blockSizeVertical * 2,
                          horizontal: SizeConfig.blockSizeHorizontal * 2),
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Colors.white,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(20)),
                      ),
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              "Weakness",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontFamily: 'Blinker',
                                  fontSize: SizeConfig.blockSizeVertical * 3,
                                  fontWeight: FontWeight.bold),
                            ),
                            Text(
                              widget.card.weaknesses
                                  .map((e) => e.type + e.value)
                                  .join(", "),
                              style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'Blinker',
                                fontSize: SizeConfig.blockSizeVertical * 2,
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(
                          vertical: SizeConfig.blockSizeVertical * 2,
                          horizontal: SizeConfig.blockSizeHorizontal * 2),
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Colors.white,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(20)),
                      ),
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              "Resistance",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontFamily: 'Blinker',
                                  fontSize: SizeConfig.blockSizeVertical * 3,
                                  fontWeight: FontWeight.bold),
                            ),
                            Text(
                              widget.card.resistances
                                  .map((e) =>
                                      e.type == "" ? "None" : e.type + e.value)
                                  .join(", "),
                              style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'Blinker',
                                fontSize: SizeConfig.blockSizeVertical * 2,
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(
                          vertical: SizeConfig.blockSizeVertical * 2,
                          horizontal: SizeConfig.blockSizeHorizontal * 2),
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Colors.white,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(20)),
                      ),
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              "Retreat Cost",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontFamily: 'Blinker',
                                  fontSize: SizeConfig.blockSizeVertical * 3,
                                  fontWeight: FontWeight.bold),
                            ),
                            Text(
                              widget.card.convertedRetreatCost.toString(),
                              style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'Blinker',
                                fontSize: SizeConfig.blockSizeVertical * 2,
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
[enter image description here][1]
</code>```

答:
You can provide  physics: NeverScrollableScrollPhysics() on GridView to disable scroll effect. If you want scrollable as secondary widget use primary: false,

To have Full Page scrollable, you can use body:SingleChildScrollView(..) or better using body:CustomScrollView(..)

Body:
I'm building an app where I have a page which gives information about a specific trading card. I want the page to be scrollable, but I also want to have a grid on the page, with each grid cell showing one data point. I made the grid using GridView.count().

My problem is that instead of have a page which I can scroll through, the top half of the page stays static, while the grid is scrollable. How do I make the grid static, while the rest of the page scrollable? I intend to have more data below this grid as well, and I want to user to be able to scroll to see all of it, with the grid being a static component of the page.

Here's my code:

import 'package:flutter/material.dart';
import 'package:pokehub/size_config.dart';
import 'package:pokemon_tcg/pokemon_tcg.dart';

class CardInfo extends StatefulWidget {
  PokemonCard card;

  CardInfo({required this.card});

  @override
  _CardInfoState createState() => _CardInfoState();
}

class _CardInfoState extends State<CardInfo> {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        backgroundColor: Colors.grey[900],
        appBar: AppBar(
          title: Text(
            "Card Profile",
            style: TextStyle(
                color: Colors.white,
                fontFamily: 'Blinker',
                fontSize: SizeConfig.blockSizeVertical * 3),
          ),
          backgroundColor: Colors.red,
          elevation: 0.0,
        ),
        body: Align(
          alignment: Alignment.center,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              SizedBox(
                height: SizeConfig.blockSizeVertical * 3,
              ),
              Text(
                "Set: " +
                    widget.card.set.name +
                    "  //  Number: " +
                    widget.card.number,
                style: TextStyle(
                    color: Colors.white,
                    fontFamily: 'Blinker',
                    fontSize: SizeConfig.blockSizeVertical * 2),
              ),
              SizedBox(
                height: SizeConfig.blockSizeVertical * 3,
              ),
              Hero(
                tag: 'card' + widget.card.id,
                child: Image.network(
                  widget.card.images.large,
                  height: SizeConfig.blockSizeVertical * 30,
                ),
              ),
              SizedBox(
                height: SizeConfig.blockSizeVertical * 2,
              ),
              Text(
                widget.card.name,
                style: TextStyle(
                  color: Colors.white,
                  fontFamily: 'Blinker',
                  fontSize: SizeConfig.blockSizeVertical * 5,
                ),
              ),
              SizedBox(
                height: SizeConfig.blockSizeVertical * 2,
              ),
              Expanded(
                child: GridView.count(
                  mainAxisSpacing: SizeConfig.blockSizeVertical * 4,
                  crossAxisSpacing: SizeConfig.blockSizeHorizontal * 4,
                  crossAxisCount: 3,
                  children: [
                    Container(
                      padding: EdgeInsets.symmetric(
                          vertical: SizeConfig.blockSizeVertical * 2,
                          horizontal: SizeConfig.blockSizeHorizontal * 2),
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Colors.white,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(20)),
                      ),
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              "Subtypes",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontFamily: 'Blinker',
                                  fontSize: SizeConfig.blockSizeVertical * 3,
                                  fontWeight: FontWeight.bold),
                            ),
                            Text(
                              widget.card.subtypes
                                  .map((e) => e.type)
                                  .join(", "),
                              style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'Blinker',
                                fontSize: SizeConfig.blockSizeVertical * 2,
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(
                          vertical: SizeConfig.blockSizeVertical * 2,
                          horizontal: SizeConfig.blockSizeHorizontal * 2),
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Colors.white,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(20)),
                      ),
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              "HP",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontFamily: 'Blinker',
                                  fontSize: SizeConfig.blockSizeVertical * 3,
                                  fontWeight: FontWeight.bold),
                            ),
                            Text(
                              widget.card.hp!,
                              style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'Blinker',
                                fontSize: SizeConfig.blockSizeVertical * 2,
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(
                          vertical: SizeConfig.blockSizeVertical * 2,
                          horizontal: SizeConfig.blockSizeHorizontal * 2),
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Colors.white,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(20)),
                      ),
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              "Type",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontFamily: 'Blinker',
                                  fontSize: SizeConfig.blockSizeVertical * 3,
                                  fontWeight: FontWeight.bold),
                            ),
                            Text(
                              widget.card.types.map((e) => e.type).join(", "),
                              style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'Blinker',
                                fontSize: SizeConfig.blockSizeVertical * 2,
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(
                          vertical: SizeConfig.blockSizeVertical * 2,
                          horizontal: SizeConfig.blockSizeHorizontal * 2),
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Colors.white,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(20)),
                      ),
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              "Weakness",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontFamily: 'Blinker',
                                  fontSize: SizeConfig.blockSizeVertical * 3,
                                  fontWeight: FontWeight.bold),
                            ),
                            Text(
                              widget.card.weaknesses
                                  .map((e) => e.type + e.value)
                                  .join(", "),
                              style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'Blinker',
                                fontSize: SizeConfig.blockSizeVertical * 2,
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(
                          vertical: SizeConfig.blockSizeVertical * 2,
                          horizontal: SizeConfig.blockSizeHorizontal * 2),
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Colors.white,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(20)),
                      ),
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              "Resistance",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontFamily: 'Blinker',
                                  fontSize: SizeConfig.blockSizeVertical * 3,
                                  fontWeight: FontWeight.bold),
                            ),
                            Text(
                              widget.card.resistances
                                  .map((e) =>
                                      e.type == "" ? "None" : e.type + e.value)
                                  .join(", "),
                              style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'Blinker',
                                fontSize: SizeConfig.blockSizeVertical * 2,
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(
                          vertical: SizeConfig.blockSizeVertical * 2,
                          horizontal: SizeConfig.blockSizeHorizontal * 2),
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Colors.white,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(20)),
                      ),
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              "Retreat Cost",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontFamily: 'Blinker',
                                  fontSize: SizeConfig.blockSizeVertical * 3,
                                  fontWeight: FontWeight.bold),
                            ),
                            Text(
                              widget.card.convertedRetreatCost.toString(),
                              style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'Blinker',
                                fontSize: SizeConfig.blockSizeVertical * 2,
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
[enter image description here][1]


问:
React State update a nested array with objects based on the id when iterated
I have an react state with objects/array that is filled, but also then later I want to edit text inputs and edit the related fields on object also, i found no solutions until now.

So this is my state for example:

```<code>const [data, setData] = useState({
    working_hours: [
      {
        id: 1,
        description: 'Random Text',
        price: 100,

      },
      {
        id: 2,
        description: 'Text Random',
        price: 100,
      },
    ]
  });
</code>```

Here is my Jsx:

```<code>{data.working_hours.map(item =>
<>
  <input type={text} value={item.description}
   onChange={(e) => handleChange(e)} />

  <input type={text} value={item.price}
   onChange={(e) => handleChange(e)} />
</>
)}
</code>```

Here is what I tried:

```<code>function handleChange(e){
 const value = e.target.value;
 setData({...data, [...data.working_hours, e.target.value]})
}
</code>```

答:
change elements

```<code>{data.working_hours.map(item =>
<>
  <input name='description' type={text} value={item.description}
   onChange={(e) => handleChange(e,item.id)} />

  <input name='price' type={text} value={item.price}
   onChange={(e) => handleChange(e,item.id)} />
</>
)}
</code>```

change handleChange

```<code>
function handleChange(e,id){
 const value = e.target.value;
 const name= e.target.name;
 var dataitemIndex = data.working_hours.findIndex(x=>x.id == id);
data.working_hours[dataitemIndex] = {...data.working_hours[dataitemIndex],[event.target.name]: event.target.value};
 setData(data);
}
</code>```

Body:
I have an react state with objects/array that is filled, but also then later I want to edit text inputs and edit the related fields on object also, i found no solutions until now.

So this is my state for example:

const [data, setData] = useState({
    working_hours: [
      {
        id: 1,
        description: 'Random Text',
        price: 100,

      },
      {
        id: 2,
        description: 'Text Random',
        price: 100,
      },
    ]
  });

Here is my Jsx:

{data.working_hours.map(item =>
<>
  <input type={text} value={item.description}
   onChange={(e) => handleChange(e)} />

  <input type={text} value={item.price}
   onChange={(e) => handleChange(e)} />
</>
)}

Here is what I tried:

function handleChange(e){
 const value = e.target.value;
 setData({...data, [...data.working_hours, e.target.value]})
}

Body:
change elements

{data.working_hours.map(item =>
<>
  <input name='description' type={text} value={item.description}
   onChange={(e) => handleChange(e,item.id)} />

  <input name='price' type={text} value={item.price}
   onChange={(e) => handleChange(e,item.id)} />
</>
)}

change handleChange

function handleChange(e,id){
 const value = e.target.value;
 const name= e.target.name;
 var dataitemIndex = data.working_hours.findIndex(x=>x.id == id);
data.working_hours[dataitemIndex] = {...data.working_hours[dataitemIndex],[event.target.name]: event.target.value};
 setData(data);
}


问:
Problems with RSelenium and ChromeDriver - "This version of ChromeDriver only supports Chrome version X"
I'm having a difficult time getting RSelenium to work with my ChromeDriver in R v4.1.2. Initially, I installed the ChromeDriver v97 because I had Chrome v97 running on my Mac as my browser. However, despite installing the v97 ChromeDriver, I would get an error every time that read

Selenium message:session not created: This version of ChromeDriver only supports Chrome version 98

So I did some research and everything I read said I could either upgrade Google Chrome or downgrade my driver. I tried both. I uninstalled the driver and installed an earlier version (v96) but it still gave me the exact same error. Then I tried upgrading my Chrome browser, but it said it was up to date and that no upgrade was available. So I just figured I'd wait until v98 was ready to install. As soon as v98 was out, I upgraded my browser to Chrome v98 and Selenium with the ChromeDriver ran smoothly without issues. I haven't changed anything since. It ran for a couple of days, but now, all of a sudden, I'm getting the error again but now it says

```<code> "This version of ChromeDriver only supports Chrome version 99"
</code>```

But I have not upgraded my ChromeDriver since installing the v97 driver. It seems as though the driver must have some code in it that checks what the most current version of Chrome is (even if that is a Beta release) and requires that I have it, regardless of which driver or browser I have installed. Has anyone come across this issue before? Any idea of how I can resolve this? I cannot upgrade to v99, it's not available yet, and uninstalling my ChromeDriver and reinstalling a previous version doesn't seem to do anything either.

Thank you in advance.

答:
The Mac has problems because there are two architectures (Intel and M1), and the code that loads the RSelenium driver hasn't been updated since the M1 came out.

This patch https://github.com/ropensci/wdman/pull/26 fixed the issue for me, working on an Intel Mac.  You should also see this issue:  https://github.com/ropensci/RSelenium/issues/221, which offers some code to sequentially try drivers until it finds one that works.

Body:
I'm having a difficult time getting RSelenium to work with my ChromeDriver in R v4.1.2. Initially, I installed the ChromeDriver v97 because I had Chrome v97 running on my Mac as my browser. However, despite installing the v97 ChromeDriver, I would get an error every time that read

Selenium message:session not created: This version of ChromeDriver only supports Chrome version 98

So I did some research and everything I read said I could either upgrade Google Chrome or downgrade my driver. I tried both. I uninstalled the driver and installed an earlier version (v96) but it still gave me the exact same error. Then I tried upgrading my Chrome browser, but it said it was up to date and that no upgrade was available. So I just figured I'd wait until v98 was ready to install. As soon as v98 was out, I upgraded my browser to Chrome v98 and Selenium with the ChromeDriver ran smoothly without issues. I haven't changed anything since. It ran for a couple of days, but now, all of a sudden, I'm getting the error again but now it says

 "This version of ChromeDriver only supports Chrome version 99"

But I have not upgraded my ChromeDriver since installing the v97 driver. It seems as though the driver must have some code in it that checks what the most current version of Chrome is (even if that is a Beta release) and requires that I have it, regardless of which driver or browser I have installed. Has anyone come across this issue before? Any idea of how I can resolve this? I cannot upgrade to v99, it's not available yet, and uninstalling my ChromeDriver and reinstalling a previous version doesn't seem to do anything either.

Thank you in advance.


答:
try this:

class CardInfo extends StaefulWidget {
  PokemonCard card;

  CardInfo({required this.card});

  @override
  _CardInfoState createState() => _CardInfoState();
}

class _CardInfoState extends State<CardInfo> {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        backgroundColor: Colors.grey[900],
        appBar: AppBar(
          title: Text(
            "Card Profile",
            style: TextStyle(
                color: Colors.white,
                fontFamily: 'Blinker',
                fontSize: SizeConfig.blockSizeVertical * 3),
          ),
          backgroundColor: Colors.red,
          elevation: 0.0,
        ),
        body: Align(
          alignment: Alignment.center,
          child: ListView(
            children: [
              SizedBox(
                height: SizeConfig.blockSizeVertical * 3,
              ),
              Text(
                "Set: " +
                    widget.card.set.name +
                    "  //  Number: " +
                    widget.card.number,
                style: TextStyle(
                    color: Colors.white,
                    fontFamily: 'Blinker',
                    fontSize: SizeConfig.blockSizeVertical * 2),
              ),
              SizedBox(
                height: SizeConfig.blockSizeVertical * 3,
              ),
              Hero(
                tag: 'card' + widget.card.id,
                child: Image.network(
                  widget.card.images.large,
                  height: SizeConfig.blockSizeVertical * 30,
                ),
              ),
              SizedBox(
                height: SizeConfig.blockSizeVertical * 2,
              ),
              Text(
                widget.card.name,
                style: TextStyle(
                  color: Colors.white,
                  fontFamily: 'Blinker',
                  fontSize: SizeConfig.blockSizeVertical * 5,
                ),
              ),
              SizedBox(
                height: SizeConfig.blockSizeVertical * 2,
              ),
              GridView.count(
                mainAxisSpacing: SizeConfig.blockSizeVertical * 4,
                crossAxisSpacing: SizeConfig.blockSizeHorizontal * 4,
                crossAxisCount: 3,
                children: [
                  Container(
                    padding: EdgeInsets.symmetric(
                        vertical: SizeConfig.blockSizeVertical * 2,
                        horizontal: SizeConfig.blockSizeHorizontal * 2),
                    decoration: BoxDecoration(
                      border: Border.all(
                        color: Colors.white,
                      ),
                      borderRadius: BorderRadius.all(Radius.circular(20)),
                    ),
                    child: Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            "Subtypes",
                            style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'Blinker',
                                fontSize: SizeConfig.blockSizeVertical * 3,
                                fontWeight: FontWeight.bold),
                          ),
                          Text(
                            widget.card.subtypes
                                .map((e) => e.type)
                                .join(", "),
                            style: TextStyle(
                              color: Colors.white,
                              fontFamily: 'Blinker',
                              fontSize: SizeConfig.blockSizeVertical * 2,
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.symmetric(
                        vertical: SizeConfig.blockSizeVertical * 2,
                        horizontal: SizeConfig.blockSizeHorizontal * 2),
                    decoration: BoxDecoration(
                      border: Border.all(
                        color: Colors.white,
                      ),
                      borderRadius: BorderRadius.all(Radius.circular(20)),
                    ),
                    child: Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            "HP",
                            style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'Blinker',
                                fontSize: SizeConfig.blockSizeVertical * 3,
                                fontWeight: FontWeight.bold),
                          ),
                          Text(
                            widget.card.hp!,
                            style: TextStyle(
                              color: Colors.white,
                              fontFamily: 'Blinker',
                              fontSize: SizeConfig.blockSizeVertical * 2,
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.symmetric(
                        vertical: SizeConfig.blockSizeVertical * 2,
                        horizontal: SizeConfig.blockSizeHorizontal * 2),
                    decoration: BoxDecoration(
                      border: Border.all(
                        color: Colors.white,
                      ),
                      borderRadius: BorderRadius.all(Radius.circular(20)),
                    ),
                    child: Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            "Type",
                            style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'Blinker',
                                fontSize: SizeConfig.blockSizeVertical * 3,
                                fontWeight: FontWeight.bold),
                          ),
                          Text(
                            widget.card.types.map((e) => e.type).join(", "),
                            style: TextStyle(
                              color: Colors.white,
                              fontFamily: 'Blinker',
                              fontSize: SizeConfig.blockSizeVertical * 2,
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.symmetric(
                        vertical: SizeConfig.blockSizeVertical * 2,
                        horizontal: SizeConfig.blockSizeHorizontal * 2),
                    decoration: BoxDecoration(
                      border: Border.all(
                        color: Colors.white,
                      ),
                      borderRadius: BorderRadius.all(Radius.circular(20)),
                    ),
                    child: Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            "Weakness",
                            style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'Blinker',
                                fontSize: SizeConfig.blockSizeVertical * 3,
                                fontWeight: FontWeight.bold),
                          ),
                          Text(
                            widget.card.weaknesses
                                .map((e) => e.type + e.value)
                                .join(", "),
                            style: TextStyle(
                              color: Colors.white,
                              fontFamily: 'Blinker',
                              fontSize: SizeConfig.blockSizeVertical * 2,
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.symmetric(
                        vertical: SizeConfig.blockSizeVertical * 2,
                        horizontal: SizeConfig.blockSizeHorizontal * 2),
                    decoration: BoxDecoration(
                      border: Border.all(
                        color: Colors.white,
                      ),
                      borderRadius: BorderRadius.all(Radius.circular(20)),
                    ),
                    child: Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            "Resistance",
                            style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'Blinker',
                                fontSize: SizeConfig.blockSizeVertical * 3,
                                fontWeight: FontWeight.bold),
                          ),
                          Text(
                            widget.card.resistances
                                .map((e) =>
                                    e.type == "" ? "None" : e.type + e.value)
                                .join(", "),
                            style: TextStyle(
                              color: Colors.white,
                              fontFamily: 'Blinker',
                              fontSize: SizeConfig.blockSizeVertical * 2,
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.symmetric(
                        vertical: SizeConfig.blockSizeVertical * 2,
                        horizontal: SizeConfig.blockSizeHorizontal * 2),
                    decoration: BoxDecoration(
                      border: Border.all(
                        color: Colors.white,
                      ),
                      borderRadius: BorderRadius.all(Radius.circular(20)),
                    ),
                    child: Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            "Retreat Cost",
                            style: TextStyle(
                                color: Colors.white,
                                fontFamily: 'Blinker',
                                fontSize: SizeConfig.blockSizeVertical * 3,
                                fontWeight: FontWeight.bold),
                          ),
                          Text(
                            widget.card.convertedRetreatCost.toString(),
                            style: TextStyle(
                              color: Colors.white,
                              fontFamily: 'Blinker',
                              fontSize: SizeConfig.blockSizeVertical * 2,
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

```

Title: Flutter: How do I disable scrolling for a GridView widget, but have scrolling enabled for the page as a whole?


问:
Accessing SQL metadata in LightSwitch
I am trying to access extended properties in my SQL database in LightSwitch. Ideally I would be able to populate a choicelist based on these extended properties - namely picklist values.

Is there any way in which I can do this?

Any help would be much appreciated.

Cheers

Jimmy

答:
Expose the extended properties from SQL Server with a view or stored proc and then access it like regular application data.

Try this bundle of links which accompany my presentation on metadata: https://bitly.com/bundles/caderoux/3

Title: Accessing SQL metadata in LightSwitch


问:
Why second method of these classes are performing their functions as long as they are not called?
here i have server and client that can connect together and send message.but second method*(def run(self):)* of these classes in both server and client did not called why they are send and receive message?(Why these methods working without calling them?)

code of server that uses socket and Thread:

from threading import Thread
import socket

class SendingThread(Thread):
    def __init__(self, mySocket):
        Thread.__init__(self)
        self.mySocket = mySocket

    def run(self):
        # write code to send data continuously
        while True:
            data = input()
            self.mySocket.send(bytes(data, 'utf-8'))

class ReceivingThread(Thread):
    def __init__(self, mySocket):
        Thread.__init__(self)
        self.mySocket = mySocket

    def run(self):
        # write code to receive data continuously
        while True:
            msg = self.mySocket.recv(1024)
            print(msg.decode('utf-8'))

# create a socket object
s = socket.socket(
    socket.AF_INET, # internet address family => IP v4
    socket.SOCK_STREAM # TCP
)
# bind socket with a port number
s.bind(('127.0.0.1', 2010))
# keep System_1 in listening mode
s.listen()
# accept the incoming connection request
mySocket, address = s.accept()
# create a thread to send data
sendThread = SendingThread(mySocket)
# create an another to receive data
receiveThread = ReceivingThread(mySocket)
# start both threads
sendThread.start()
receiveThread.start()
```
<hr />
<h2>code of client that uses socket and Thread:</h2>
<pre class="lang-py prettyprint-override"><code>from threading import Thread
import socket

class MySendingThread(Thread):
    def __init__(self, mySocket):
        Thread.__init__(self)
        self.mySocket = mySocket

    def run(self):
        # write code to send data to System_1
        while True:
            data = input()
            self.mySocket.send(bytes(data, 'utf-8'))

class MyReceivingThread(Thread):
    def __init__(self, mySocket):
        Thread.__init__(self)
        self.mySocket = mySocket

    def run(self):
        # write code to receive data from System_1
        while True:
            msg = self.mySocket.recv(1024)
            print(msg.decode('utf-8'))

# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# send a connection request
s.connect(('127.0.0.1', 2010))
# create a thread to send data => System_1
mySendThread = MySendingThread(s)
# create a thread to receive data from System_1
myReceiveThread = MyReceivingThread(s)
# start both threads
mySendThread.start()
myReceiveThread.start()
</code>```

答:
SendingThread and ReceivingThread in server and MySendingThread and MyReceivingThread in client inherit from threading.Thread

Have a look at the docs:

The Thread class represents an activity that is run in a separate
thread of control. There are two ways to specify the activity: by
passing a callable object to the constructor, or by overriding the
run() method in a subclass. No other methods (except for the
constructor) should be overridden in a subclass. In other words, only
override the __init__() and run() methods of this class.

Once a thread object is created, its activity must be started by calling the thread’s start() method. This invokes the run() method in
a separate thread of control.

When you call start() it invoke the respective run() method you override in the child class.

Body:
here i have server and client that can connect together and send message.but second method*(def run(self):)* of these classes in both server and client did not called why they are send and receive message?(Why these methods working without calling them?)

code of server that uses socket and Thread:

from threading import Thread
import socket

class SendingThread(Thread):
    def __init__(self, mySocket):
        Thread.__init__(self)
        self.mySocket = mySocket

    def run(self):
        # write code to send data continuously
        while True:
            data = input()
            self.mySocket.send(bytes(data, 'utf-8'))

class ReceivingThread(Thread):
    def __init__(self, mySocket):
        Thread.__init__(self)
        self.mySocket = mySocket

    def run(self):
        # write code to receive data continuously
        while True:
            msg = self.mySocket.recv(1024)
            print(msg.decode('utf-8'))

# create a socket object
s = socket.socket(
    socket.AF_INET, # internet address family => IP v4
    socket.SOCK_STREAM # TCP
)
# bind socket with a port number
s.bind(('127.0.0.1', 2010))
# keep System_1 in listening mode
s.listen()
# accept the incoming connection request
mySocket, address = s.accept()
# create a thread to send data
sendThread = SendingThread(mySocket)
# create an another to receive data
receiveThread = ReceivingThread(mySocket)
# start both threads
sendThread.start()
receiveThread.start()

code of client that uses socket and Thread:

from threading import Thread
import socket

class MySendingThread(Thread):
    def __init__(self, mySocket):
        Thread.__init__(self)
        self.mySocket = mySocket

    def run(self):
        # write code to send data to System_1
        while True:
            data = input()
            self.mySocket.send(bytes(data, 'utf-8'))

class MyReceivingThread(Thread):
    def __init__(self, mySocket):
        Thread.__init__(self)
        self.mySocket = mySocket

    def run(self):
        # write code to receive data from System_1
        while True:
            msg = self.mySocket.recv(1024)
            print(msg.decode('utf-8'))

# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# send a connection request
s.connect(('127.0.0.1', 2010))
# create a thread to send data => System_1
mySendThread = MySendingThread(s)
# create a thread to receive data from System_1
myReceiveThread = MyReceivingThread(s)
# start both threads
mySendThread.start()
myReceiveThread.start()


问:
What is the file path of env.properties file in jenkins?
In job A , I am writing a value to env.properties file like below:
echo name=$name > env.properties

Is it possible to access that name in job B from the env.properties file?  If yes, can you please help , how can i achieve this.

答:
In job A, env.properties file locates in job A's workspace.

In job B, to access env.properties file in job A's workspace, you will use this path: ..\job A\env.properties

You can use Inject environment variable plugin to import that name in job B from the env.properties files

Note:

You can only use this way if both job A and job B running on same node


问:
confused about formatter in numpy. set_printoptions
I encountered the following piece of code:

```<code>z=np.arange(0,12)
np.set_printoptions(formatter=dict(int=lambda x: f'{x:4}'))
print(z)
</code>```

I understand what the code is doing but I am not clear as to what the quantity inside the brackets of dict() is. Without int= we have a function. In numpy docs the value of formatter should be a dict of callables. The keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. So shouldn't it be int: instead of int=? I got a synatx error when I tried that

答:
The notation int= is just keyword argument, passed to the method dict(), that is equivalent to

```<code>fmt = {"int": lambda x: f'{x:4}'}
</code>```

Other example

```<code>fmt = dict(int=lambda x: f'{x:4}', float=lambda x: f'{x:4}')
fmt = {"int": lambda x: f'{x:4}', 'float': lambda x: f'{x:10}'}
fmt = dict(int=lambda x: f'{x:4}', float=lambda x: f'{x:10}')
fmt = {"int": lambda x: f'{x:4}', 'float': lambda x: f'{x:10}'}

value = 1
print(fmt[type(value).__name__](value))  #    1

value = 1.1
print(fmt[type(value).__name__](value))  #           1.1
</code>```

Body:
I encountered the following piece of code:

z=np.arange(0,12)
np.set_printoptions(formatter=dict(int=lambda x: f'{x:4}'))
print(z)

I understand what the code is doing but I am not clear as to what the quantity inside the brackets of dict() is. Without int= we have a function. In numpy docs the value of formatter should be a dict of callables. The keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. So shouldn't it be int: instead of int=? I got a synatx error when I tried that

Body:
The notation int= is just keyword argument, passed to the method dict(), that is equivalent to

fmt = {"int": lambda x: f'{x:4}'}

Other example

fmt = dict(int=lambda x: f'{x:4}', float=lambda x: f'{x:4}')
fmt = {"int": lambda x: f'{x:4}', 'float': lambda x: f'{x:10}'}
fmt = dict(int=lambda x: f'{x:4}', float=lambda x: f'{x:10}')
fmt = {"int": lambda x: f'{x:4}', 'float': lambda x: f'{x:10}'}

value = 1
print(fmt[type(value).__name__](value))  #    1

value = 1.1
print(fmt[type(value).__name__](value))  #           1.1