问:
is it possible to use a svg as a placeholder for image in next js?
I'm using next Js Image tag (next/image). Is it possible to import a svg and use it as a placeholder until the image finish loading?

I tried to create a use State and it to true on the "onLoad" of the tag as I would do in a img tag, but that doesn't work. The fallback image that should show before the image load never shows, it's like the images are always loaded, even thought they didn't appear on html yet

Here the code I tried:

```<code>const [hasImageLoaded, setHasImageLoaded] = useState(false);

  function handleImageLoaded(): void {
    setHasImageLoaded(true);
  }

const displayImgStyle = {
  display: hasImageLoaded ? undefined : 'none',
};

const loadingImgStyle = {
  display: hasImageLoaded ? 'none' : undefined,
};

return (
<>
  <div style={displayImgStyle}>
    <Image
      width={216}
      height={216}
      className={styles.pokemon}
      src={image}
      alt={name}
      title={name}
      onLoad={handleImageLoaded}
    />
  </div>

  <MySvg style={loadingImgStyle} />
</>
)

</code>```

答:
NextJS v11 and higher

Use blurDataURL property for placeholders, but before convert your SVG to data-uri.

Read more about blurDataURL

 Solution for NextJS below version v11

To avoid the image loading before the placeholder does you need to convert it to data-uri and deliver it with your code:

const placeholder = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='-8 -8 40 40' fill='none' stroke='%23fff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-image'%3E%3Crect x='3' y='3' width='18' height='18' rx='2' ry='2'%3E%3C/rect%3E%3Ccircle cx='8.5' cy='8.5' r='1.5'%3E%3C/circle%3E%3Cpolyline points='21 15 16 10 5 21'%3E%3C/polyline%3E%3C/svg%3E`

```
<p>Now you need to fetch the real image and for this use <code>Image</code> class:</p>
<pre class="lang-js prettyprint-override"><code>const [url, setUrl] = useState(placeholder) // use placeholder as default image, which appears instantly

const img = new Image()
img.src = src
img.onload = () => setUrl(img.src) // callback is called when image is loaded, with setUrl we swap images
</code>```

Full component:

import './styles.css'
import {useEffect, useState} from 'react'

// to create data url use this service: https://heyallan.github.io/svg-to-data-uri/
const placeholder = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='-8 -8 40 40' fill='none' stroke='%23fff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-image'%3E%3Crect x='3' y='3' width='18' height='18' rx='2' ry='2'%3E%3C/rect%3E%3Ccircle cx='8.5' cy='8.5' r='1.5'%3E%3C/circle%3E%3Cpolyline points='21 15 16 10 5 21'%3E%3C/polyline%3E%3C/svg%3E`

const Picture = ({alt, src, ...props}) => {
  const [url, setUrl] = useState(placeholder)
  useEffect(() => {
    if (!src) return
    const img = new Image()
    img.src = src
    img.onload = () => setUrl(img.src)
  }, [src])

  return
}

const App = () => (

Hello CodeSandbox

    <Picture
      className='img'
      alt='Random image'
      src='https://picsum.photos/500/500'
    />

)

```
<p>☝ To avoid name collisions import NextJS <code>Image</code> component with different name:</p>
<pre class="lang-js prettyprint-override"><code>import NextImage from 'next/image' // instead of import Image from 'next/image'

</code>```

Here you can find the demo. To see how it works click refresh icon:

Body:
I'm using next Js Image tag (next/image). Is it possible to import a svg and use it as a placeholder until the image finish loading?

I tried to create a use State and it to true on the "onLoad" of the tag as I would do in a img tag, but that doesn't work. The fallback image that should show before the image load never shows, it's like the images are always loaded, even thought they didn't appear on html yet

Here the code I tried:

const [hasImageLoaded, setHasImageLoaded] = useState(false);

  function handleImageLoaded(): void {
    setHasImageLoaded(true);
  }

const displayImgStyle = {
  display: hasImageLoaded ? undefined : 'none',
};

const loadingImgStyle = {
  display: hasImageLoaded ? 'none' : undefined,
};

return (
<>

    <Image
      width={216}
      height={216}
      className={styles.pokemon}
      src={image}
      alt={name}
      title={name}
      onLoad={handleImageLoaded}
    />

  <MySvg style={loadingImgStyle} />
</>
)

Body:
NextJS v11 and higher

Use blurDataURL property for placeholders, but before convert your SVG to data-uri.

Read more about blurDataURL

 Solution for NextJS below version v11

To avoid the image loading before the placeholder does you need to convert it to data-uri and deliver it with your code:

const placeholder = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='-8 -8 40 40' fill='none' stroke='%23fff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-image'%3E%3Crect x='3' y='3' width='18' height='18' rx='2' ry='2'%3E%3C/rect%3E%3Ccircle cx='8.5' cy='8.5' r='1.5'%3E%3C/circle%3E%3Cpolyline points='21 15 16 10 5 21'%3E%3C/polyline%3E%3C/svg%3E`

<img src={placeholder}/>

Now you need to fetch the real image and for this use Image class:

const [url, setUrl] = useState(placeholder) // use placeholder as default image, which appears instantly

const img = new Image()
img.src = src
img.onload = () => setUrl(img.src) // callback is called when image is loaded, with setUrl we swap images

Full component:

import './styles.css'
import {useEffect, useState} from 'react'

// to create data url use this service: https://heyallan.github.io/svg-to-data-uri/
const placeholder = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='-8 -8 40 40' fill='none' stroke='%23fff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-image'%3E%3Crect x='3' y='3' width='18' height='18' rx='2' ry='2'%3E%3C/rect%3E%3Ccircle cx='8.5' cy='8.5' r='1.5'%3E%3C/circle%3E%3Cpolyline points='21 15 16 10 5 21'%3E%3C/polyline%3E%3C/svg%3E`

const Picture = ({alt, src, ...props}) => {
  const [url, setUrl] = useState(placeholder)
  useEffect(() => {
    if (!src) return
    const img = new Image()
    img.src = src
    img.onload = () => setUrl(img.src)
  }, [src])

  return <img alt={alt} src={url} {...props} />
}

const App = () => (
  <div className='App'>
    <h1>Hello CodeSandbox</h1>
    <Picture
      className='img'
      alt='Random image'
      src='https://picsum.photos/500/500'
    />
  </div>
)

☝ To avoid name collisions import NextJS Image component with different name:

import NextImage from 'next/image' // instead of import Image from 'next/image'

Here you can find the demo. To see how it works click refresh icon:


来源: stackexchange

问:
How to fix IndexError: invalid index to scalar variable
This code generates error:

```<code>IndexError: invalid index to scalar variable.
</code>```

at the line: results.append(RMSPE(np.expm1(y_train[testcv]), [y[1] for y in y_test]))

How to fix it?

```<code>import pandas as pd
import numpy as np
from sklearn import ensemble
from sklearn import cross_validation

def ToWeight(y):
    w = np.zeros(y.shape, dtype=float)
    ind = y != 0
    w[ind] = 1./(y[ind]**2)
    return w

def RMSPE(y, yhat):
    w = ToWeight(y)
    rmspe = np.sqrt(np.mean( w * (y - yhat)**2 ))
    return rmspe

forest = ensemble.RandomForestRegressor(n_estimators=10, min_samples_split=2, n_jobs=-1)

print ("Cross validations")
cv = cross_validation.KFold(len(train), n_folds=5)

results = []
for traincv, testcv in cv:
    y_test = np.expm1(forest.fit(X_train[traincv], y_train[traincv]).predict(X_train[testcv]))
    results.append(RMSPE(np.expm1(y_train[testcv]), [y[1] for y in y_test]))
</code>```

testcv is:

```<code>[False False False ...,  True  True  True]
</code>```

答:
Editing the yolo_video.py file in repo is required for those who are using darknet code.`This file works, replaced with required edits</p>
```<code># import the necessary packages
import numpy as np
import argparse
import imutils
import time
import cv2
import os
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", required=True,
    help="path to input video")
ap.add_argument("-o", "--output", required=True,
    help="path to output video")
ap.add_argument("-y", "--yolo", required=True,
    help="base path to YOLO directory")
ap.add_argument("-c", "--confidence", type=float, default=0.5,
    help="minimum probability to filter weak detections")
ap.add_argument("-t", "--threshold", type=float, default=0.3,
    help="threshold when applyong non-maxima suppression")
args = vars(ap.parse_args())

# load the COCO class labels our YOLO model was trained on
labelsPath = os.path.sep.join([args["yolo"], "biscuits.names"])
LABELS = open(labelsPath).read().strip().split("\n")
# initialize a list of colors to represent each possible class label
np.random.seed(42)
COLORS = np.random.randint(0, 255, size=(len(LABELS), 3),
    dtype="uint8")
# derive the paths to the YOLO weights and model configuration
weightsPath = os.path.sep.join([args["yolo"], "yolov4-custom_best.weights"])
configPath = os.path.sep.join([args["yolo"], "yolov4-custom.cfg"])
# load our YOLO object detector trained on COCO dataset (80 classes)
# and determine only the *output* layer names that we need from YOLO
print("[INFO] loading YOLO from disk...")
net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)

ln = net.getLayerNames()
print("ln",net)
ln = [ln[i - 1] for i in net.getUnconnectedOutLayers()]

# initialize the video stream, pointer to output video file, and
# frame dimensions
vs = cv2.VideoCapture(args["input"])
writer = None
(W, H) = (None, None)
# try to determine the total number of frames in the video file
try:
    prop = cv2.cv.CV_CAP_PROP_FRAME_COUNT if imutils.is_cv2()\
        else cv2.CAP_PROP_FRAME_COUNT
    total = int(vs.get(prop))
    print("[INFO] {} total frames in video".format(total))
# an error occurred while trying to determine the total
# number of frames in the video file
except:
    print("[INFO] could not determine # of frames in video")
    print("[INFO] no approx. completion time can be provided")
    total = -1

# loop over frames from the video file stream
while True:
    # read the next frame from the file
    (grabbed, frame) = vs.read()
    # if the frame was not grabbed, then we have reached the end
    # of the stream
    if not grabbed:
        break
    # if the frame dimensions are empty, grab them
    if W is None or H is None:
        (H, W) = frame.shape[:2]
        # construct a blob from the input frame and then perform a forward
    # pass of the YOLO object detector, giving us our bounding boxes
    # and associated probabilities
    blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416),
        swapRB=True, crop=False)
    net.setInput(blob)
    start = time.time()
    layerOutputs = net.forward(ln)
    end = time.time()
    # initialize our lists of detected bounding boxes, confidences,
    # and class IDs, respectively
    boxes = []
    confidences = []
    classIDs = []
# loop over each of the layer outputs
    for output in layerOutputs:
        # loop over each of the detections
        for detection in output:
            # extract the class ID and confidence (i.e., probability)
            # of the current object detection
            scores = detection[5:]
            classID = np.argmax(scores)
            confidence = scores[classID]
            # filter out weak predictions by ensuring the detected
            # probability is greater than the minimum probability
            if confidence > args["confidence"]:
                # scale the bounding box coordinates back relative to
                # the size of the image, keeping in mind that YOLO
                # actually returns the center (x, y)-coordinates of
                # the bounding box followed by the boxes' width and
                # height
                box = detection[0:4] * np.array([W, H, W, H])
                (centerX, centerY, width, height) = box.astype("int")
                # use the center (x, y)-coordinates to derive the top
                # and and left corner of the bounding box
                x = int(centerX - (width / 2))
                y = int(centerY - (height / 2))
                # update our list of bounding box coordinates,
                # confidences, and class IDs
                boxes.append([x, y, int(width), int(height)])
                confidences.append(float(confidence))
                classIDs.append(classID)
    # apply non-maxima suppression to suppress weak, overlapping
    # bounding boxes
    idxs = cv2.dnn.NMSBoxes(boxes, confidences, args["confidence"],
        args["threshold"])
    # ensure at least one detection exists
    if len(idxs) > 0:
        # loop over the indexes we are keeping
        for i in idxs.flatten():
            # extract the bounding box coordinates
            (x, y) = (boxes[i][0], boxes[i][1])
            (w, h) = (boxes[i][2], boxes[i][3])
            # draw a bounding box rectangle and label on the frame
            color = [int(c) for c in COLORS[classIDs[i]]]
            cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
            text = "{}: {:.4f}".format(LABELS[classIDs[i]],
                confidences[i])
            cv2.putText(frame, text, (x, y - 5),
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
    # check if the video writer is None
    if writer is None:
        # initialize our video writer
        fourcc = cv2.VideoWriter_fourcc(*"MJPG")
        writer = cv2.VideoWriter(args["output"], fourcc, 30,
            (frame.shape[1], frame.shape[0]), True)
        # some information on processing single frame
        if total > 0:
            elap = (end - start)
            print("[INFO] single frame took {:.4f} seconds".format(elap))
            print("[INFO] estimated total time to finish: {:.4f}".format(
                elap * total))
    # write the output frame to disk
    writer.write(frame)
# release the file pointers
print("[INFO] cleaning up...")
writer.release()
vs.release()`
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This code generates error:

IndexError: invalid index to scalar variable.

at the line: results.append(RMSPE(np.expm1(y_train[testcv]), [y[1] for y in y_test]))

How to fix it?

import pandas as pd
import numpy as np
from sklearn import ensemble
from sklearn import cross_validation

def ToWeight(y):
    w = np.zeros(y.shape, dtype=float)
    ind = y != 0
    w[ind] = 1./(y[ind]**2)
    return w

def RMSPE(y, yhat):
    w = ToWeight(y)
    rmspe = np.sqrt(np.mean( w * (y - yhat)**2 ))
    return rmspe

forest = ensemble.RandomForestRegressor(n_estimators=10, min_samples_split=2, n_jobs=-1)

print ("Cross validations")
cv = cross_validation.KFold(len(train), n_folds=5)

results = []
for traincv, testcv in cv:
    y_test = np.expm1(forest.fit(X_train[traincv], y_train[traincv]).predict(X_train[testcv]))
    results.append(RMSPE(np.expm1(y_train[testcv]), [y[1] for y in y_test]))

testcv is:

[False False False ...,  True  True  True]

Body:
Editing the yolo_video.py file in repo is required for those who are using darknet code.`This file works, replaced with required edits

# import the necessary packages
import numpy as np
import argparse
import imutils
import time
import cv2
import os
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", required=True,
    help="path to input video")
ap.add_argument("-o", "--output", required=True,
    help="path to output video")
ap.add_argument("-y", "--yolo", required=True,
    help="base path to YOLO directory")
ap.add_argument("-c", "--confidence", type=float, default=0.5,
    help="minimum probability to filter weak detections")
ap.add_argument("-t", "--threshold", type=float, default=0.3,
    help="threshold when applyong non-maxima suppression")
args = vars(ap.parse_args())

# load the COCO class labels our YOLO model was trained on
labelsPath = os.path.sep.join([args["yolo"], "biscuits.names"])
LABELS = open(labelsPath).read().strip().split("\n")
# initialize a list of colors to represent each possible class label
np.random.seed(42)
COLORS = np.random.randint(0, 255, size=(len(LABELS), 3),
    dtype="uint8")
# derive the paths to the YOLO weights and model configuration
weightsPath = os.path.sep.join([args["yolo"], "yolov4-custom_best.weights"])
configPath = os.path.sep.join([args["yolo"], "yolov4-custom.cfg"])
# load our YOLO object detector trained on COCO dataset (80 classes)
# and determine only the *output* layer names that we need from YOLO
print("[INFO] loading YOLO from disk...")
net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)

ln = net.getLayerNames()
print("ln",net)
ln = [ln[i - 1] for i in net.getUnconnectedOutLayers()]

# initialize the video stream, pointer to output video file, and
# frame dimensions
vs = cv2.VideoCapture(args["input"])
writer = None
(W, H) = (None, None)
# try to determine the total number of frames in the video file
try:
    prop = cv2.cv.CV_CAP_PROP_FRAME_COUNT if imutils.is_cv2()\
        else cv2.CAP_PROP_FRAME_COUNT
    total = int(vs.get(prop))
    print("[INFO] {} total frames in video".format(total))
# an error occurred while trying to determine the total
# number of frames in the video file
except:
    print("[INFO] could not determine # of frames in video")
    print("[INFO] no approx. completion time can be provided")
    total = -1

# loop over frames from the video file stream
while True:
    # read the next frame from the file
    (grabbed, frame) = vs.read()
    # if the frame was not grabbed, then we have reached the end
    # of the stream
    if not grabbed:
        break
    # if the frame dimensions are empty, grab them
    if W is None or H is None:
        (H, W) = frame.shape[:2]
        # construct a blob from the input frame and then perform a forward
    # pass of the YOLO object detector, giving us our bounding boxes
    # and associated probabilities
    blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416),
        swapRB=True, crop=False)
    net.setInput(blob)
    start = time.time()
    layerOutputs = net.forward(ln)
    end = time.time()
    # initialize our lists of detected bounding boxes, confidences,
    # and class IDs, respectively
    boxes = []
    confidences = []
    classIDs = []
# loop over each of the layer outputs
    for output in layerOutputs:
        # loop over each of the detections
        for detection in output:
            # extract the class ID and confidence (i.e., probability)
            # of the current object detection
            scores = detection[5:]
            classID = np.argmax(scores)
            confidence = scores[classID]
            # filter out weak predictions by ensuring the detected
            # probability is greater than the minimum probability
            if confidence > args["confidence"]:
                # scale the bounding box coordinates back relative to
                # the size of the image, keeping in mind that YOLO
                # actually returns the center (x, y)-coordinates of
                # the bounding box followed by the boxes' width and
                # height
                box = detection[0:4] * np.array([W, H, W, H])
                (centerX, centerY, width, height) = box.astype("int")
                # use the center (x, y)-coordinates to derive the top
                # and and left corner of the bounding box
                x = int(centerX - (width / 2))
                y = int(centerY - (height / 2))
                # update our list of bounding box coordinates,
                # confidences, and class IDs
                boxes.append([x, y, int(width), int(height)])
                confidences.append(float(confidence))
                classIDs.append(classID)
    # apply non-maxima suppression to suppress weak, overlapping
    # bounding boxes
    idxs = cv2.dnn.NMSBoxes(boxes, confidences, args["confidence"],
        args["threshold"])
    # ensure at least one detection exists
    if len(idxs) > 0:
        # loop over the indexes we are keeping
        for i in idxs.flatten():
            # extract the bounding box coordinates
            (x, y) = (boxes[i][0], boxes[i][1])
            (w, h) = (boxes[i][2], boxes[i][3])
            # draw a bounding box rectangle and label on the frame
            color = [int(c) for c in COLORS[classIDs[i]]]
            cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
            text = "{}: {:.4f}".format(LABELS[classIDs[i]],
                confidences[i])
            cv2.putText(frame, text, (x, y - 5),
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
    # check if the video writer is None
    if writer is None:
        # initialize our video writer
        fourcc = cv2.VideoWriter_fourcc(*"MJPG")
        writer = cv2.VideoWriter(args["output"], fourcc, 30,
            (frame.shape[1], frame.shape[0]), True)
        # some information on processing single frame
        if total > 0:
            elap = (end - start)
            print("[INFO] single frame took {:.4f} seconds".format(elap))
            print("[INFO] estimated total time to finish: {:.4f}".format(
                elap * total))
    # write the output frame to disk
    writer.write(frame)
# release the file pointers
print("[INFO] cleaning up...")
writer.release()
vs.release()`

ContentLicense: CC BY-SA 4.0


问:
Generate an image with features ORB can detect
For the purposes of a unit test, I'm trying to create an image with features ORB can detect; this is preferable to storing a real-world image. I'm using simple geometric shapes with lots of corners, but ORB isn't finding anything -- why not?

This is my image:

Which I generated with this code:

```<code>import cv2
import numpy as np

img_dims = (480, 640)
center = (np.array(img_dims) / 2).astype(int)
radius = 10

features = np.zeros(img_dims+(3,), dtype=np.float32)

features = cv2.rectangle(features,
                         (center - radius)[::-1],
                         (center + radius)[::-1],
                         (0, 255, 0),
                         -1)
features = cv2.circle(features,
                      center[::-1],
                      radius,
                      (255, 0, 0),
                      2)
features = cv2.rectangle(features,
                         (center - int(radius / 2))[::-1],
                         (center + int(radius / 2))[::-1],
                         (0, 0, 255),
                         -1)

# cv2.imshow("", features)
# cv2.waitKey(-1)

detector = cv2.ORB_create(nfeatures=100000)
keypoints, descriptors = detector.detectAndCompute(features, None)
assert len(keypoints)
</code>```

答: The problem was the datatype of the image, which needed to be np.uint8.

Body:
For the purposes of a unit test, I'm trying to create an image with features ORB can detect; this is preferable to storing a real-world image. I'm using simple geometric shapes with lots of corners, but ORB isn't finding anything -- why not?

This is my image:

Which I generated with this code:

import cv2
import numpy as np

img_dims = (480, 640)
center = (np.array(img_dims) / 2).astype(int)
radius = 10

features = np.zeros(img_dims+(3,), dtype=np.float32)

features = cv2.rectangle(features,
                         (center - radius)[::-1],
                         (center + radius)[::-1],
                         (0, 255, 0),
                         -1)
features = cv2.circle(features,
                      center[::-1],
                      radius,
                      (255, 0, 0),
                      2)
features = cv2.rectangle(features,
                         (center - int(radius / 2))[::-1],
                         (center + int(radius / 2))[::-1],
                         (0, 0, 255),
                         -1)

# cv2.imshow("", features)
# cv2.waitKey(-1)

detector = cv2.ORB_create(nfeatures=100000)
keypoints, descriptors = detector.detectAndCompute(features, None)
assert len(keypoints)


问:
Calling MSSQL stored procedures from iReport
I want to call an stored procedure in an MSSQL server from iReport.

Query:

```<code>SET QUOTED_IDENTIFIER OFF
SET DATEFORMAT mdy

Exec SP_SAMPLE '12-jan-2008', '12-jul-2011',
"$P!{Param1}",
"$P!{Param2}",
1,
"$P!{Param3}"

SET QUOTED_IDENTIFIER ON
Where,
    Param1 = 'A436F3A9-6A8B-40C4-B38E-567B05522449',
        '4DD40BC2-3390-4B1B-8841-        483A8FDAB2FD',
        'B95E8F04-6EE7-4BC6-BDD0-F95C4AFDAC0B',
        'AE757961-0E25-41B8-A382-    7600DDA0ABC7',
        '90B9CC0C-6090-4CEF-8BC9-9C8EA3C0F63C',
        '1E191B19-13D0-4CE2-B1EC-    3CFF9316887F',
        'A9EE7AE9-435C-4164-96F5-3DB20A6321BE',
        'DCD6D045-8B42-4B83-8C97-21EE9DFF644C'
    Param2 = '4E6E8464-F08A-4BB8-950F-38908E4E7B30',
        '76EBA40E-F898-4541-9208-8A6B3A35E082',
        '7C64DA92-C168-4A74-8955-F1974258AD12',
        '2E6DDC25-E037-4842-9E7F-2B9586561744'
    Param3 = 3EC43FB7-F258-4441-8188-A55E7BD40ADE
</code>```

Note that stored procedures param1, param2, param3 are of text datatype in sqlserver. Whereas in iReport I made them a collection.

Could any one tell me how can I generate the above query in iReport with the double quotes?

Also, Is there any way to display the query with filled parameter values when running iReport?

答:
Jasper Reports operates with two types of parameters: $P{name_parameter} and $P!{name_parameter}.
You using $P! parameter in query that give you full control on building query.

Example:

```<code><parameter name="strParam1" class="java.lang.String"/>
<parameter name="strParam2" class="java.lang.String"/>
<parameter name="strParam3" class="java.lang.String"/>
<queryString><![CDATA[SELECT atr1 FROM mytable WHERE stratr1=$P{strParam1} AND stratr2=$P!{strParam2} AND stratr3=$P!{strParam3}]]></queryString>
</code>```

If:

```<code>strParam1 =  string1 // (without quotes)
strParam2 = 'string2' // param (with quotes)
strParam3 =  string3 // (without quotes)
</code>```

the result query will be:

```<code>SELECT atr1 FROM mytable WHERE stratr1='string1' AND stratr2='string2' AND stratr3=string3
</code>```

Also, Is there any way to display the query with filled parameter
  values when running iReport?

In IReport 4.1 you can view resulting query in output console (iReport output window).

You can set log4j.properties to see result query for custom java application.

Body:
I want to call an stored procedure in an MSSQL server from iReport.

Query:

SET QUOTED_IDENTIFIER OFF
SET DATEFORMAT mdy

Exec SP_SAMPLE '12-jan-2008', '12-jul-2011',
"$P!{Param1}",
"$P!{Param2}",
1,
"$P!{Param3}"

SET QUOTED_IDENTIFIER ON
Where,
    Param1 = 'A436F3A9-6A8B-40C4-B38E-567B05522449',
        '4DD40BC2-3390-4B1B-8841-        483A8FDAB2FD',
        'B95E8F04-6EE7-4BC6-BDD0-F95C4AFDAC0B',
        'AE757961-0E25-41B8-A382-    7600DDA0ABC7',
        '90B9CC0C-6090-4CEF-8BC9-9C8EA3C0F63C',
        '1E191B19-13D0-4CE2-B1EC-    3CFF9316887F',
        'A9EE7AE9-435C-4164-96F5-3DB20A6321BE',
        'DCD6D045-8B42-4B83-8C97-21EE9DFF644C'
    Param2 = '4E6E8464-F08A-4BB8-950F-38908E4E7B30',
        '76EBA40E-F898-4541-9208-8A6B3A35E082',
        '7C64DA92-C168-4A74-8955-F1974258AD12',
        '2E6DDC25-E037-4842-9E7F-2B9586561744'
    Param3 = 3EC43FB7-F258-4441-8188-A55E7BD40ADE

Note that stored procedures param1, param2, param3 are of text datatype in sqlserver. Whereas in iReport I made them a collection.

Could any one tell me how can I generate the above query in iReport with the double quotes?

Also, Is there any way to display the query with filled parameter values when running iReport?

Body:
Jasper Reports operates with two types of parameters: $P{name_parameter} and $P!{name_parameter}.
You using $P! parameter in query that give you full control on building query.

Example:

<parameter name="strParam1" class="java.lang.String"/>
<parameter name="strParam2" class="java.lang.String"/>
<parameter name="strParam3" class="java.lang.String"/>
<queryString><![CDATA[SELECT atr1 FROM mytable WHERE stratr1=$P{strParam1} AND stratr2=$P!{strParam2} AND stratr3=$P!{strParam3}]]></queryString>

If:

strParam1 =  string1 // (without quotes)
strParam2 = 'string2' // param (with quotes)
strParam3 =  string3 // (without quotes)

the result query will be:

SELECT atr1 FROM mytable WHERE stratr1='string1' AND stratr2='string2' AND stratr3=string3

Also, Is there any way to display the query with filled parameter
  values when running iReport?

In IReport 4.1 you can view resulting query in output console (iReport output window).

You can set log4j.properties to see result query for custom java application.


问:
Port not running but app wont stop running in browser - Windows - React - Node
So when I go to localhost:3001 it shows project I worked on before. I restart my computer, its still there, kill all node/vscode processes in task manager, its still there. I tried the npx kill port 3001 - seems ok says "port killed" but, the app still there in localhost 3001. When I use netstat findstr 3001 shows nothing there. When I use CurrPort or cmd to check all ports listening - 3001 doesn't show up.

If I listen in port 3000, everything works normal, but when I npm start another app in React itll take me to port 3001 and it doesnt give any error. Except when it opens on Port 3001 it doesnt display the app I npm started in, it still shows that ghost app that I cant get out of port 3001.

In the network tab of the ghost app/port 3001 it shows port 3001 there. I cant post screenshots cus low reputation but idk if something with the initiators in network tab might give a hint to what the problem is.

I could always just set it so React uses 3002 onwards or just run one app at a time in port:3000 buts its bothering that this ghost app has taken over a port.

Hopefully its just something stupid Im overlooking, but if anybody ever had a similar experience let me know!

TL:DR my port 3001 is showing not running listening everywhere I check but everytime I go to it it shows this old project and if I try to run another app at the port terminal says its running, everything ok ,but it is still that old app still there

答: So it seemed to be something with the browser not port, worked normal in another browser. So went into the inspector tools of the browser went in storage and deleted all cookies, cache, local&session storage and that fixed it. Also killing the service-worker.js process in the port worked for someone else who had the same problem from the project.</p>


问:
VBA and python script does not work together
Python code does not run after executing. The code has to read the data frames from the Excel where I run VBA code to execute the python code. Im not sure this could be a reason since I have another totally different excel where I do exactly same running VBA code in excel file to run a python code, which reads the data in this excel file. I get the finished msgbox in less then a second but if I run a code in Pycharm it takes 2 min to finish.

```<code>Option Explicit
Sub RunPythonScript()

'Declare Variables
Dim objShell As Object
Dim PythonExe, PythonScript As String

'Create a new Object shell.
Set objShell = VBA.CreateObject("Wscript.Shell")

'Provide file path to Python.exe
'USE TRIPLE QUOTES WHEN FILE PATH CONTAINS SPACES.
PythonExe = """C:\Users\gobro7\AppData\Local\Programs\Python\Python39\python.exe"""
PythonScript = "C:\Users\gobro7\Wholesale - Documents\Report\VL.py"

'Run the Python Script
objShell.Run PythonExe & PythonScript

MsgBox "Finished"

End Sub
</code>```

Path in python script

```<code>import pandas as pd
import numpy as np
import os

# Get the user
username = os.getlogin()

# search for directory
directory = r'C:/Users/' + username + '/Wholesale - Documents/Report/'
</code>```

答:
Basically, try

```<code>PythonExe = """C:\Users\gobro7\AppData\Local\Programs\Python\Python39\python.exe """
PythonScript = """C:\Users\gobro7\Wholesale - Documents\Report\VL.py"""

'Run the Python Script
objShell.Run PythonExe & PythonScript, 0, True
</code>```

Note the space at the end of PythonExe as well the triple double-quotes around PythonScript.
The 0 will keep the shell window hidden, True will wait for the job to return.

EDIT:
Today I was able to test on Windows/Excel. So I created a python script:

```<code>import pandas as pd
import time

print('start', str(time.time()))
df = pd.read_excel('Book1.xlsm')
print(df)
time.sleep(10) # just to waste some time like long running operation
print('end', str(time.time()))
</code>```

and Excel file Book1.xlsm with following macro

```<code>Sub RunPythonScript()

'Declare Variables
Dim objShell As Object
Dim PythonExe, PythonScript, cmd As String

'Create a new Object shell.
Set objShell = VBA.CreateObject("Wscript.Shell")

'Provide file path to Python.exe
'USE TRIPLE QUOTES WHEN FILE PATH CONTAINS SPACES.
PythonExe = "C:\Users\SomeRealUser\sandbox\sbox\Scripts\python.exe "
PythonScript = """C:\Users\SomeRealUser\sandbox\py script\mypy.py"""
cmd = PythonExe & PythonScript
Debug.Print cmd
'Run the Python Script
objShell.Run cmd, 1, True

MsgBox "Finished"

End Sub
</code>```

and some dummy data in Sheet1 and it worked as expected when I run RunPythonScript() macro.

Note:

I use virtual environment named sbox to run the python, with
pandas installed - it shouldn't matter or make difference as long as the path is correct and all dependencies are installed.

SomeRealUser is replacement for my real user

In objShell.Run cmd, 1, True I pass as second argument 1 to observe the terminal that is opened, but it works just fine with 0 (i.e. hidden terminal window)

The path to file deliberately has space to mimic your conditions.

All that said - in my opinion there are better ways to accomplish the task of runninf python code or even run the python script with Shell.run (see the link I shared to CPearson)

Body:
Python code does not run after executing. The code has to read the data frames from the Excel where I run VBA code to execute the python code. Im not sure this could be a reason since I have another totally different excel where I do exactly same running VBA code in excel file to run a python code, which reads the data in this excel file. I get the finished msgbox in less then a second but if I run a code in Pycharm it takes 2 min to finish.

Option Explicit
Sub RunPythonScript()

'Declare Variables
Dim objShell As Object
Dim PythonExe, PythonScript As String

'Create a new Object shell.
Set objShell = VBA.CreateObject("Wscript.Shell")

'Provide file path to Python.exe
'USE TRIPLE QUOTES WHEN FILE PATH CONTAINS SPACES.
PythonExe = """C:\Users\gobro7\AppData\Local\Programs\Python\Python39\python.exe"""
PythonScript = "C:\Users\gobro7\Wholesale - Documents\Report\VL.py"

'Run the Python Script
objShell.Run PythonExe & PythonScript

MsgBox "Finished"

End Sub

Path in python script

import pandas as pd
import numpy as np
import os

# Get the user
username = os.getlogin()

# search for directory
directory = r'C:/Users/' + username + '/Wholesale - Documents/Report/'

Body:
Basically, try

PythonExe = """C:\Users\gobro7\AppData\Local\Programs\Python\Python39\python.exe """
PythonScript = """C:\Users\gobro7\Wholesale - Documents\Report\VL.py"""

'Run the Python Script
objShell.Run PythonExe & PythonScript, 0, True

Note the space at the end of PythonExe as well the triple double-quotes around PythonScript.
The 0 will keep the shell window hidden, True will wait for the job to return.

EDIT:
Today I was able to test on Windows/Excel. So I created a python script:

import pandas as pd
import time

print('start', str(time.time()))
df = pd.read_excel('Book1.xlsm')
print(df)
time.sleep(10) # just to waste some time like long running operation
print('end', str(time.time()))

and Excel file Book1.xlsm with following macro

Sub RunPythonScript()

'Declare Variables
Dim objShell As Object
Dim PythonExe, PythonScript, cmd As String

'Create a new Object shell.
Set objShell = VBA.CreateObject("Wscript.Shell")

'Provide file path to Python.exe
'USE TRIPLE QUOTES WHEN FILE PATH CONTAINS SPACES.
PythonExe = "C:\Users\SomeRealUser\sandbox\sbox\Scripts\python.exe "
PythonScript = """C:\Users\SomeRealUser\sandbox\py script\mypy.py"""
cmd = PythonExe & PythonScript
Debug.Print cmd
'Run the Python Script
objShell.Run cmd, 1, True

MsgBox "Finished"

End Sub

and some dummy data in Sheet1 and it worked as expected when I run RunPythonScript() macro.

Note:

I use virtual environment named sbox to run the python, with
pandas installed - it shouldn't matter or make difference as long as the path is correct and all dependencies are installed.

SomeRealUser is replacement for my real user

In objShell.Run cmd, 1, True I pass as second argument 1 to observe the terminal that is opened, but it works just fine with 0 (i.e. hidden terminal window)

The path to file deliberately has space to mimic your conditions.

All that said - in my opinion there are better ways to accomplish the task of runninf python code or even run the python script with Shell.run (see the link I shared to CPearson)


问:
Is it possible to run an asynchronous function without making the main function as async?
Is it possible to run an asynchronous function without making the main function as async?

```<code>function index() {
    console.log('1');
    aaa();
    console.log('3');
}

async function aaa() {
    return await bbb().then((value) => {
        console.log(value);
    });
}

async function bbb() {
    return await new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('2');
        }, 1000);
    });
}

index();
</code>```

It is possible to display:

1

2

3

Without making the index function as async?

答:
You need to do something to cause console.log('3') to run after the promise returned by aaa() has been resolved.

Making index async and using await is the approach that most people find easiest to write and maintain.

```<code>async function index() {
    console.log('1');
    await aaa();
    console.log('3');
}
</code>```

You could use then() instead.

```<code>function index() {
    console.log('1');
    aaa().then(
        () => { console.log('3'); }
    );

}
</code>```

Body:
Is it possible to run an asynchronous function without making the main function as async?

function index() {
    console.log('1');
    aaa();
    console.log('3');
}

async function aaa() {
    return await bbb().then((value) => {
        console.log(value);
    });
}

async function bbb() {
    return await new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('2');
        }, 1000);
    });
}

index();

It is possible to display:

1

2

3

Without making the index function as async?

Body:
You need to do something to cause console.log('3') to run after the promise returned by aaa() has been resolved.

Making index async and using await is the approach that most people find easiest to write and maintain.

async function index() {
    console.log('1');
    await aaa();
    console.log('3');
}

You could use then() instead.

function index() {
    console.log('1');
    aaa().then(
        () => { console.log('3'); }
    );

}


问:
Django channels not recalling old messages from channel
I am using Django channels to create a chat app. When the chat page is refreshed, the past messages disappear. Also, when I reconnect to the channel, the old messages do not show up.

Everything else seems to work fine, messages can be sent and received by the other user, message data is being saved into the database for each specific channel. No error is thrown back.

managers.py

```<code>from django.db import models
from django.db.models import Count

class ThreadManager(models.Manager):
    def get_or_create_personal_thread(self, user1, user2):
        threads = self.get_queryset().filter(thread_type='personal')
        threads = threads.filter(users__in=[user1, user2]).distinct()
        threads = threads.annotate(u_count=Count('users')).filter(u_count=2)
        if threads.exists():
            return threads.first()
        else:
            thread = self.create(thread_type='personal')
            thread.users.add(user1)
            thread.users.add(user2)
            return thread

    def by_user(self, user):
        return self.get_queryset().filter(users__in=[user])
</code>```

models.py

```<code>from django.db import models
from app_users.models import User
from app_chat.managers import ThreadManager

class TrackingModel(models.Model):
    created_on = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class Thread(TrackingModel):
    THREAD_TYPE = (
        ('personal', 'Personal'),
        ('group', 'Group')
    )

    name = models.CharField(max_length=50, null=True, blank=True)
    thread_type = models.CharField(
        max_length=15, choices=THREAD_TYPE, default='group')
    users = models.ManyToManyField(User)

    objects = ThreadManager()

    def __str__(self):
        if self.thread_type == 'personal' and self.users.count() == 2:
            return f'{self.users.first()} and {self.users.last()}'
        return f'{self.name}'

class Message(TrackingModel):
    thread = models.ForeignKey(Thread, on_delete=models.CASCADE)
    sender = models.ForeignKey(User, on_delete=models.CASCADE)
    text = models.TextField(blank=False, null=False)

    def __str__(self) -> str:
        return f'From <Thread - {self.thread}>'
</code>```

consumers.py

```<code>import json
from channels.generic.websocket import AsyncWebsocketConsumer
from app_users.models import User
from app_chat.models import Thread, Message
from asgiref.sync import sync_to_async
from channels.db import database_sync_to_async

class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        me = self.scope['user']
        other_username = self.scope['url_route']['kwargs']['username']
        other_user = await sync_to_async(User.objects.get)(username=other_username)
        self.thread_obj = await sync_to_async(Thread.objects.get_or_create_personal_thread)(me, other_user)
        self.room_name = f'personal_thread_{self.thread_obj.id}'
        self.room_group_name = 'chat_%s' % self.room_name

        # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()
        print(f"Connected to server ==")

    async def disconnect(self, close_code):
        # Leave group
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket

    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        username = text_data_json['username']
        # Send message to room group
        await self.channel_layer.group_send(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message,
                'username': username,
            }
        )

        await self.store_message(message)

    # Receive message from room group
    async def chat_message(self, event):
        message = event['message']
        username = event['username']

        # Send message to WebSocket
        await self.send(text_data=json.dumps({
            'message': message,
            'username': username,
        }))
        # print(f'{username} : {message} Message recieved')

    @database_sync_to_async
    def store_message(self, message):
        Message.objects.create(
            thread=self.thread_obj,
            sender=self.scope['user'],
            text=message
        )
</code>```

room.html

```<code><!-- chat/templates/chat/room.html -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Chat Room</title>
</head>
<body>
    <textarea id="chat-log" cols="100" rows="20"></textarea><br>
    <input id="chat-message-input" type="text" size="100"><br>
    <input id="chat-message-submit" type="button" value="Send">
    {{ room_name|json_script:"room-name" }}
    {{ request.user.username|json_script:"user_username"}}
    <script>
        const user_username = JSON.parse(document.getElementById('user_username').textContent);
        const roomName = JSON.parse(document.getElementById('room-name').textContent);

        const chatSocket = new WebSocket(
            'ws://'
            + window.location.host
            + '/ws/chat/'
            + roomName
            + '/'
        );
        chatSocket.onopen = function(e) {
            console.log('Connection is open')
        };

        chatSocket.onmessage = function(e) {
            const data = JSON.parse(e.data);
            document.querySelector('#chat-log').value += (data.username + ': ' + data.message +  '' + '\n');
        };

        chatSocket.onclose = function(e) {
            console.error('Chat socket closed unexpectedly');
        };

        document.querySelector('#chat-message-input').focus();
        document.querySelector('#chat-message-input').onkeyup = function(e) {
            if (e.keyCode === 13) {  // enter, return
                document.querySelector('#chat-message-submit').click();
            }
        };

        document.querySelector('#chat-message-submit').onclick = function(e) {
            const messageInputDom = document.querySelector('#chat-message-input');
            const message = messageInputDom.value;
            chatSocket.send(JSON.stringify({
                'message': message,
                'username': user_username,
            }));
            messageInputDom.value = '';
        };
    </script>
</body>
</html>
</code>```

答: This is normal behavior for the WebSockets protocol, after you connect to a WebSocket only new messages will show up, if the connection closes then the message history will disappear. You will need to implement some sort of function in order to retrieve old messages and send them on connect.</p>

Body:
I am using Django channels to create a chat app. When the chat page is refreshed, the past messages disappear. Also, when I reconnect to the channel, the old messages do not show up.

Everything else seems to work fine, messages can be sent and received by the other user, message data is being saved into the database for each specific channel. No error is thrown back.

managers.py

from django.db import models
from django.db.models import Count

class ThreadManager(models.Manager):
    def get_or_create_personal_thread(self, user1, user2):
        threads = self.get_queryset().filter(thread_type='personal')
        threads = threads.filter(users__in=[user1, user2]).distinct()
        threads = threads.annotate(u_count=Count('users')).filter(u_count=2)
        if threads.exists():
            return threads.first()
        else:
            thread = self.create(thread_type='personal')
            thread.users.add(user1)
            thread.users.add(user2)
            return thread

    def by_user(self, user):
        return self.get_queryset().filter(users__in=[user])

models.py

from django.db import models
from app_users.models import User
from app_chat.managers import ThreadManager

class TrackingModel(models.Model):
    created_on = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class Thread(TrackingModel):
    THREAD_TYPE = (
        ('personal', 'Personal'),
        ('group', 'Group')
    )

    name = models.CharField(max_length=50, null=True, blank=True)
    thread_type = models.CharField(
        max_length=15, choices=THREAD_TYPE, default='group')
    users = models.ManyToManyField(User)

    objects = ThreadManager()

    def __str__(self):
        if self.thread_type == 'personal' and self.users.count() == 2:
            return f'{self.users.first()} and {self.users.last()}'
        return f'{self.name}'

class Message(TrackingModel):
    thread = models.ForeignKey(Thread, on_delete=models.CASCADE)
    sender = models.ForeignKey(User, on_delete=models.CASCADE)
    text = models.TextField(blank=False, null=False)

    def __str__(self) -> str:
        return f'From <Thread - {self.thread}>'

consumers.py

import json
from channels.generic.websocket import AsyncWebsocketConsumer
from app_users.models import User
from app_chat.models import Thread, Message
from asgiref.sync import sync_to_async
from channels.db import database_sync_to_async

class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        me = self.scope['user']
        other_username = self.scope['url_route']['kwargs']['username']
        other_user = await sync_to_async(User.objects.get)(username=other_username)
        self.thread_obj = await sync_to_async(Thread.objects.get_or_create_personal_thread)(me, other_user)
        self.room_name = f'personal_thread_{self.thread_obj.id}'
        self.room_group_name = 'chat_%s' % self.room_name

        # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()
        print(f"Connected to server ==")

    async def disconnect(self, close_code):
        # Leave group
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket

    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        username = text_data_json['username']
        # Send message to room group
        await self.channel_layer.group_send(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message,
                'username': username,
            }
        )

        await self.store_message(message)

    # Receive message from room group
    async def chat_message(self, event):
        message = event['message']
        username = event['username']

        # Send message to WebSocket
        await self.send(text_data=json.dumps({
            'message': message,
            'username': username,
        }))
        # print(f'{username} : {message} Message recieved')

    @database_sync_to_async
    def store_message(self, message):
        Message.objects.create(
            thread=self.thread_obj,
            sender=self.scope['user'],
            text=message
        )

room.html

<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>Chat Room</title>

    <textarea id="chat-log" cols="100" rows="20"></textarea>

    <input id="chat-message-input" type="text" size="100">

    <input id="chat-message-submit" type="button" value="Send">
    {{ room_name|json_script:"room-name" }}
    {{ request.user.username|json_script:"user_username"}}


问:
Number of configurations in mlr3 hyperband tuning
How can I control the number of configurations being evaluated during hyperband tuning in mlr3? I noticed that when I tune 6 parameters in xgboost(), the code evaluates about 9 configurations. When I tune the same number of parameters in catboost(), the code starts with evaluating 729 configurations. I am using eta = 3 in both cases.</p>

答:
The number of sampled configurations in hyperband is defined by the lower and upper bound of the budget hyperparameter and eta. You can get a preview of the schedule and number of configurations:

mlr3hyperband::hyperband_schedule(r_min = 1, r_max = 81, eta = 3)

#>     bracket stage budget  n
#>  1:       4     0      1 81
#>  2:       4     1      3 27
#>  3:       4     2      9  9
#>  4:       4     3     27  3
#>  5:       4     4     81  1
#>  6:       3     0      3 34
#>  7:       3     1      9 11
#>  8:       3     2     27  3
#>  9:       3     3     81  1
#> 10:       2     0      9 15
#> 11:       2     1     27  5
#> 12:       2     2     81  1
#> 13:       1     0     27  8
#> 14:       1     1     81  2
#> 15:       0     0     81  5

mlr3hyperband::hyperband_n_configs(r_min = 1, r_max = 81, eta = 3)

#> 143
```

If you want to evaluate more configurations, increase the repetition parameter of hyperband. Hyperband will start again after evaluating the last bracket. Install the latest gh version for this devtools::install_github("mlr-org/mlr3hyperband").

Body:
The number of sampled configurations in hyperband is defined by the lower and upper bound of the budget hyperparameter and eta. You can get a preview of the schedule and number of configurations:

mlr3hyperband::hyperband_schedule(r_min = 1, r_max = 81, eta = 3)

#>     bracket stage budget  n
#>  1:       4     0      1 81
#>  2:       4     1      3 27
#>  3:       4     2      9  9
#>  4:       4     3     27  3
#>  5:       4     4     81  1
#>  6:       3     0      3 34
#>  7:       3     1      9 11
#>  8:       3     2     27  3
#>  9:       3     3     81  1
#> 10:       2     0      9 15
#> 11:       2     1     27  5
#> 12:       2     2     81  1
#> 13:       1     0     27  8
#> 14:       1     1     81  2
#> 15:       0     0     81  5

mlr3hyperband::hyperband_n_configs(r_min = 1, r_max = 81, eta = 3)

#> 143

If you want to evaluate more configurations, increase the repetition parameter of hyperband. Hyperband will start again after evaluating the last bracket. Install the latest gh version for this devtools::install_github("mlr-org/mlr3hyperband").


问:
Send Array of hashes to class to create a user from each
I have a array of hashes

```<code>pets = [
    {
    "firstName": "Brianna",
     "lastName": "Parson",
     "children": ["sam","Joe"],
     "buddys": {

    },

    {
     "firstName": "jeffery",
     "lastName": "thomas",

     }
     }
    ]
</code>```

How do you send a class an array of hashes?

答:
You can do it like this

```<code>users = [
  {
    "firstName": "Brianna",
    "lastName": "Parson",
    "job": "SOFTWARE ENGINEER",
    "totalAssetWorth": "2000.00",
    "totalDebt": "1500.00",
    "children": ["sam","Joe"],
    "pets": {
      "dog": "jeff",
      "bird": "zoe"
    }
  },
  {
    "firstName": "jeffery",
    "lastName": "thomas",
    "job": "Lawyer",
    "totalAssetWorth": "6000.00",
    "totalDebt": "1300.00",
    "children": [],
    "pets": {
      "cat": "gnocchi"
    }
  }
]
</code>```
```<code>class User
  def initialize(args)
    @first_name = args[:firstName].capitalize
    @last_name = args[:lastName].capitalize
    @job = args[:job].downcase
    @total_asset_worth = args[:totalAssetWorth].to_f
    @total_debt = args[:totalDebt]
    @children = args[:children]
    @pets = args[:pets]
  end

  def to_s
    "#{@first_name} is a #{@job} and has #{@children.count} children and #{@pets.count} pet"
  end
end
</code>```
```<code>puts users.map { |args| User.new(args) }

# Brianna is a software engineer and has 2 children and 2 pet
# Jeffery is a lawyer and has 0 children and 1 pet
</code>```

Some Ruby magic: when pass array to puts method, each element will be put on new line and to_s method will be applied

Body:
I have a array of hashes

pets = [
    {
    "firstName": "Brianna",
     "lastName": "Parson",
     "children": ["sam","Joe"],
     "buddys": {

    },

    {
     "firstName": "jeffery",
     "lastName": "thomas",

     }
     }
    ]

How do you send a class an array of hashes?

Body:
You can do it like this

users = [
  {
    "firstName": "Brianna",
    "lastName": "Parson",
    "job": "SOFTWARE ENGINEER",
    "totalAssetWorth": "2000.00",
    "totalDebt": "1500.00",
    "children": ["sam","Joe"],
    "pets": {
      "dog": "jeff",
      "bird": "zoe"
    }
  },
  {
    "firstName": "jeffery",
    "lastName": "thomas",
    "job": "Lawyer",
    "totalAssetWorth": "6000.00",
    "totalDebt": "1300.00",
    "children": [],
    "pets": {
      "cat": "gnocchi"
    }
  }
]

class User
  def initialize(args)
    @first_name = args[:firstName].capitalize
    @last_name = args[:lastName].capitalize
    @job = args[:job].downcase
    @total_asset_worth = args[:totalAssetWorth].to_f
    @total_debt = args[:totalDebt]
    @children = args[:children]
    @pets = args[:pets]
  end

  def to_s
    "#{@first_name} is a #{@job} and has #{@children.count} children and #{@pets.count} pet"
  end
end

puts users.map { |args| User.new(args) }

# Brianna is a software engineer and has 2 children and 2 pet
# Jeffery is a lawyer and has 0 children and 1 pet

Some Ruby magic: when pass array to puts method, each element will be put on new line and to_s method will be applied


问:
Direct connection to Internet without Proxy
Is it possible to make a Direct connection to the Internet without using a Proxy.

Consider a case that my Organization has a Proxy and I use the DIRECT option given in the Java Proxy class.

```<code>SocketAddress addr = new
InetSocketAddress("webcache.mydomain.com", 8080);
Proxy proxy = new Proxy(Proxy.Type.DIRECT, addr);
</code>```

If you go by the documentation it states
DIRECT which represents a direct connection, or absence of proxy.

Which is exactly the way it behaves. When I use this option, I dont have to give any Proxy details and I can access the content from the Internet.

I have three questions

As per my understanding if an Organization has a Proxy, all network
traffic should get routed through the Proxy. No one should be able
to access the Network directly ?

I also noted that if I remove the Proxy details from IE, I can not
access the Web :-( How can Java still do it ?

If in any Organization you can access both with the Proxy and
Directly, how does the firewall block certain sites ? How does the
firewall even work ?

Thanks in advance.

答: Not all Network traffic goes through a Proxy, if your Organization has a Proxy. You can still go ahead and establish a Direct connection to the Internet. Mostly the Organizations will block Direct connections and force you to use Proxies. Some times they might allow you to have a Restricted Direct connection, which allows certain URL's and denies other ones.</p>

Body:
Is it possible to make a Direct connection to the Internet without using a Proxy.

Consider a case that my Organization has a Proxy and I use the DIRECT option given in the Java Proxy class.

SocketAddress addr = new
InetSocketAddress("webcache.mydomain.com", 8080);
Proxy proxy = new Proxy(Proxy.Type.DIRECT, addr);

If you go by the documentation it states
DIRECT which represents a direct connection, or absence of proxy.

Which is exactly the way it behaves. When I use this option, I dont have to give any Proxy details and I can access the content from the Internet.

I have three questions

As per my understanding if an Organization has a Proxy, all network
traffic should get routed through the Proxy. No one should be able
to access the Network directly ?

I also noted that if I remove the Proxy details from IE, I can not
access the Web :-( How can Java still do it ?

If in any Organization you can access both with the Proxy and
Directly, how does the firewall block certain sites ? How does the
firewall even work ?

Thanks in advance.


问:
Array of constraints Julia
I am trying to get an array of constraints, but I keep getting different kinds of errors, and I don't know what I'm doing wrong.

data array is 77x9    (integer values)

foods is a column vector of size 77x1, a variable of array type

lower is a column vector of 9x1, an integer vector

I should have 9 constraints

Here is what I have,

```<code>model2 = Model()
@variable(model2, foods[i=1:77] >= 0)  # Quantity of food

 for i ∈ 1:9
 for j ∈ 1:77
 @constraint(model2, c2[i], sum(data[j][i]*foods[j])<=lower[i])
 end
 end
</code>```

答:
What you want to do is

```<code>@constraint(model2, data' * foods .<= lower)
</code>```

Explanation

Let's make a toy example:

```<code>julia> @variable(model2, foods[i=1:3] >= 0)
3-element Vector{VariableRef}:
 foods[1]
 foods[2]
 foods[3]

julia> data = collect(reshape(1:12, 3, 4))
3×4 Matrix{Int64}:
 1  4  7  10
 2  5  8  11
 3  6  9  12

julia> lower = rand(101:104, 4)
4-element Vector{Int64}:
 104
 102
 102
 102
</code>```

For such case you can use just matrix multiplication:

```<code>julia> data' * foods
4-element Vector{AffExpr}:
 foods[1] + 2 foods[2] + 3 foods[3]
 4 foods[1] + 5 foods[2] + 6 foods[3]
 7 foods[1] + 8 foods[2] + 9 foods[3]
 10 foods[1] + 11 foods[2] + 12 foods[3]
</code>```

Now adding the right hand side constraint (note that we vectorized the <= operator:

```<code>julia> @constraint(model2, data' * foods .<= lower)
4-element Vector{ConstraintRef{Model, MathOptInterface.ConstraintIndex{MathOptInterface.ScalarAffineFunction{Float64}, MathOptInterface.LessThan{Float64}}, ScalarShape}}:
 foods[1] + 2 foods[2] + 3 foods[3] <= 104.0
 4 foods[1] + 5 foods[2] + 6 foods[3] <= 102.0
 7 foods[1] + 8 foods[2] + 9 foods[3] <= 102.0
 10 foods[1] + 11 foods[2] + 12 foods[3] <= 102.0
</code>```

Title: Array of constraints Julia

Body:
I am trying to get an array of constraints, but I keep getting different kinds of errors, and I don't know what I'm doing wrong.

data array is 77x9    (integer values)

foods is a column vector of size 77x1, a variable of array type

lower is a column vector of 9x1, an integer vector

I should have 9 constraints

Here is what I have,

model2 = Model()
@variable(model2, foods[i=1:77] >= 0)  # Quantity of food

 for i ∈ 1:9
 for j ∈ 1:77
 @constraint(model2, c2[i], sum(data[j][i]*foods[j])<=lower[i])
 end
 end

Body:
What you want to do is

@constraint(model2, data' * foods .<= lower)

Explanation

Let's make a toy example:

julia> @variable(model2, foods[i=1:3] >= 0)
3-element Vector{VariableRef}:
 foods[1]
 foods[2]
 foods[3]

julia> data = collect(reshape(1:12, 3, 4))
3×4 Matrix{Int64}:
 1  4  7  10
 2  5  8  11
 3  6  9  12

julia> lower = rand(101:104, 4)
4-element Vector{Int64}:
 104
 102
 102
 102

For such case you can use just matrix multiplication:

julia> data' * foods
4-element Vector{AffExpr}:
 foods[1] + 2 foods[2] + 3 foods[3]
 4 foods[1] + 5 foods[2] + 6 foods[3]
 7 foods[1] + 8 foods[2] + 9 foods[3]
 10 foods[1] + 11 foods[2] + 12 foods[3]

Now adding the right hand side constraint (note that we vectorized the <= operator:

julia> @constraint(model2, data' * foods .<= lower)
4-element Vector{ConstraintRef{Model, MathOptInterface.ConstraintIndex{MathOptInterface.ScalarAffineFunction{Float64}, MathOptInterface.LessThan{Float64}}, ScalarShape}}:
 foods[1] + 2 foods[2] + 3 foods[3] <= 104.0
 4 foods[1] + 5 foods[2] + 6 foods[3] <= 102.0
 7 foods[1] + 8 foods[2] + 9 foods[3] <= 102.0
 10 foods[1] + 11 foods[2] + 12 foods[3] <= 102.0


问:
Check equality of 2 variables in Github Action
If a tag is started with v pushed to the branch, a release will be make. Here is the issue: people may forgot pump up the version before release. Therefore check equality between tagged version and the version in the code is needed

The version in the code can fetch by poetry version -s and then a letter v is needed to add to the front of the version string (please see below)

VERSION_CODE = "v""$(poetry version -s)"

The version from the git tag can be access as below

VERSION_TAG = $(git describe --exact-match --tags $(git log -n1 --pretty='%h'))

Question: How can I check the equality of VERSION_CODE and VERSION_TAG so that the pipeline will make a release if the value of them are alined?

The code I have for now is shown below. There is an error message for step if: VERSION_CODE != VERSION_TAG that there is an unrecognised named-value: 'VERSION_CODE'. Located at position 1 within expression: VERSION_CODE

```<code>name: Release By Tag

on:
  push:
    tags:
      - "v*" # Push events to matching v*, i.e. v1.0, v20.15.10

jobs:
  version-check:
    name: check version
    runs-on: ubuntu-latest
    steps:

       ... set up environment, ex install poetry

       - name: try to fail version check
         run: |
           VERSION_CODE = "v""$(poetry version -s)"
           VERSION_TAG = $(git describe --exact-match --tags $(git log -n1 --pretty='%h')
         if: VERSION_CODE != VERSION_TAG
         run: exit 1

       - name: version is correct
         run: echo "version tag is alined"

       ... make a release
</code>```

答:
You can only pass variables to next step - if checking happens before step is executed, so you cannot access it as you posted. Also exit 1 is not the right pattern, you rather need to generate variables, pass them around and them use them in next steps.

One solution will be:

```<code>name: Release By Tag

on:
  push:
    tags:
      - "v*" # Push events to matching v*, i.e. v1.0, v20.15.10

jobs:
  version-check:
    name: check version
    runs-on: ubuntu-latest
    steps:

       ... set up environment, ex install poetry

       - name: try to fail version check
         id: version_info
         run: |
           VERSION_CODE="v""$(poetry version -s)"
           VERSION_TAG=$(git describe --exact-match --tags $(git log -n1 --pretty='%h')
           echo "::set-output name=VERSION_CODE::$VERSION_CODE"
           echo "::set-output name=VERSION_TAG::$VERSION_TAG"

       - name: version is correct
         if: ${{ steps.version_info.outputs.VERSION_CODE == steps.version_info.outputs.VERSION_TAG }}
         run: echo "version tag is alined"

       ... make a release
</code>```

You can also check if those values are matching in your first step and pass just boolean to the next step - depending on your needs.

Body:
If a tag is started with v pushed to the branch, a release will be make. Here is the issue: people may forgot pump up the version before release. Therefore check equality between tagged version and the version in the code is needed

The version in the code can fetch by poetry version -s and then a letter v is needed to add to the front of the version string (please see below)

VERSION_CODE = "v""$(poetry version -s)"

The version from the git tag can be access as below

VERSION_TAG = $(git describe --exact-match --tags $(git log -n1 --pretty='%h'))

Question: How can I check the equality of VERSION_CODE and VERSION_TAG so that the pipeline will make a release if the value of them are alined?

The code I have for now is shown below. There is an error message for step if: VERSION_CODE != VERSION_TAG that there is an unrecognised named-value: 'VERSION_CODE'. Located at position 1 within expression: VERSION_CODE

name: Release By Tag

on:
  push:
    tags:
      - "v*" # Push events to matching v*, i.e. v1.0, v20.15.10

jobs:
  version-check:
    name: check version
    runs-on: ubuntu-latest
    steps:

       ... set up environment, ex install poetry

       - name: try to fail version check
         run: |
           VERSION_CODE = "v""$(poetry version -s)"
           VERSION_TAG = $(git describe --exact-match --tags $(git log -n1 --pretty='%h')
         if: VERSION_CODE != VERSION_TAG
         run: exit 1

       - name: version is correct
         run: echo "version tag is alined"

       ... make a release

Body:
You can only pass variables to next step - if checking happens before step is executed, so you cannot access it as you posted. Also exit 1 is not the right pattern, you rather need to generate variables, pass them around and them use them in next steps.

One solution will be:

name: Release By Tag

on:
  push:
    tags:
      - "v*" # Push events to matching v*, i.e. v1.0, v20.15.10

jobs:
  version-check:
    name: check version
    runs-on: ubuntu-latest
    steps:

       ... set up environment, ex install poetry

       - name: try to fail version check
         id: version_info
         run: |
           VERSION_CODE="v""$(poetry version -s)"
           VERSION_TAG=$(git describe --exact-match --tags $(git log -n1 --pretty='%h')
           echo "::set-output name=VERSION_CODE::$VERSION_CODE"
           echo "::set-output name=VERSION_TAG::$VERSION_TAG"

       - name: version is correct
         if: ${{ steps.version_info.outputs.VERSION_CODE == steps.version_info.outputs.VERSION_TAG }}
         run: echo "version tag is alined"

       ... make a release

You can also check if those values are matching in your first step and pass just boolean to the next step - depending on your needs.


问:
How to put a spy to a single function using SinonJS?
I have this:

```<code>import * as sinon from 'sinon';
import {someFunc, someOtherFunc} from 'someModule';

describe("Something", () => {

  let sandbox: sinon.SinonSandbox;

  beforeEach('setup sandbox', function() {
    sandbox = sinon.createSandbox();
  });

  afterEach('restore sandbox', function() {
    sandbox.restore();
  });

  it("SomeTest", async () => {

    const spy = sanbox.spy(someFunc);
    someOtherFunc(1);
    console.log(spy.callCount) // prints 0

  })

</code>```

someFunc() is just a simple function, it is exported like:

```<code>export function someFunc(...)
</code>```

It is called by someOtherFunc(). Yet, the spy never gets called. The number of calls is 0.

Is it not possible to use Sinon this way? This works fine with Jest.

I think it's not working because sinon doesn't replace the function with the spy.

I also tried to put a spy to the module itself:

```<code>import * as lib from 'someModule'
...

 it("SomeTest", async () => {

    const spy = sanbox.spy(lib);
    lib.someOtherFunc(1);
    console.log(spy.someFunc.callCount) // prints 0

  })
</code>```

But this produces the same results. 0 calls.

答:
Just to clarify:

In order to be able to use Sinon spies, you need to export your module functionality in a certain way. Basically, use classes or objects.

Works:

```<code>export default {
func() {},
func2() {}
}

export const someLib {
func() {},
func2() {}
}

module.exports = {
func() {}
}

class Ping {
func() {}
}

export default Ping();
</code>```

or something similar.

What doesn't work:

```<code>export function func() {}
export function func2  {}

export const foo = () => {}
</code>```

and so on..

Body:
I have this:

import * as sinon from 'sinon';
import {someFunc, someOtherFunc} from 'someModule';

describe("Something", () => {

  let sandbox: sinon.SinonSandbox;

  beforeEach('setup sandbox', function() {
    sandbox = sinon.createSandbox();
  });

  afterEach('restore sandbox', function() {
    sandbox.restore();
  });

  it("SomeTest", async () => {

    const spy = sanbox.spy(someFunc);
    someOtherFunc(1);
    console.log(spy.callCount) // prints 0

  })

someFunc() is just a simple function, it is exported like:

export function someFunc(...)

It is called by someOtherFunc(). Yet, the spy never gets called. The number of calls is 0.

Is it not possible to use Sinon this way? This works fine with Jest.

I think it's not working because sinon doesn't replace the function with the spy.

I also tried to put a spy to the module itself:

import * as lib from 'someModule'
...

 it("SomeTest", async () => {

    const spy = sanbox.spy(lib);
    lib.someOtherFunc(1);
    console.log(spy.someFunc.callCount) // prints 0

  })

But this produces the same results. 0 calls.

Body:
Just to clarify:

In order to be able to use Sinon spies, you need to export your module functionality in a certain way. Basically, use classes or objects.

Works:

export default {
func() {},
func2() {}
}

export const someLib {
func() {},
func2() {}
}

module.exports = {
func() {}
}

class Ping {
func() {}
}

export default Ping();

or something similar.

What doesn't work:

export function func() {}
export function func2  {}

export const foo = () => {}

and so on..


问:
Avoid cast in generic factories
Suppose I have a class structure looking like this:

public abstract class Interval<I extends Interval<?>> {
    public static final IntervalFactory<? extends Interval<?>> factory = null;

    // some variables and methods
}

public class Week extends Interval<Week> {
    public static final IntervalFactory<Week> factory = new WeekFactory();

    // some variables and methods
}

public interface IntervalFactory {
    I containing(LocalDate date);
    List containing(LocalDate startDate, LocalDate endDate);
}

public class WeekFactory implements IntervalFactory<Week> {
    @Override
    public Week containing(LocalDate date) {
        // implementation
    }

    @Override
    public List<Week> containing(LocalDate startDate, LocalDate endDate) {
        // implementation
    }
}
```
<p>Now I have a class that uses those intervals and factories:</p>
```public class SomeClass<I extends Interval<?>> {
    private final IntervalFactory intervalFactory;

    public DistributorForSlowQuantifier() {
        this.intervalFactory = (IntervalFactory) I.factory;
    }

    public Map distribute(double value) {
        // implementation
    }
}
```

Is this the right way of approaching the problem if a class needs to create instances from a type variable?

Is there a way around the cast in the SomeClass constructor?

The obvious things don't work - having a wildcard as the type parameter of intervalFactory in SomeClass loses all the type information, the factories are static, so I cannot use I as a type parameter, and if I don't mark them as static, I need an instance of I to access the factory...

The cast is absolutely safe, as long as Interval implementations choose the "corresponding" factory, but it still feels... wrong.

答:
The cast in the SomeClass constructor doesn't even work.  It'll always use Interval.factory, whether or not that corresponds to the kind of factory you want.  I.factory does not do what you think.

By far the most common and sensical approach: to pass in the appropriate factory to the constructor.  You can add some syntactic sugar around this with static imports  and static factory methods to make it look like e.g. new DistributorForSlowQuantifier(days()) or the like.  There are other, much more convoluted and messy workarounds, but all things considered, they're worse.

Title: Avoid cast in generic factories

Body:
Suppose I have a class structure looking like this:

public abstract class Interval<I extends Interval<?>> {
    public static final IntervalFactory<? extends Interval<?>> factory = null;

    // some variables and methods
}

public class Week extends Interval<Week> {
    public static final IntervalFactory<Week> factory = new WeekFactory();

    // some variables and methods
}

public interface IntervalFactory {
    I containing(LocalDate date);
    List containing(LocalDate startDate, LocalDate endDate);
}

public class WeekFactory implements IntervalFactory<Week> {
    @Override
    public Week containing(LocalDate date) {
        // implementation
    }

    @Override
    public List<Week> containing(LocalDate startDate, LocalDate endDate) {
        // implementation
    }
}

Now I have a class that uses those intervals and factories:

public class SomeClass<I extends Interval<?>> {
    private final IntervalFactory intervalFactory;

    public DistributorForSlowQuantifier() {
        this.intervalFactory = (IntervalFactory) I.factory;
    }

    public Map distribute(double value) {
        // implementation
    }
}

Is this the right way of approaching the problem if a class needs to create instances from a type variable?

Is there a way around the cast in the SomeClass constructor?

The obvious things don't work - having a wildcard as the type parameter of intervalFactory in SomeClass loses all the type information, the factories are static, so I cannot use I as a type parameter, and if I don't mark them as static, I need an instance of I to access the factory...

The cast is absolutely safe, as long as Interval implementations choose the "corresponding" factory, but it still feels... wrong.


问:
How do I add characters in dates to make them look normal without affecting the rest of the line?
I have a file with tons of lines using a semicolon (;) as a delimiter. I have about 5 fields and need to change the format of only the first 2 fields without affecting the remainder of each line

20211119000751;20211119000759;IDNumber;Code;THings;SomeStuff

I want the end result to look like

2021-11-19 00:07:51;2021-11-19 00:07:59;IDNumber;Code;THings;SomeStuff

I have tried the solution How Do I add Multiple characters using SED? (My first Poorly Made question) and change date format from DD/MM/YYYY to YYYY-MM-DD with sed doesn't make sense to me.

```<code>sed -e 's/\(....\)\(..\)\(..\)\(..\)\(..\)\(..\);\(.*\)/\1-\2-\3 \4:\5:\6;\7/' \
    -e 's/\(.*\);\(....\)\(..\)\(..\)\(..\)\(..\)\(..\)/\1;\2-\3-\4 \5:\6:\7/' \
    < input > output
</code>```

This solution makes sense, but affects the rest of the line.

答:
Crappy but working solution (each line add a character at a given position
/./ select any char
the n number at the end is the number of repetition of the selected pattern, so /4 repeat /./ 4 times
& is the selected motif, plus a character, sor for example :
`s/./&-/4' take any first 4 character, and replace them by & ("Re-add" the pattern itself) plus a character.
Everything of that piped into another sed.

I usually use python for date formatting, plus the easy csv parsing, if it's a possible solution for you.

```<code>sed 's/./&-/4' < input.csv | \
sed 's/./&-/7' | \
sed 's/./&\ /10' | \
sed 's/./&:/13' | \
sed 's/./&:/16' | \
sed 's/./&-/24' | \
sed 's/./&-/27' | \
sed 's/./&\ /30' | \
sed 's/./&\:/33' | \
sed 's/./&\:/36' >> output.csv
</code>```

Body:
I have a file with tons of lines using a semicolon (;) as a delimiter. I have about 5 fields and need to change the format of only the first 2 fields without affecting the remainder of each line

20211119000751;20211119000759;IDNumber;Code;THings;SomeStuff

I want the end result to look like

2021-11-19 00:07:51;2021-11-19 00:07:59;IDNumber;Code;THings;SomeStuff

I have tried the solution How Do I add Multiple characters using SED? (My first Poorly Made question) and change date format from DD/MM/YYYY to YYYY-MM-DD with sed doesn't make sense to me.

sed -e 's/\(....\)\(..\)\(..\)\(..\)\(..\)\(..\);\(.*\)/\1-\2-\3 \4:\5:\6;\7/' \
    -e 's/\(.*\);\(....\)\(..\)\(..\)\(..\)\(..\)\(..\)/\1;\2-\3-\4 \5:\6:\7/' \
    < input > output

This solution makes sense, but affects the rest of the line.

Body:
Crappy but working solution (each line add a character at a given position
/./ select any char
the n number at the end is the number of repetition of the selected pattern, so /4 repeat /./ 4 times
& is the selected motif, plus a character, sor for example :
`s/./&-/4' take any first 4 character, and replace them by & ("Re-add" the pattern itself) plus a character.
Everything of that piped into another sed.

I usually use python for date formatting, plus the easy csv parsing, if it's a possible solution for you.

sed 's/./&-/4' < input.csv | \
sed 's/./&-/7' | \
sed 's/./&\ /10' | \
sed 's/./&:/13' | \
sed 's/./&:/16' | \
sed 's/./&-/24' | \
sed 's/./&-/27' | \
sed 's/./&\ /30' | \
sed 's/./&\:/33' | \
sed 's/./&\:/36' >> output.csv


问:
How to Recursively find secondary profiles and merge into primary one
I have a sample array, in which I would like to find the secondary ones and recursively check the secondary one until all secondary profiles gets unset from PHP array.
Here is the example array.

```<code>$testarray= array(
    array(
        array(
            'id' => 'ccdbh-743748',
            'name' => 'test',
            'email' => 'testemail@test.com',
            'newsletter' => 'abc,def,ghi',
            'created_at' => '1546753453',
            'profile_type' => 'primary'
        ),
        array(
            'id' => 'uisvuiacsiodciosd',
            'name' => 'test',
            'email' => 'testemail@test.com',
            'newsletter' => 'def',
            'created_at' => '1546753453',
            'profile_type' => 'secondary'
        ),
        array(
            'id' => 'sdcisodjcosjdocij',
            'name' => 'test',
            'email' => 'testemail@test.com',
            'newsletter' => 'ghi',
            'created_at' => '1546753453',
            'profile_type' => 'secondary'
        )
    ),
    array(
        array(
            'id' => 'sdcisodjcosjdocij',
            'name' => 'test',
            'email' => 'testemail@test.com',
            'newsletter' => 'abc',
            'created_at' => '1546753453',
            'profile_type' => 'secondary'
        ),
        array(
            'id' => 'ccdbh-743748',
            'name' => 'test',
            'email' => 'testemail@test.com',
            'newsletter' => 'abc,def',
            'created_at' => '1546753453',
            'profile_type' => 'primary'
        )
    ),
    array(
        array(
            'id' => 'sdcisodjcosjdocij',
            'name' => 'test',
            'email' => 'testemail@test.com',
            'newsletter' => 'abc',
            'created_at' => '1546753453',
            'profile_type' => 'secondary'
        ),
        array(
            'id' => 'sdcisodjcoscisudhiu',
            'name' => 'test',
            'email' => 'testemail@test.com',
            'newsletter' => 'abc,def',
            'created_at' => '1515217453',
            'profile_type' => 'primary'
        )
    )
);
</code>```

What I have tried so far.

```<code>function duplicate_profiles_merger ($profiles_array) {
    $innderdata = array();
    foreach ($profiles_array as $key => $val) {
        if (is_array($val) && in_array('secondary', $val)) {
            unset($val[$key]);
            // echo 'recursion';
            duplicate_profiles_merger($profiles_array);
        } else {
            // $innderdata = $val;
//POST Request API code goes here. Like curl request.
//data '{"primary":{"email":"cool.person@company.com"}, "secondary":{"email":"cperson@gmail.com"}}'
            echo 'done';
        }

        return $innderdata = $val;

    }
}
</code>```

But this gets me in an infinite state.
Below is the scenario that I want to achieve.

Here is the data that I need to pass through the API post request.
data '{"primary":{"email":"cool.person@company.com"}, "secondary":{"email":"cperson@gmail.com"}}'

Now I need the primary email and the secondary email for profile merge.
But there is more than one secondary profile that exists in the array, so for that, I need some kind of recursive functionality.

Thanks

答:
This answer sums up the comment section:

You call your recursion method with the same exact array you started with. But PHP is passing arguments as value as default, meaning you only modify the $var element, but not the $profiles_array, because of this you are creating an infinite loop.

Plus: There is no need for recursion here because there is no "child-structure" that would profit from real recursion here. A simple loop should do the trick.

```<code>function duplicate_profiles_merger ($profiles_array) {
    $innderdata = array();
    foreach ($profiles_array as $key => $val) {
        if (is_array($val) && $val['profile_type'] == 'primary') {
            array_push($innerdata, $val);
        }
    }

    return $innerdata;
}
</code>```

This should be all there is to it. You can also modify the existing array, eg. deleting all secondary profiles. Then you have to pass the array as reference, not value: https://www.php.net/manual/en/language.references.pass.php

Body:
I have a sample array, in which I would like to find the secondary ones and recursively check the secondary one until all secondary profiles gets unset from PHP array.
Here is the example array.

$testarray= array(
    array(
        array(
            'id' => 'ccdbh-743748',
            'name' => 'test',
            'email' => 'testemail@test.com',
            'newsletter' => 'abc,def,ghi',
            'created_at' => '1546753453',
            'profile_type' => 'primary'
        ),
        array(
            'id' => 'uisvuiacsiodciosd',
            'name' => 'test',
            'email' => 'testemail@test.com',
            'newsletter' => 'def',
            'created_at' => '1546753453',
            'profile_type' => 'secondary'
        ),
        array(
            'id' => 'sdcisodjcosjdocij',
            'name' => 'test',
            'email' => 'testemail@test.com',
            'newsletter' => 'ghi',
            'created_at' => '1546753453',
            'profile_type' => 'secondary'
        )
    ),
    array(
        array(
            'id' => 'sdcisodjcosjdocij',
            'name' => 'test',
            'email' => 'testemail@test.com',
            'newsletter' => 'abc',
            'created_at' => '1546753453',
            'profile_type' => 'secondary'
        ),
        array(
            'id' => 'ccdbh-743748',
            'name' => 'test',
            'email' => 'testemail@test.com',
            'newsletter' => 'abc,def',
            'created_at' => '1546753453',
            'profile_type' => 'primary'
        )
    ),
    array(
        array(
            'id' => 'sdcisodjcosjdocij',
            'name' => 'test',
            'email' => 'testemail@test.com',
            'newsletter' => 'abc',
            'created_at' => '1546753453',
            'profile_type' => 'secondary'
        ),
        array(
            'id' => 'sdcisodjcoscisudhiu',
            'name' => 'test',
            'email' => 'testemail@test.com',
            'newsletter' => 'abc,def',
            'created_at' => '1515217453',
            'profile_type' => 'primary'
        )
    )
);

What I have tried so far.

function duplicate_profiles_merger ($profiles_array) {
    $innderdata = array();
    foreach ($profiles_array as $key => $val) {
        if (is_array($val) && in_array('secondary', $val)) {
            unset($val[$key]);
            // echo 'recursion';
            duplicate_profiles_merger($profiles_array);
        } else {
            // $innderdata = $val;
//POST Request API code goes here. Like curl request.
//data '{"primary":{"email":"cool.person@company.com"}, "secondary":{"email":"cperson@gmail.com"}}'
            echo 'done';
        }

        return $innderdata = $val;

    }
}

But this gets me in an infinite state.
Below is the scenario that I want to achieve.

Here is the data that I need to pass through the API post request.
data '{"primary":{"email":"cool.person@company.com"}, "secondary":{"email":"cperson@gmail.com"}}'

Now I need the primary email and the secondary email for profile merge.
But there is more than one secondary profile that exists in the array, so for that, I need some kind of recursive functionality.

Thanks

Body:
This answer sums up the comment section:

You call your recursion method with the same exact array you started with. But PHP is passing arguments as value as default, meaning you only modify the $var element, but not the $profiles_array, because of this you are creating an infinite loop.

Plus: There is no need for recursion here because there is no "child-structure" that would profit from real recursion here. A simple loop should do the trick.

function duplicate_profiles_merger ($profiles_array) {
    $innderdata = array();
    foreach ($profiles_array as $key => $val) {
        if (is_array($val) && $val['profile_type'] == 'primary') {
            array_push($innerdata, $val);
        }
    }

    return $innerdata;
}

This should be all there is to it. You can also modify the existing array, eg. deleting all secondary profiles. Then you have to pass the array as reference, not value: https://www.php.net/manual/en/language.references.pass.php


问:
SMS messages non ASCII characters encoding
I have a Nokia N900 phone, and when sending an SMS, the widget displays the number of characters left in the message (and the number of actual short messages needed to send the whole message).

I live in France, where I noticed the following odd thing when writing messages with non-ASCII characters:

some non-ASCII chars are encoded on one char/byte , e.g. "é", "è", "à", "ù"

the presence of some non-ASCII chars such as "ç", "ê", "ô" consumes a fixed amount of 90 char/bytes + 1 byte per character

the presence of a second "ç", "ê" etc. only consumes 1 additional byte.

So I'm wondering how the messages are encoded, because I can't see the above scheme matching the traditional encodings I know (iso-8859-1, UTF-8, UTF-16...).

答:
https://en.wikipedia.org/wiki/SMS#Message_size

Depend on the encoding, SMS can send 160/140/70 characters. If any of the non-ASCII chars are used, the entire message would have to be encoded in UTF-16, hence the "consumption" you experienced.


问:
Lit element - onlick event in slotted child element
I have the following

```<code>    <custom-component>
     <div slot="form">
    <form>
    bunch of input elements
  <span slot="inner">  <button type="submit" id="submitButton"></button> </span>
    <button type="Reset"></button>
    </form>
    </div>
    </custom-component>
</code>```

How do I listen to on click event the button type submit from the parent component custom-component?
For reasons that I'm not going to to into, making the whole slotted form a component is not an option.

In the custom component file, this is what I tried

```<code>    <slot name='form' >
    <slot  name='inner' @click=${this.handleSearch}> </slot>

    </slot>
</code>```

Body:
I have the following

    <custom-component>

    <form>
    bunch of input elements
    <button type="submit" id="submitButton"></button>
    <button type="Reset"></button>
    </form>

    </custom-component>

How do I listen to on click event the button type submit from the parent component custom-component?
For reasons that I'm not going to to into, making the whole slotted form a component is not an option.

In the custom component file, this is what I tried

    <slot name='form' >
    <slot  name='inner' @click=${this.handleSearch}> </slot>

    </slot>

Body:
It seems like you'll need to change a few things to make this work as intended.

First, the "inner" slot in your example isn't doing anything. You can't have a nested slot inside of light DOM rendered slot children. To test this out to see that this is true, you can try two things.

Remove the <slot name="inner"> element, and you'll see that the "Submit" button still renders just fine in HTML.

Second, the @click listener on the <slot name="inner"> never fires. Try moving it to the <slot name="form"> and you'll see that the callback fires as expected.

Another issue you'll run into is that the default browser Event being bubbled through the shadowRoot doesn't contain any information. If you console.log the data in the event callback, you'll see that all you get is {isTrusted: true} instead of the more useful event and element information.

Since you can't create the form within the web component, the other option is to just handle all of the logic with JavaScript in a <script> tag next to your <custom-component> in HTML. This makes sense since this is closer to the intended use of slotted children - to be able to add arbitrary HTML as children to your web components, but your web component isn't necessarily in charge of anything related to that HTML, it's just rendering it.

If you need to be in charge of the rendering, events, or logic related to the HTML children, they should be inside the web component, or else the logic needs to be handled outside of the web component.


问:
android - removing item from ListView on long click
I'm having some troubles while trying to remove an item from the list view on long click. Below is the code:

```<code>public class MListViewActivity extends ListActivity {

private ListView lv;
private String[] some_data = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    some_data = getResources().getStringArray(R.array.mdata);

    // Bind resources Array to ListAdapter
    ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(this,
            R.layout.list_item, R.id.label, some_data);
    this.setListAdapter(myAdapter);

    lv = getListView();
    lv.setDividerHeight(3);

    lv.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
                int arg2, long arg3) {

            // Can't manage to remove an item here

            return false;
        }
    });
}
</code>```

Any help is appreciated

答:
itemAdapter = new ArrayAdapter<String>(
        view.getContext(),
        androidx.appcompat.R.layout.support_simple_spinner_dropdown_item,
        itemViewModel.getItems().getValue().stream().map(TaskCard::getTitle).collect(Collectors.toList())
);
ListView listview = view.findViewById(R.id.item_listview);
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int i, long l) {
        itemAdapter.remove(itemAdapter.getItem(i));
        return true;
    }
});
```

Body:
I'm having some troubles while trying to remove an item from the list view on long click. Below is the code:

public class MListViewActivity extends ListActivity {

private ListView lv;
private String[] some_data = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    some_data = getResources().getStringArray(R.array.mdata);

    // Bind resources Array to ListAdapter
    ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(this,
            R.layout.list_item, R.id.label, some_data);
    this.setListAdapter(myAdapter);

    lv = getListView();
    lv.setDividerHeight(3);

    lv.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
                int arg2, long arg3) {

            // Can't manage to remove an item here

            return false;
        }
    });
}

Any help is appreciated