问:
How to detect the custom shape in the given binary image using OpenCV?
I am looking for a way to detect custom shape in the given binary image using OpenCV.

my custom shape is like below:

I am trying to find if the above shape(or approx. to it) exists in the given 512 by 512 binary image.

I tried different ways like using cv::matchTemplate()
but this is not working for variant with scaled and rotated shapes.

I need some solution to identify the these kind of shapes in a given binary images.

Thank in advance

some information on shape
:shapes is simple with three connected component with line separation.
These are shapes of cross section of tibia, fibula and talus bone at ankle joint.
some more images of shape

Edit:
512by512 Images having the the shape

512 by 512 image without the shape

答:
Here's my algorithm. The idea is to cluster contours (in the sample algorithm just by dilation/erosion) and for each contour to normalize the size and to test the shape similarity in different rotations. Then compare the image region with the template.

I am using this image as template:

 with this contour

and this object image (removed the white background because I assume to use external contours only.

The algorithm gives this result:

```<code>found target shape with similarity 72.5144% and angle: 180 degrees
5 of 26
found target shape with similarity 73.1325% and angle: 0 degrees
6 of 26
found target shape with similarity 71.7287% and angle: 270 degrees
7 of 26
8 of 26
found target shape with similarity 72.3608% and angle: 90 degrees
9 of 26
10 of 26
11 of 26
12 of 26
13 of 26
14 of 26
15 of 26
16 of 26
found target shape with similarity 62.7371% and angle: 60 degrees
17 of 26
found target shape with similarity 62.6041% and angle: 240 degrees
18 of 26
19 of 26
20 of 26
found target shape with similarity 62.8935% and angle: 150 degrees
21 of 26
found target shape with similarity 62.39% and angle: 330 degrees
22 of 26
23 of 26
24 of 26
25 of 26
</code>```

This is the code (with some dirty helpers for saving the images etc.):

```<code>int glob_counter = 0;
double contourMaskSimilarity(float angleDiff, float scale, cv::Point2f cont_center, std::vector<cv::Point> contour, cv::Mat img, cv::Point2f template_center, cv::Mat img_templ)
{
    cv::Mat rotationMat = cv::getRotationMatrix2D(cont_center, angleDiff, scale);
    cv::Mat rotationMatPersp = cv::Mat::eye(3, 3, CV_64FC1);
    for (int y = 0; y < rotationMat.rows; ++y)
        for (int x = 0; x < rotationMat.cols; ++x)
        {
            rotationMatPersp.at<double>(y, x) = rotationMat.at<double>(y, x);
        }

    //cv::Mat img_tmp = img_color.clone();
    cv::Mat img_tmp_mask = cv::Mat::zeros(img.size(), img.type());
    std::vector < std::vector<cv::Point> >contours_img;
    contours_img.push_back(contour);
    cv::drawContours(img_tmp_mask, contours_img, 0, cv::Scalar::all(255), -1);

    //cv::circle(img_tmp, cont_center, 3, cv::Scalar(255, 0, 255), 2); // drawing

    std::vector<cv::Point2f> points;
    std::vector<cv::Point2f> warpedPoints;
    points.push_back(cont_center);

    cv::perspectiveTransform(points, warpedPoints, rotationMatPersp);

    cv::Mat translation = cv::Mat::eye(3, 3, CV_64FC1);
    translation.at<double>(0, 2) = template_center.x - warpedPoints[0].x; // x
    translation.at<double>(1, 2) = template_center.y - warpedPoints[0].y; // x

    cv::Mat transformation = translation * rotationMatPersp; // transformation after each other => 1. rotation 2. translation

    cv::Mat imgBin = img.clone();
    imgBin = imgBin & img_tmp_mask;
    cv::Mat imgBinWarped;
    // warp the image to same size and rotation as the template, according to angle and center
    //cv::warpPerspective(imgBin, imgBinWarped, transformation, cv::Size(img.size().width * scale, img.size().height * scale));
    cv::warpPerspective(imgBin, imgBinWarped, transformation, img_templ.size());

    cv::Rect subImage = cv::Rect(0, 0, img_templ.cols, img_templ.rows);
    cv::Mat imgSub = imgBinWarped(subImage);

    cv::Mat imgMul = imgSub.mul(img_templ); // 255 everywhere where template and current image-region are non-zero. 0 everywhere else

    double sum1 = cv::countNonZero(imgMul);
    double sum2 = cv::countNonZero(img_templ);
    double sum3 = cv::countNonZero(imgSub);
    //std::cout << sum1 << " " << sum2 << " " << sum3 << std::endl;

    // confidence similar to intersection over union.
    // use a better shape-similarity here, like a chamfer matching or a mean-hausdorff-distance?
    double conf = sum1 * sum1 / (sum2 * sum3);
    //std::cout << conf * 100 << " %" << std::endl;

    // TODO: remove!
    if (conf > 0.5)
    {
        cv::imwrite("C:/data/StackOverflow/bone_shapes/out_sub_" + std::to_string(glob_counter) + "_" + std::to_string(conf) + ".png", imgSub);
        cv::imwrite("C:/data/StackOverflow/bone_shapes/out_mul_" + std::to_string(glob_counter) + "_" + std::to_string(conf) + ".png", imgMul);
        glob_counter++;
    }

    return conf;
}

int main()
{
    cv::Mat img_templ = cv::imread("C:/data/StackOverflow/bone_shapes/bone_shape_template.png", cv::IMREAD_GRAYSCALE);
    // binarize the img (I guess it was binarized already?)
    cv::Mat templ = img_templ > 0;

    cv::Mat img_shapes = cv::imread("C:/data/StackOverflow/bone_shapes/bones_set_blackBG.png", cv::IMREAD_GRAYSCALE);
    // binarize the image (it was some grayscale gradients at the object borders...)
    cv::Mat img = img_shapes > 200;

    // 1. close-operator to merge all the parts of the shapes to a single contour. For other shapes you might need some kind of clustering.
    cv::Mat img_closed = img.clone();
    int nDilations = 2;
    cv::dilate(img_closed, img_closed, cv::getStructuringElement(cv::MorphShapes::MORPH_RECT, cv::Size(3, 3), cv::Point(1, 1)), cv::Point(1, 1), nDilations);
    cv::erode(img_closed, img_closed, cv::getStructuringElement(cv::MorphShapes::MORPH_RECT, cv::Size(3, 3), cv::Point(1, 1)), cv::Point(1, 1), nDilations);

    cv::Mat template_closed = templ.clone();
    int nDilationsTemplate = 2;
    cv::dilate(template_closed, template_closed, cv::getStructuringElement(cv::MorphShapes::MORPH_RECT, cv::Size(3, 3), cv::Point(1, 1)), cv::Point(1, 1), nDilations);
    cv::erode(template_closed, template_closed, cv::getStructuringElement(cv::MorphShapes::MORPH_RECT, cv::Size(3, 3), cv::Point(1, 1)), cv::Point(1, 1), nDilations);

    // 2. find contours (only necessary once for the template:)

    std::vector<std::vector<cv::Point> > contour_template;
    cv::findContours(template_closed, contour_template, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);

    std::vector<std::vector<cv::Point> > contours_img;
    cv::findContours(img_closed, contours_img, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);

    // display the results for debugging/sanity checks only
    cv::Mat img_color, template_color;
    cv::cvtColor(img_shapes, img_color, cv::COLOR_GRAY2BGR);
    cv::cvtColor(img_templ, template_color, cv::COLOR_GRAY2BGR);

    for (int i = 0; i < contour_template.size(); ++i)
        cv::drawContours(template_color, contour_template, i, cv::Scalar(255, 0, 255), 4);
    cv::imshow("template color", template_color);

    for (int i = 0; i < contours_img.size(); ++i)
        cv::drawContours(img_color, contours_img, i, cv::Scalar(0, 0, 255), 2);
    cv::imshow("img color", img_color);
    //cv::waitKey(1);

    // make sure the template only has one contour!
    if (contour_template.size() != 1)
    {
        std::cout << "closed template doesnt consist of a single contour" << std::endl;
        throw("closed template doesnt consist of a single contour");
    }

    // 3. get size and orientation of the shapes:
    cv::RotatedRect template_orientation = cv::minAreaRect(contour_template[0]);
    cv::Point2f template_center;    float template_size = 0;
    //cv::minEnclosingCircle(contour_template[0], template_center, template_size);
    template_center = template_orientation.center;
    template_size = (template_orientation.size.width > template_orientation.size.height) ? template_orientation.size.width : template_orientation.size.height;

    // now check every contour in the target image:
    for (int i = 0; i < contours_img.size(); ++i)
    {
        std::cout << i << " of " << contours_img.size() << std::endl;
        std::vector<cv::Point> cont = contours_img[i];

        cv::RotatedRect cont_orientation = cv::minAreaRect(cont);
        cv::Point2f cont_center;    float cont_size = 0;

        cont_center = cont_orientation.center;
        cont_size = (cont_orientation.size.width > cont_orientation.size.height) ? cont_orientation.size.width : cont_orientation.size.height;
        // angle difference according to rotated rectangle bounding boxes
        float angleDiff = template_orientation.angle - cont_orientation.angle;
        // scale according to rotated rectangle bounding boxes
        float scale = template_size / cont_size;

        double bestSimilarity = 0.0;
        float bestAngle = 0.0;
        float stepDegree = 15; // make smaller if you need a finer rotation resolution.

        // check various angles:
        for (float j = 0; j < 360.0f; j+=stepDegree)
        {
            //float angle = angleDiff + j * stepDegree; // initial guess for rotation. Works if shape is really similar
            float angle = j;
            // similarity computation is slow for small contours. Maybe because of the warping?
            double similarity = contourMaskSimilarity(angle, scale, cont_center, contours_img[i], img, template_center, templ);
            if (similarity > bestSimilarity)
            {
                bestSimilarity = similarity;
                bestAngle = angle;
            }
        }
        glob_counter++;

        if (bestSimilarity > 0.5)
        {
            cv::drawContours(img_color, contours_img, i, cv::Scalar(0, 255, 0), 2);
            std::cout << "found target shape with similarity " << 100*bestSimilarity << "% and angle: " << bestAngle << " degrees"<< std::endl;
        }

        //cv::waitKey(0);

        //cv::waitKey(0);
        /*
        std::cout << rotationMat << std::endl;

        cv::Point2f offsetTemplateImage;
        offsetTemplateImage.x = -template_center.x;
        offsetTemplateImage.y = -template_center.y;
        cv::Rect subImage = cv::Rect(cont_center.x + offsetTemplateImage.x, cont_center.y + offsetTemplateImage.y, img_templ.cols, img_templ.rows);
        */
    }

    cv::imshow("template", img_templ);
    cv::imshow("template binary", templ);
    cv::imshow("template closed", template_closed);

    cv::imshow("shapes", img_shapes);
    cv::imshow("shapes binary", img);
    cv::imshow("shapes closed", img_closed);

    cv::imshow("result", img_color);

    cv::imwrite("C:/data/StackOverflow/bone_shapes/out_template_color.png", template_color);
    cv::imwrite("C:/data/StackOverflow/bone_shapes/out_result.png", img_color);

    cv::waitKey(0);
}
</code>```

Here are some samples for warped images and the multiplied binary with the template:

Body:
Here's my algorithm. The idea is to cluster contours (in the sample algorithm just by dilation/erosion) and for each contour to normalize the size and to test the shape similarity in different rotations. Then compare the image region with the template.

I am using this image as template:

 with this contour

and this object image (removed the white background because I assume to use external contours only.

The algorithm gives this result:

found target shape with similarity 72.5144% and angle: 180 degrees
5 of 26
found target shape with similarity 73.1325% and angle: 0 degrees
6 of 26
found target shape with similarity 71.7287% and angle: 270 degrees
7 of 26
8 of 26
found target shape with similarity 72.3608% and angle: 90 degrees
9 of 26
10 of 26
11 of 26
12 of 26
13 of 26
14 of 26
15 of 26
16 of 26
found target shape with similarity 62.7371% and angle: 60 degrees
17 of 26
found target shape with similarity 62.6041% and angle: 240 degrees
18 of 26
19 of 26
20 of 26
found target shape with similarity 62.8935% and angle: 150 degrees
21 of 26
found target shape with similarity 62.39% and angle: 330 degrees
22 of 26
23 of 26
24 of 26
25 of 26

This is the code (with some dirty helpers for saving the images etc.):

int glob_counter = 0;
double contourMaskSimilarity(float angleDiff, float scale, cv::Point2f cont_center, std::vector<cv::Point> contour, cv::Mat img, cv::Point2f template_center, cv::Mat img_templ)
{
    cv::Mat rotationMat = cv::getRotationMatrix2D(cont_center, angleDiff, scale);
    cv::Mat rotationMatPersp = cv::Mat::eye(3, 3, CV_64FC1);
    for (int y = 0; y < rotationMat.rows; ++y)
        for (int x = 0; x < rotationMat.cols; ++x)
        {
            rotationMatPersp.at<double>(y, x) = rotationMat.at<double>(y, x);
        }

    //cv::Mat img_tmp = img_color.clone();
    cv::Mat img_tmp_mask = cv::Mat::zeros(img.size(), img.type());
    std::vector < std::vector<cv::Point> >contours_img;
    contours_img.push_back(contour);
    cv::drawContours(img_tmp_mask, contours_img, 0, cv::Scalar::all(255), -1);

    //cv::circle(img_tmp, cont_center, 3, cv::Scalar(255, 0, 255), 2); // drawing

    std::vector<cv::Point2f> points;
    std::vector<cv::Point2f> warpedPoints;
    points.push_back(cont_center);

    cv::perspectiveTransform(points, warpedPoints, rotationMatPersp);

    cv::Mat translation = cv::Mat::eye(3, 3, CV_64FC1);
    translation.at<double>(0, 2) = template_center.x - warpedPoints[0].x; // x
    translation.at<double>(1, 2) = template_center.y - warpedPoints[0].y; // x

    cv::Mat transformation = translation * rotationMatPersp; // transformation after each other => 1. rotation 2. translation

    cv::Mat imgBin = img.clone();
    imgBin = imgBin & img_tmp_mask;
    cv::Mat imgBinWarped;
    // warp the image to same size and rotation as the template, according to angle and center
    //cv::warpPerspective(imgBin, imgBinWarped, transformation, cv::Size(img.size().width * scale, img.size().height * scale));
    cv::warpPerspective(imgBin, imgBinWarped, transformation, img_templ.size());

    cv::Rect subImage = cv::Rect(0, 0, img_templ.cols, img_templ.rows);
    cv::Mat imgSub = imgBinWarped(subImage);

    cv::Mat imgMul = imgSub.mul(img_templ); // 255 everywhere where template and current image-region are non-zero. 0 everywhere else

    double sum1 = cv::countNonZero(imgMul);
    double sum2 = cv::countNonZero(img_templ);
    double sum3 = cv::countNonZero(imgSub);
    //std::cout << sum1 << " " << sum2 << " " << sum3 << std::endl;

    // confidence similar to intersection over union.
    // use a better shape-similarity here, like a chamfer matching or a mean-hausdorff-distance?
    double conf = sum1 * sum1 / (sum2 * sum3);
    //std::cout << conf * 100 << " %" << std::endl;

    // TODO: remove!
    if (conf > 0.5)
    {
        cv::imwrite("C:/data/StackOverflow/bone_shapes/out_sub_" + std::to_string(glob_counter) + "_" + std::to_string(conf) + ".png", imgSub);
        cv::imwrite("C:/data/StackOverflow/bone_shapes/out_mul_" + std::to_string(glob_counter) + "_" + std::to_string(conf) + ".png", imgMul);
        glob_counter++;
    }

    return conf;
}

int main()
{
    cv::Mat img_templ = cv::imread("C:/data/StackOverflow/bone_shapes/bone_shape_template.png", cv::IMREAD_GRAYSCALE);
    // binarize the img (I guess it was binarized already?)
    cv::Mat templ = img_templ > 0;

    cv::Mat img_shapes = cv::imread("C:/data/StackOverflow/bone_shapes/bones_set_blackBG.png", cv::IMREAD_GRAYSCALE);
    // binarize the image (it was some grayscale gradients at the object borders...)
    cv::Mat img = img_shapes > 200;

    // 1. close-operator to merge all the parts of the shapes to a single contour. For other shapes you might need some kind of clustering.
    cv::Mat img_closed = img.clone();
    int nDilations = 2;
    cv::dilate(img_closed, img_closed, cv::getStructuringElement(cv::MorphShapes::MORPH_RECT, cv::Size(3, 3), cv::Point(1, 1)), cv::Point(1, 1), nDilations);
    cv::erode(img_closed, img_closed, cv::getStructuringElement(cv::MorphShapes::MORPH_RECT, cv::Size(3, 3), cv::Point(1, 1)), cv::Point(1, 1), nDilations);

    cv::Mat template_closed = templ.clone();
    int nDilationsTemplate = 2;
    cv::dilate(template_closed, template_closed, cv::getStructuringElement(cv::MorphShapes::MORPH_RECT, cv::Size(3, 3), cv::Point(1, 1)), cv::Point(1, 1), nDilations);
    cv::erode(template_closed, template_closed, cv::getStructuringElement(cv::MorphShapes::MORPH_RECT, cv::Size(3, 3), cv::Point(1, 1)), cv::Point(1, 1), nDilations);

    // 2. find contours (only necessary once for the template:)

    std::vector<std::vector<cv::Point> > contour_template;
    cv::findContours(template_closed, contour_template, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);

    std::vector<std::vector<cv::Point> > contours_img;
    cv::findContours(img_closed, contours_img, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);

    // display the results for debugging/sanity checks only
    cv::Mat img_color, template_color;
    cv::cvtColor(img_shapes, img_color, cv::COLOR_GRAY2BGR);
    cv::cvtColor(img_templ, template_color, cv::COLOR_GRAY2BGR);

    for (int i = 0; i < contour_template.size(); ++i)
        cv::drawContours(template_color, contour_template, i, cv::Scalar(255, 0, 255), 4);
    cv::imshow("template color", template_color);

    for (int i = 0; i < contours_img.size(); ++i)
        cv::drawContours(img_color, contours_img, i, cv::Scalar(0, 0, 255), 2);
    cv::imshow("img color", img_color);
    //cv::waitKey(1);

    // make sure the template only has one contour!
    if (contour_template.size() != 1)
    {
        std::cout << "closed template doesnt consist of a single contour" << std::endl;
        throw("closed template doesnt consist of a single contour");
    }

    // 3. get size and orientation of the shapes:
    cv::RotatedRect template_orientation = cv::minAreaRect(contour_template[0]);
    cv::Point2f template_center;    float template_size = 0;
    //cv::minEnclosingCircle(contour_template[0], template_center, template_size);
    template_center = template_orientation.center;
    template_size = (template_orientation.size.width > template_orientation.size.height) ? template_orientation.size.width : template_orientation.size.height;

    // now check every contour in the target image:
    for (int i = 0; i < contours_img.size(); ++i)
    {
        std::cout << i << " of " << contours_img.size() << std::endl;
        std::vector<cv::Point> cont = contours_img[i];

        cv::RotatedRect cont_orientation = cv::minAreaRect(cont);
        cv::Point2f cont_center;    float cont_size = 0;

        cont_center = cont_orientation.center;
        cont_size = (cont_orientation.size.width > cont_orientation.size.height) ? cont_orientation.size.width : cont_orientation.size.height;
        // angle difference according to rotated rectangle bounding boxes
        float angleDiff = template_orientation.angle - cont_orientation.angle;
        // scale according to rotated rectangle bounding boxes
        float scale = template_size / cont_size;

        double bestSimilarity = 0.0;
        float bestAngle = 0.0;
        float stepDegree = 15; // make smaller if you need a finer rotation resolution.

        // check various angles:
        for (float j = 0; j < 360.0f; j+=stepDegree)
        {
            //float angle = angleDiff + j * stepDegree; // initial guess for rotation. Works if shape is really similar
            float angle = j;
            // similarity computation is slow for small contours. Maybe because of the warping?
            double similarity = contourMaskSimilarity(angle, scale, cont_center, contours_img[i], img, template_center, templ);
            if (similarity > bestSimilarity)
            {
                bestSimilarity = similarity;
                bestAngle = angle;
            }
        }
        glob_counter++;

        if (bestSimilarity > 0.5)
        {
            cv::drawContours(img_color, contours_img, i, cv::Scalar(0, 255, 0), 2);
            std::cout << "found target shape with similarity " << 100*bestSimilarity << "% and angle: " << bestAngle << " degrees"<< std::endl;
        }

        //cv::waitKey(0);

        //cv::waitKey(0);
        /*
        std::cout << rotationMat << std::endl;

        cv::Point2f offsetTemplateImage;
        offsetTemplateImage.x = -template_center.x;
        offsetTemplateImage.y = -template_center.y;
        cv::Rect subImage = cv::Rect(cont_center.x + offsetTemplateImage.x, cont_center.y + offsetTemplateImage.y, img_templ.cols, img_templ.rows);
        */
    }

    cv::imshow("template", img_templ);
    cv::imshow("template binary", templ);
    cv::imshow("template closed", template_closed);

    cv::imshow("shapes", img_shapes);
    cv::imshow("shapes binary", img);
    cv::imshow("shapes closed", img_closed);

    cv::imshow("result", img_color);

    cv::imwrite("C:/data/StackOverflow/bone_shapes/out_template_color.png", template_color);
    cv::imwrite("C:/data/StackOverflow/bone_shapes/out_result.png", img_color);

    cv::waitKey(0);
}

Here are some samples for warped images and the multiplied binary with the template:


来源: stackexchange

问:
smooth animation of the size of a functional component during state change
As you can see, by clicking on the component underneath, we can change its size. I would like to make a transition between those sizes. Is it possible with CSSTransition ?</p>
```<code>export const Liste_planete2 = () => {
    const [height, setHeight] = useState<number>(30)

    const handleClick=()=>{
            setHeight(height+30)
    }
    return(
        <div style={{height:height}} onClick={handleClick}>
            Text
        </div>
    )
}
</code>```

答:
Try it:</p>
```<code>export const Liste_planete2 = () => {
    const [height, setHeight] = useState<number>(30)

    const handleClick=()=>{
            setHeight(height+30)
    }
    return(
        <div style={{height:height, transition: "all 0.5s"}} onClick={handleClick}>
            Text
        </div>
    )
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
As you can see, by clicking on the component underneath, we can change its size. I would like to make a transition between those sizes. Is it possible with CSSTransition ?

export const Liste_planete2 = () => {
    const [height, setHeight] = useState<number>(30)

    const handleClick=()=>{
            setHeight(height+30)
    }
    return(

            Text

    )
}

Body:
Try it:

export const Liste_planete2 = () => {
    const [height, setHeight] = useState<number>(30)

    const handleClick=()=>{
            setHeight(height+30)
    }
    return(
        <div style={{height:height, transition: "all 0.5s"}} onClick={handleClick}>
            Text
        </div>
    )
}


问:
windows 10- atom-live-server not starting
Whenever i click the start server button as shown in the image nothing happens and the server does not start
I have installed atom-live-server on my laptop, but the server is not starting. I am trying to start the server from atom. I have checked for any incompatible packages view in Toggle command palette but it shows every package is fine and compatible. Please help..
I am working with Windows 10 64 bit configuration.

答: I had a similar issue and here is what helped me: To use the package you’ll need to have a project folder added to the Project sidebar. From here go to Packages > atom-live-server > Start Server and a preview of your site will open up in your default browser. If you need to stop the server again go to Packages > atom-live-server > Stop Server. I opened a separate folder for the project and the file is now loading in the live server.</p>

ContentLicense: CC BY-SA 3.0


问:
VBO for tilemap (draw order and slanted aerial 2D)
I want to draw a tilemap in a (ANSI C, C99 cannot be used due to windows compatibility) game that uses GL for accelerated graphics, although the game is a top-down 2D perspective using textured quads.
The popular opinion for handling a timemap seems to use a GL vertex buffer object, which I am about to write. However, I realized I want some tiles to go a little beyond vertical bounds, faking a slanted aerial view. That will make whatever is directly above the block to be partially covered by the tile.
If I use a VBO here, I will need to draw the entire tilemap in one sitting. Meaning that any object I draw afterwards will be directly on top of the tilemap.

What would be the sanest approach to this problem? Should I draw the tilemap first, then the entities (players/enemies) and then the excess vertical space so they cover the entities, and finally the effects that display over both? (such as shots, explosions, etcetera). But this would give me the issue of shots not being covered by terrain, and if I change the order, terrain covering large explosions awkwardly.
Alternatively I can sort all visual objects and draw them in a top-down fashion, but that would mean I need to change textures often, as sorting by texture wouldn't help too much in this specific case.

As well, I want to be able to modify the colors of every individual vertex in the grid in a dynamic way, so that entities can cast colors into the map. From what I am understanding, the way to achieve this would be with a vertex shader. Is this correct?

EDIT: A last thing. If I draw a VBO like that tilemap that is larger than the screen,by translating,  does GL automatically cull out-of-view faces or do I need to reform the VBO every time I move the "camera"?

答:
A VBO is just a piece of abstract memory reserved in the graphics memory. You can place data in any layout and arrangement as you like. You can use a single VBO to store several independent meshes. gl{Vertex,Normal,TexCoord,Color,Attrib}Pointer functions are used to set the offset into memory, that means either process address space or offset into the bound VBO.

Furthermore once can easily draw only subsets of the bound data with either glDrawArrays and glDrawElements by choosing approriate first element or indices in the index buffer.

So, no, you don't have to draw entire VBOs.


问:
How to check if next element in a list is greater than the previous in Haskell?
(I am currently doing an online course on Haskell and this is an exercise. I am not looking for answers, but simply for some pointers on how to proceed!)

I have trouble wrapping my head around this. In imperative languages I would simply use a loop, but since Haskell doesn't really have those I am left scratching my head.

I need to write a function nextIsGreater :: [Int] -> [Int] that, given a list of numbers, produces a list with all elements of the input list such that the element is followed by a greater number in the input list (the next number is greater).

Here is what I've managed to come up with so far.

```<code>nextIsGreater :: [Int] -> [Int]

nextIsGreater xs = [x | x <- init xs, y <- tail xs, x < y]
</code>```

So far it works if I have only two numbers in the list. Say [0,5], it returns [0] as it is supposed to. If I have, say [0,5,6] then my code seems to check the 0 against both of the next numbers in the list and returns [0,0,5], when it should return [0,5]. How could I compare each adjacent number to eachother?

答:
Not a bad attempt, but

```<code>   [x | x <- init xs, y <- tail xs, x < y]
</code>```

corresponds to a nested loop: you choose x from init xs, and then for each of these choices you pick all possible y from tail xs.

To make the idea work as intended, you'd need to use {-# LANGUAGE ParallelListComp #-} or equivalently zip the sources:

```<code>nextIsGreater xs = [x | (x,y) <- zip (init xs) (tail xs), x<y]
</code>```

But there's a simpler way to obtain all choices of two consecutive elements, with tails:

```<code>nextIsGreater xs = [x | (x:y:_) <- tails xs, x<y]
</code>```

Body:
(I am currently doing an online course on Haskell and this is an exercise. I am not looking for answers, but simply for some pointers on how to proceed!)

I have trouble wrapping my head around this. In imperative languages I would simply use a loop, but since Haskell doesn't really have those I am left scratching my head.

I need to write a function nextIsGreater :: [Int] -> [Int] that, given a list of numbers, produces a list with all elements of the input list such that the element is followed by a greater number in the input list (the next number is greater).

Here is what I've managed to come up with so far.

nextIsGreater :: [Int] -> [Int]

nextIsGreater xs = [x | x <- init xs, y <- tail xs, x < y]

So far it works if I have only two numbers in the list. Say [0,5], it returns [0] as it is supposed to. If I have, say [0,5,6] then my code seems to check the 0 against both of the next numbers in the list and returns [0,0,5], when it should return [0,5]. How could I compare each adjacent number to eachother?

Body:
Not a bad attempt, but

   [x | x <- init xs, y <- tail xs, x < y]

corresponds to a nested loop: you choose x from init xs, and then for each of these choices you pick all possible y from tail xs.

To make the idea work as intended, you'd need to use {-# LANGUAGE ParallelListComp #-} or equivalently zip the sources:

nextIsGreater xs = [x | (x,y) <- zip (init xs) (tail xs), x<y]

But there's a simpler way to obtain all choices of two consecutive elements, with tails:

nextIsGreater xs = [x | (x:y:_) <- tails xs, x<y]


问:
how can I change src of 3 image with a button in reactjs?
how can I change src of 3 image with a button in reactjs?

it changes function for dark to light mode.

```<code>  const switchTheme = () => {
    const newTheme = theme === "light" ? "dark" : "light";
    setTheme(newTheme);
  };
</code>```
```<code><button onClick={() => { switchTheme();}} className="buttonMode">
</code>```

but after that, I should change the src of the image to a white one.

```<code><img id="logo" src={"/LOGO.svg"} alt="" />
</code>```

LOGO.SVG to LOGOBLACK.svg.

How can I handle that?

答:
You can use ternary operator, just like you did with the newTheme

```<code><img id="logo" src={theme === "light" ? "/Logo.svg" : "/LogoBlack.svg"}
</code>```

Body:
how can I change src of 3 image with a button in reactjs?

it changes function for dark to light mode.

  const switchTheme = () => {
    const newTheme = theme === "light" ? "dark" : "light";
    setTheme(newTheme);
  };

<button onClick={() => { switchTheme();}} className="buttonMode">

but after that, I should change the src of the image to a white one.

LOGO.SVG to LOGOBLACK.svg.

How can I handle that?

Body:
You can use ternary operator, just like you did with the newTheme

<img id="logo" src={theme === "light" ? "/Logo.svg" : "/LogoBlack.svg"}


问:
OpenJdK 8 - Can't compile package javafx.util does not exist
```<code>Linux Mint 20.3
   os.name = Linux
   os.arch = amd64
   os.version = 5.13.0-25-generic

 Java :
    openjdk version "1.8.0_322"
    OpenJDK Runtime Environment (build 1.8.0_322-b06)
    OpenJDK 64-Bit Server VM (build 25.322-b06, mixed mode)

Maven 3.8.3
</code>```

I build my java project by Maven.

When I try to compile my java project by OpenJdk 1.8.0_322:

```<code>  package com.myproject;

    import java.util.Collection;
    import java.util.List;
    import java.util.Map;

    import javafx.util.Pair; //  here error

    @SuppressWarnings("rawtypes")
    public interface SomeMyInterface {
      // some code here
      Map<Integer, List<Pair<Integer,Integer>>> findAllMgIdsAssociatedNsPairs();
    }
</code>```

I get error:

```<code>[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /SomeMyInterface.java:[10,19] package javafx.util does not exist
</code>```

P.S. If I use jdk1.8.0_202 from Oracle the project success compile!

P.P.S. The project must be compile by java 8. It's client requirements.

答:
tl;dr

Either:

Develop/deploy on a JDK that includes the OpenJFX libraries.

Add the OpenJFX libraries to your Java project.

Details

JavaFX has never been an official part of Java SE.

For a while Oracle included their JavaFX library along with their JDK. They later ceased bundling.

You need to add an implementation of JavaFX to your project. You’ll find such an implementation in OpenJFX. This open-source project is housed as a subproject on the OpenJDK project, co-led by Gluon and Oracle.

Use your dependency manager of choice, such as Apache Maven or Gradle, to add the OpenJFX library to your project. Below I put Maven repo links for OpenJFX 11 through 17, but those require Java 11+. I have not found any Maven repo links for JavaFX/OpenJFX for Java 8.

Alternatively, you can develop on, and deploy to, a JDK that bundles the OpenJFX libraries. At least two vendors offer an edition of their JDK product with such a bundle:

ZuluFX by Azul Systems

See this downloads list for Java 8 on macOS, Linux, & Windows. Notice the Java Package filter field at top of downloads list.

LibericaFX by BellSoft

On the Downloads page, choose the Full option for an edition bundling OpenJFX. Available for Java 8 on macOS, Linux, & Windows.

If at all possible, consider moving on from Java 8. I suggest moving to the later LTS versions of Java, 11 and 17, as well as the latest LTS version of OpenJFX, 17, which requires Java 11 or later. Both Java and JavaFX have evolved greatly in recent years. This evolution includes the jlink and jpackage tooling to package your JavaFX app as single "double-clickable" app that includes the minimal parts of a JDK/JVM needed to run on a specific platform.

Versions

For OpenJFX versions 11 through 17, Java 11 or later is required/recommended. See Release Notes.

Maven links for OpenJFX 11 through 18 can be found here, and on other Maven repositories.

Source code for OpenJFX versions 14 through 18 can be found on GitHub site for OpenJDK. Source code for older versions 2, 8, 9, and 10 can be found on the read-only Mercurial repository of OpenJDK.

Body:
Linux Mint 20.3
   os.name = Linux
   os.arch = amd64
   os.version = 5.13.0-25-generic

 Java :
    openjdk version "1.8.0_322"
    OpenJDK Runtime Environment (build 1.8.0_322-b06)
    OpenJDK 64-Bit Server VM (build 25.322-b06, mixed mode)

Maven 3.8.3

I build my java project by Maven.

When I try to compile my java project by OpenJdk 1.8.0_322:

  package com.myproject;

    import java.util.Collection;
    import java.util.List;
    import java.util.Map;

    import javafx.util.Pair; //  here error

    @SuppressWarnings("rawtypes")
    public interface SomeMyInterface {
      // some code here
      Map<Integer, List<Pair<Integer,Integer>>> findAllMgIdsAssociatedNsPairs();
    }

I get error:

[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /SomeMyInterface.java:[10,19] package javafx.util does not exist

P.S. If I use jdk1.8.0_202 from Oracle the project success compile!

P.P.S. The project must be compile by java 8. It's client requirements.


问:
Custom notification sounds not working if app is closed
I am trying to implement custom notification sounds. There are two different sounds, one for message and one for call, the sounds work when the app is running and I get a notification but phone's default sound will ring if the app is closed and removed from recent as well. I have used Firebase for notifications.</p>

答:
This is happening mostly as you were getting the notification payload in the push notification. Whenever we get the notification and data both in the fcm payload. Notification tag is always accessed using the system tray of the android system. So it will not consider your custom notification setting.

Try to get only the data in the fcm payload and not the notification.


问:
Is there an accepted "name" for an event that simply reports back a "message"
I have a "DataImporter" class [takes data from many sources and processes it] that I want to report back through an event when it "does something".
At the moment I have:
DataImporterStarted
DataImporterCompleted
DataImporterImportedData
DataImporterDeleted

But they all do the same thing...report back a simple string saying "Data Importer started at xx:xx" or "DataImporter Imported xxx Rows" etc.

Should I be keeping the events separate, or is there an accepted pattern/naming convention for this kind of "I'm doing something" event?
Thx

I was trying to avoid code like this:

```<code>var importer = new DataImporter();
importer.DataImporterStarted += new DataImporterStartedEventHandler(importer_DataImporterMessage);
importer.DataImported += new DataImportedEventHandler(importer_DataImporterMessage);
importer.DataImporterCompleted += new DataImporterCompletedEventHandler(importer_DataImporterMessage);
importer.RunDataImporter();
</code>```

答: You could use something like create a DataImporterProgress event with a Action property like "Updated" or "Deleted" (an enumeration) and a Message string in it's eventArgs property.

Body:
I have a "DataImporter" class [takes data from many sources and processes it] that I want to report back through an event when it "does something".
At the moment I have:
DataImporterStarted
DataImporterCompleted
DataImporterImportedData
DataImporterDeleted

But they all do the same thing...report back a simple string saying "Data Importer started at xx:xx" or "DataImporter Imported xxx Rows" etc.

Should I be keeping the events separate, or is there an accepted pattern/naming convention for this kind of "I'm doing something" event?
Thx

I was trying to avoid code like this:

var importer = new DataImporter();
importer.DataImporterStarted += new DataImporterStartedEventHandler(importer_DataImporterMessage);
importer.DataImported += new DataImportedEventHandler(importer_DataImporterMessage);
importer.DataImporterCompleted += new DataImporterCompletedEventHandler(importer_DataImporterMessage);
importer.RunDataImporter();


问:
Python Dictionary: Output dictionary within a list within a dictionary
I have a dictionary with a lot of keys. One of those keys has a list of dictionaries; i want to extract data from the ladder dictionary.

It looks like this:

```<code>Data = {
(...)
Users:[{'username':'X','email':'Y'},{'username':'W','email':'Z'}]
(...)
}
</code>```

And I want to create a list with all the emails, so that

```<code>print(listEmails)
>['Y','Z']
</code>```

How should I do this?

答:
```<code>print([user.get('email') for user in Data['Users']])
</code>```

That is assuming Users from your sample is actually str - 'Users'

Body:
I have a dictionary with a lot of keys. One of those keys has a list of dictionaries; i want to extract data from the ladder dictionary.

It looks like this:

Data = {
(...)
Users:[{'username':'X','email':'Y'},{'username':'W','email':'Z'}]
(...)
}

And I want to create a list with all the emails, so that

print(listEmails)
>['Y','Z']

How should I do this?

Body:
print([user.get('email') for user in Data['Users']])

That is assuming Users from your sample is actually str - 'Users'


问:
html images not loading unless full filepath is used
I originally transferred this project from windows to linux, and it was working completely fine on windows, but now images are not loading.

I have an image:

```<code><img src="/assets/s1.png" alt="dinosaur">
</code>```

And it is only loading on the webpage if I change the filepath to /home/user/Desktop/Project/assets/s1.png

The image file is in the folder assets and the assets folder and html file are both within the Project folder.

The weird thing is that when I change /home/user/Desktop/Project/assets/s1.png to /Desktop/Project/assets/s1.png it stops working. I would like to be able to only include the necessary path /assets/s1.png because I will need the path to stay the same if this project gets moved around between environments.

答:
Based on a comment on the question:

the address of the page is file:///home/user/Desktop/Project/file.tpl

That's the problem then.  The "root" of the "web server" (from the browser's perspective) is the root of the file system.  So this absolute path won't work:

```<code><img src="/assets/s1.png" alt="dinosaur">
</code>```

But this one will:

```<code><img src="/home/user/Desktop/Project/assets/s1.png" alt="dinosaur">
</code>```

However, that latter one clearly won't be helpful in a web-hosted environment.

You can instead use a relative path, for example:

```<code><img src="./assets/s1.png" alt="dinosaur">
</code>```

This should work in the example given, but we can't know if this will have further implications in a larger and more complex web application.  For example, if you're dynamically loading sections or templates from different folders, their "relative paths" may be different.  (That's one advantage of absolute paths, they're the same regardless of what page you're on.)

But more to the root cause of the problem... You really shouldn't be testing a web page from the file system.  The intent is to host it on a web server, so the testing should be hosted on a web server.

It makes little sense to make changes to the code in order to get it to work in an environment that will never be used, only to probably have to make more changes to get it to work in the actual target environment.  Keep the test environment and the target environment as similar as possible.

Body:
I originally transferred this project from windows to linux, and it was working completely fine on windows, but now images are not loading.

I have an image:

And it is only loading on the webpage if I change the filepath to /home/user/Desktop/Project/assets/s1.png

The image file is in the folder assets and the assets folder and html file are both within the Project folder.

The weird thing is that when I change /home/user/Desktop/Project/assets/s1.png to /Desktop/Project/assets/s1.png it stops working. I would like to be able to only include the necessary path /assets/s1.png because I will need the path to stay the same if this project gets moved around between environments.

Body:
Based on a comment on the question:

the address of the page is file:///home/user/Desktop/Project/file.tpl

That's the problem then.  The "root" of the "web server" (from the browser's perspective) is the root of the file system.  So this absolute path won't work:

<img src="/assets/s1.png" alt="dinosaur">

But this one will:

<img src="/home/user/Desktop/Project/assets/s1.png" alt="dinosaur">

However, that latter one clearly won't be helpful in a web-hosted environment.

You can instead use a relative path, for example:

<img src="./assets/s1.png" alt="dinosaur">

This should work in the example given, but we can't know if this will have further implications in a larger and more complex web application.  For example, if you're dynamically loading sections or templates from different folders, their "relative paths" may be different.  (That's one advantage of absolute paths, they're the same regardless of what page you're on.)

But more to the root cause of the problem... You really shouldn't be testing a web page from the file system.  The intent is to host it on a web server, so the testing should be hosted on a web server.

It makes little sense to make changes to the code in order to get it to work in an environment that will never be used, only to probably have to make more changes to get it to work in the actual target environment.  Keep the test environment and the target environment as similar as possible.


问:
How to Define 1D and 2D Arrays Accurately
I know what 1D (1 - Dimensional) and 2D (2 - Dimensional) arrays are, but I don't know how to describe them.

e.g. A 2D array is data in a table - Needs more detail

This link can help you if you do not know what 1D and 2D arrays are. I am not allowed to use the wording of these definitions, however.

答:
It would be better to say that a one dimension array is an array which holds a single set of data such as strings, numbers or objects.

A multi dimensional or a 2d array, an array contains another level of arrays inside.


问:
Check if a Postgres JSON array contains a string
I have a table to store information about my rabbits. It looks like this:

```<code>create table rabbits (rabbit_id bigserial primary key, info json not null);
insert into rabbits (info) values
  ('{"name":"Henry", "food":["lettuce","carrots"]}'),
  ('{"name":"Herald","food":["carrots","zucchini"]}'),
  ('{"name":"Helen", "food":["lettuce","cheese"]}');
</code>```

How should I find the rabbits who like carrots? I came up with this:

```<code>select info->>'name' from rabbits where exists (
  select 1 from json_array_elements(info->'food') as food
  where food::text = '"carrots"'
);
</code>```

I don't like that query. It's a mess.

As a full-time rabbit-keeper, I don't have time to change my database schema. I just want to properly feed my rabbits. Is there a more readable way to do that query?

答:
If the array is at the root of the jsonb column, i.e. column looks like:

food

["lettuce", "carrots"]

["carrots", "zucchini"]

just use the column name directly inside the brackets:

```<code>select * from rabbits where (food)::jsonb ? 'carrots';
</code>```

Body:
I have a table to store information about my rabbits. It looks like this:

create table rabbits (rabbit_id bigserial primary key, info json not null);
insert into rabbits (info) values
  ('{"name":"Henry", "food":["lettuce","carrots"]}'),
  ('{"name":"Herald","food":["carrots","zucchini"]}'),
  ('{"name":"Helen", "food":["lettuce","cheese"]}');

How should I find the rabbits who like carrots? I came up with this:

select info->>'name' from rabbits where exists (
  select 1 from json_array_elements(info->'food') as food
  where food::text = '"carrots"'
);

I don't like that query. It's a mess.

As a full-time rabbit-keeper, I don't have time to change my database schema. I just want to properly feed my rabbits. Is there a more readable way to do that query?

Body:
If the array is at the root of the jsonb column, i.e. column looks like:

food

["lettuce", "carrots"]

["carrots", "zucchini"]

just use the column name directly inside the brackets:

select * from rabbits where (food)::jsonb ? 'carrots';


问:
Hashing and salting a password field
I have been tossing around the question of how to store the passwords in my DB for some time now. This is my first time at making a secure application with a web login, so i wanted to set up some good practices.

First, i read up on hashing and salting. It seems that the idea is...

Get hashing algorithm

Get password from user

Add 'salt' to plain text password from user

hash the entire password (including salt)

Store the salt in the db so that you can retrieve it later (for verification of PSWD)

And that got me thinking... If a hacker knows your salt (because it is stored in the DB somewhere, maybe a column called this_is_not_the_salt_ur_looking_for or something equally ambiguous) they can re-generate the password dictionary and gain access.

Then i had an idea. What if you stored your salt inside the hashed password field. So follow steps 1-4 (randomly generating the salt), then in step 5, insert the salt in the password somewhere known by the password interpreting class or service:

xxxxxsaltvaluexxxxxxxxxxxxxxxx

where x is the hashed string values. Can anyone see any issues with this? is it just completely unnecessary?

Answer:

There is no reason why this couldnt be done. As Yahia states, other methods of securing a password include double (or n) hashing. On another note, BCrypt looks like a good method of stopping brute force attacks almost entirely, but I couldnt find a trusted library for C#

Thanks!

TTD

答: You're about to fall into a rabbit hole. Use bcrypt.</p>

Title: Hashing and salting a password field


问:
Python & HTTPX: How does httpx client's connection pooling work?
Consider this function that makes a simple GET request to an API endpoint:

import httpx

def check_status_without_session(url : str) -> int:
    response = httpx.get(url)
    return response.status_code
```
<p>Running this function will open a new TCP connection every time the function <code>check_status_without_session</code> is called. Now, this section of HTTPX documentation recommends using the <code>Client</code> API while making multiple requests to the same URL. The following function does that:</p>
<pre class="lang-py prettyprint-override"><code>import httpx

def check_status_with_session(url: str) -> int:
    with httpx.Client() as client:
        response = client.get(url)
        return response.status_code
</code>```

According to the docs using Client will ensure that:

... a Client instance uses HTTP connection pooling. This means that when you make several requests to the same host, the Client will reuse the underlying TCP connection, instead of recreating one for every single request.

My question is, in the second case, I have wrapped the Client context manager in a function. If I call check_status_with_session multiple times with the same URL, wouldn't that just create a new pool of connections each time the function is called? This implies it's not actually reusing the connections. As the function stack gets destroyed after the execution of the function, the Client object should be destroyed as well, right? Is there any advantage in doing it like this or is there a better way?

答:
Is there any advantage in doing it like this or is there a better way?

No, there is no advantage using httpx.Client in the way you've shown. In fact the httpx.<method> API, e.g. httpx.get, does exactly the same thing!

The "pool" is a feature of the transport manager held by Client, which is HTTPTransport by default. The transport is created at Client initialisation time and stored as the instance property self._transport.

Creating a new Client instance means a new HTTPTransport instance, and transport instances have their own TCP connection pool. By creating a new Client instance each time and using it only once, you get no benefit over using e.g. httpx.get directly.

And that might be OK! Connection pooling is an optimisation over creating a new TCP connection for each request. Your application may not need that optimisation, it may be performant enough already for your needs.

If you are making many requests to the same endpoint in a tight loop, iterating within the context of the loop may net you some throughput gains, e.g.

with httpx.Client(base_url="https://example.com") as client:
    results = [client.get(f"/api/resource/{idx}") for idx in range(100)]
```

For such I/O-heavy workloads you may do even better by executing results in parallel, e.g. using httpx.AsyncClient.

Body:
Consider this function that makes a simple GET request to an API endpoint:

import httpx

def check_status_without_session(url : str) -> int:
    response = httpx.get(url)
    return response.status_code

Running this function will open a new TCP connection every time the function check_status_without_session is called. Now, this section of HTTPX documentation recommends using the Client API while making multiple requests to the same URL. The following function does that:

import httpx

def check_status_with_session(url: str) -> int:
    with httpx.Client() as client:
        response = client.get(url)
        return response.status_code

According to the docs using Client will ensure that:

... a Client instance uses HTTP connection pooling. This means that when you make several requests to the same host, the Client will reuse the underlying TCP connection, instead of recreating one for every single request.

My question is, in the second case, I have wrapped the Client context manager in a function. If I call check_status_with_session multiple times with the same URL, wouldn't that just create a new pool of connections each time the function is called? This implies it's not actually reusing the connections. As the function stack gets destroyed after the execution of the function, the Client object should be destroyed as well, right? Is there any advantage in doing it like this or is there a better way?

Body:
Is there any advantage in doing it like this or is there a better way?

No, there is no advantage using httpx.Client in the way you've shown. In fact the httpx.<method> API, e.g. httpx.get, does exactly the same thing!

The "pool" is a feature of the transport manager held by Client, which is HTTPTransport by default. The transport is created at Client initialisation time and stored as the instance property self._transport.

Creating a new Client instance means a new HTTPTransport instance, and transport instances have their own TCP connection pool. By creating a new Client instance each time and using it only once, you get no benefit over using e.g. httpx.get directly.

And that might be OK! Connection pooling is an optimisation over creating a new TCP connection for each request. Your application may not need that optimisation, it may be performant enough already for your needs.

If you are making many requests to the same endpoint in a tight loop, iterating within the context of the loop may net you some throughput gains, e.g.

with httpx.Client(base_url="https://example.com") as client:
    results = [client.get(f"/api/resource/{idx}") for idx in range(100)]

For such I/O-heavy workloads you may do even better by executing results in parallel, e.g. using httpx.AsyncClient.


问:
Convert 16-digit datetime string to datetime with microseconds
I am trying to convert a 16-digit datetime string (with milliseconds) in SQL Server to an actual datetime along with the milliseconds. An example would be changing a record like this, 2022020804180454, to read a US DateTime of 02/08/2022 04:18:04.54.

How do I go about doing this? Google/Bing searches speak to having the date with a midnight timestamp

```<code>CONVERT(datetime, CAST('2022020804180454' AS CHAR(8)), 101)
</code>```

which is not what I am after.

Any help or being pointed in the right direction would be helpful.

答:
Inject the needed characters, with STUFF, and then convert:

SELECT CONVERT(datetime2(2),STUFF(STUFF(STUFF(STUFF(V.YourDateString,15,0,'.'),13,0,':'),11,0,':'),9,0,' '))
FROM (VALUES('2022020804180454'))V(YourDateString);
```

Body:
I am trying to convert a 16-digit datetime string (with milliseconds) in SQL Server to an actual datetime along with the milliseconds. An example would be changing a record like this, 2022020804180454, to read a US DateTime of 02/08/2022 04:18:04.54.

How do I go about doing this? Google/Bing searches speak to having the date with a midnight timestamp

CONVERT(datetime, CAST('2022020804180454' AS CHAR(8)), 101)

which is not what I am after.

Any help or being pointed in the right direction would be helpful.


问:
Creating a list from a text file
I have a text file called my_urls.txt that has 3 URLs:

```<code>example1.com
example2.com
example3.com
</code>```
```<code>with open("../test_data/my_urls.txt", "r") as urlFile:
    urls_list = urlFile.readline().split('\n')
    print(urls_list)

['example1.com', '']
</code>```

I wonder why urls_list is not giving me ['example1.com', 'example2.com', 'example3.com']

答:
Because you do readline() instead of read(). In your example you only read the first line of the file and then close it.

Try this

```<code>urls_list = urlFile.read().split('\n')
</code>```

It will read the whole file content at once.

Title: Creating a list from a text file

Body:
I have a text file called my_urls.txt that has 3 URLs:

example1.com
example2.com
example3.com

with open("../test_data/my_urls.txt", "r") as urlFile:
    urls_list = urlFile.readline().split('\n')
    print(urls_list)

['example1.com', '']

I wonder why urls_list is not giving me ['example1.com', 'example2.com', 'example3.com']

Body:
Because you do readline() instead of read(). In your example you only read the first line of the file and then close it.

Try this

urls_list = urlFile.read().split('\n')

It will read the whole file content at once.


问:
How do I split a custom dataset into spatially disjoint training and test datasets in Python?
My question is close to this thread but the difference is I want my training and test dataset to be spatially disjoint. So no two samples from the same geographical region --you can also define the region by county, state, random geographical grid you create for you own dataset among others. An example of my dataset is like THIS which is an instance segmentation task for satellite imagery.

I know pytorch has this capability for random splitting:

```<code>train_size = int(0.75 * len(full_dataset))
test_size = len(full_dataset) - train_size
train_dataset, test_dataset = torch.utils.data.random_split(full_dataset, [train_size, test_size])
</code>```

However perhaps what I want is spatially_random_spliting functionality.
Picture below is also showing the question where in my case each point is an image with associated labels.

答:
I am not completely sure what your dataset and labels look like but from what i see why not cut image into pre defined chunk sizes like here - https://stackoverflow.com/a/63815878/4471672

and say save each chunk in different folders according to location then sample from whichever set you need (or know to be "spatially disjoint) randomly

Body:
My question is close to this thread but the difference is I want my training and test dataset to be spatially disjoint. So no two samples from the same geographical region --you can also define the region by county, state, random geographical grid you create for you own dataset among others. An example of my dataset is like THIS which is an instance segmentation task for satellite imagery.

I know pytorch has this capability for random splitting:

train_size = int(0.75 * len(full_dataset))
test_size = len(full_dataset) - train_size
train_dataset, test_dataset = torch.utils.data.random_split(full_dataset, [train_size, test_size])

However perhaps what I want is spatially_random_spliting functionality.
Picture below is also showing the question where in my case each point is an image with associated labels.


问:
Apply gradient to a tensor in a sparse way in PyTorch
I have a very large tensor L (millions of elements), from which I gather a relatively small subtensor S (maybe a thousand of elements).

I then apply my model to S, compute loss, and backpropagate to S and to L with the intent to only update selected elements in L. Problem is PyTorch makes L's gradient to be a continuous tensor, so it basically doubles L's memory usage.

Is there an easy way to compute and apply gradient to L without doubling memory usage?

Sample code to illustrate the problem:

import torch
import torch.nn as nn
from torch.nn.parameter import Parameter

net = nn.Sequential(
  nn.Linear(1, 64),
  nn.ReLU(),
  nn.Linear(64,64),
  nn.ReLU(),
  nn.Linear(64, 1))

L = Parameter(torch.zeros([1024*1024*256], dtype=torch.float32))
L.data.uniform_(-1, 1)

indices = torch.randint(high=256*1024*1024, size=[1024])
S = torch.unsqueeze(L[indices], dim=1)

out = net(S)

loss = out.sum()

loss.backward()

print(loss)
g = L.grad
print(g.shape)  # this is huge!
```

答:
You don't actually need requires_grad on L as gradients will be computed and applied manually. Instead, set it on S. That will stop backpropagation at S.

Then, you can update the values of L using S.grad and your preferred optimization. Something along these lines

```<code>L = torch.zeros([1024*1024*256], dtype=torch.float32)

...

S = torch.unsqueeze(L[indices], dim=1)
S.requires_grad_()

out = net(S)

loss = torch.abs(out).sum()

loss.backward()

with torch.no_grad():
  L[indices] -= learning_rate * torch.squeeze(S.grad)
  S.grad.zero_()
</code>```

Body:
You don't actually need requires_grad on L as gradients will be computed and applied manually. Instead, set it on S. That will stop backpropagation at S.

Then, you can update the values of L using S.grad and your preferred optimization. Something along these lines

L = torch.zeros([1024*1024*256], dtype=torch.float32)

...

S = torch.unsqueeze(L[indices], dim=1)
S.requires_grad_()

out = net(S)

loss = torch.abs(out).sum()

loss.backward()

with torch.no_grad():
  L[indices] -= learning_rate * torch.squeeze(S.grad)
  S.grad.zero_()


答:
You need to iterate over the open file. This iterates over the lines for you:

with open("../test_data/my_urls.txt", "r") as urlFile:
    urls_list = []
    for url in urlFile:
        urls_list.append(url.strip())
    print(urls_list)
```

Title: Creating a list from a text file


问:
in Powershell, how to pass $args of type string[] to a "function param()" (I dont want to pass a @{} of type Hashtable to the function)
In Powershell, how to pass $args of type string[] to a "function param()"... see code below, it doesn't work...

(Note: I dont want to  pass a hash @{} of type Hashtable to the function as required by splatting.  I want to pass a string[] type as arguments to function param)...

```<code># FILE: run1.ps1
function run1{
   param(
       [switch]$go,
       [string]$sim,
       [switch]$rec
   )

   write-host "go:  $go"
   write-host "sim: $sim"
   write-host "rec: $rec"
}

write-host ""
foreach ($a in $args) {
    write-host "a: $a"
}
write-host ""

run1 $args

</code>```
```<code>
PS> ./run1.ps1

a: -go
a: -rec:
a: dfsdf
a: -rec

go:  False
sim: -go -rec: dfsdf -rec
rec: False
</code>```

答:
Instead of run1 $args, use run1 @args, i.e. splatting with the automatic $args variable.

That way, whatever arguments are passed to the run1.ps1 script - whether named or positional - are correctly passed through to the run1 function.

Caveat: This does not work for pass-through [switch] arguments with an explicit value (which is rare, however). For instance, if you were to invoke run1.ps1 with -rec:$false (instead of simply omitting this argument), -rec and $false would mistakenly be passed as two arguments, and $rec would end up being $true.

Note:

No user-defined array can provide this functionality[1] - the automatic $args array has magic built in that enables this functionality; splatting with a user-defined array only supports passing positional arguments through, and that wouldn't work in your case, because [switch] parameters are always named (non-positional).

For splatting based on user-defined variables that supports passing named arguments, hashtable-based splatting is necessary.

As an aside:

If you make your function an advanced one (in the simplest case by decorating the param(...) block with [CmdletBinding()]), it'll ensure that no extra arguments are passed (ones that don't bind to predefined parameters), for added robustness.

If you additionally make your script an advanced one - which requires defining parameters explicitly for the script itself too - you can pass the script's parameter values through via the automatic $PSBoundParameters variable variable, i.e. with run1 @PSBoundParameters. This would also avoid the [switch]-related bug mentioned above. This answer shows an example of $PSBoundParameters-based splatting in the context of a proxy (wrapper) function around Write-Host.

[1] As Santiago Squarzon points out, there a limited way to make this work, but it is both highly obscure and more cumbersome than using a hashtable for splatting and therefore not worth considering.

For the sake of completeness: To have an array element represent a parameter name, use a dummy string decorated with a NoteProperty member literally named <CommandParameterName> whose value is the target parameter name (with or without the - prefix). A minimal example that is the equivalent of

Get-ChildItem -Directory -LiteralPath \:

$arr = ('' | Add-Member -PassThru '<CommandParameterName>' 'Directory'), ('' | Add-Member -PassThru '<CommandParameterName>' 'LiteralPath'), '\'; Get-ChildItem @arr

In fact, this technique is behind the magic of @args, as the following example shows:

function foo { $args | % { "`n---`n[$_]"; $_ | Get-Member -Type NoteProperty -Force } }; foo -param1 val1

Body:
In Powershell, how to pass $args of type string[] to a "function param()"... see code below, it doesn't work...

(Note: I dont want to  pass a hash @{} of type Hashtable to the function as required by splatting.  I want to pass a string[] type as arguments to function param)...

# FILE: run1.ps1
function run1{
   param(
       [switch]$go,
       [string]$sim,
       [switch]$rec
   )

   write-host "go:  $go"
   write-host "sim: $sim"
   write-host "rec: $rec"
}

write-host ""
foreach ($a in $args) {
    write-host "a: $a"
}
write-host ""

run1 $args

PS> ./run1.ps1

a: -go
a: -rec:
a: dfsdf
a: -rec

go:  False
sim: -go -rec: dfsdf -rec
rec: False


答:
```<code>with open("../test_data/my_urls.txt", "r") as urlFile:
    urls_list = urlFile.readline().split('\n')
</code>```

Nice try I would say, since you are using readline() to read the content of the file, but you are only reading one line.

If you want to read the whole file and then .split() it in lines, you just have to do this:

```<code>with open("../test_data/my_urls.txt", "r") as urlFile:
    urls_list = urlFile.read().split('\n')
</code>```

You can get the list of the lines in an other way:

```<code>urls_list = urlFile.readlines()
</code>```

Title: Creating a list from a text file

Body:
with open("../test_data/my_urls.txt", "r") as urlFile:
    urls_list = urlFile.readline().split('\n')

Nice try I would say, since you are using readline() to read the content of the file, but you are only reading one line.

If you want to read the whole file and then .split() it in lines, you just have to do this:

with open("../test_data/my_urls.txt", "r") as urlFile:
    urls_list = urlFile.read().split('\n')

You can get the list of the lines in an other way:

urls_list = urlFile.readlines()


问:
Check if a word exists in another string in c# without using any inbuilt function
```<code>string sentence = "This is a goodday";
string word = "good";
</code>```

I know this can be done with .Contains() method. I was asked in an interview how to do it without contains method.

答:
how to do it in english.

```<code>pick the first letter of word.
walk down sentence a character at a time till you find that letter
now look at the next letters in sentence to see if they are the rest of that word
yes - done
no - keep going
</code>```

the thing to use is that word[x] is the x-1th character of word, so you just need 2 indexes and a loop or 2

Body:
string sentence = "This is a goodday";
string word = "good";

I know this can be done with .Contains() method. I was asked in an interview how to do it without contains method.

Body:
how to do it in english.

pick the first letter of word.
walk down sentence a character at a time till you find that letter
now look at the next letters in sentence to see if they are the rest of that word
yes - done
no - keep going

the thing to use is that word[x] is the x-1th character of word, so you just need 2 indexes and a loop or 2


问:
Spring Autowiring + Hibernate Search
I am trying to inject a hibernate session to use with hibernate search and am having trouble figuring out how to setup the spring beans for hibernate search. I am aware that spring does not support hibernate search. I had this working before i decided to use hibernateDAO. Any suggestions would be much appreciated.

```<code>public class RestaurantDAOImpl extends HibernateDaoSupport implements RestaurantDAO{

    public String getDishResults(final String query, final String location){
        return getHibernateTemplate().execute( new HibernateCallback<String>() {
            @Override
            public String doInHibernate(Session session) throws HibernateException, SQLException {

              FullTextSession fullTextSession = Search.getFullTextSession(session);
              fullTextSession.beginTransaction();

              QueryBuilder qBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity( Dish.class ).get();

              Query luceneQuery = qBuilder.keyword()
                    .onFields("dishName").matching("Burger")
                    .createQuery();

              ...

              return // code that generates json result based on hibernate search
        });
    }

}
</code>```

spring context

```<code><!-- Hibernate SessionFactory -->
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource">
        <ref local="dataSource" />
    </property>
    <property name="configLocation">
        <value>hibernate.cfg.xml</value>
    </property>
</bean>
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="hibernateProperties">
        <props>
            <!-- <prop key="hibernate.hbm2ddl.auto">create</prop> -->
            <prop key="hibernate.connection.pool_size">1</prop>
            <prop key="hibernate.show_sql">false</prop>
            <prop key="hibernate.connection.autocommit">true</prop>

            <!--MySQL -->
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
            <prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/database</prop>
            <prop key="hibernate.connection.username">root</prop>
            <prop key="hibernate.connection.password"></prop>

        </props>
    </property>
    <property name="annotatedClasses">
        <list>
            <value>com.bytebite.entities.Restaurant</value>
            <value>com.bytebite.entities.Dish</value>
        </list>
    </property>

</bean>

<bean id="hibernateInterceptor" class="org.springframework.orm.hibernate3.HibernateInterceptor"
    autowire="byName" /><!--sessionFactory will get autowired -->

<bean id="restaurantDAOTarget" class="com.bytebite.dao.RestaurantDAOImpl"
    autowire="byName" /><!--sessionFactory will get autowired -->

<bean id="RestaurantDAO" class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="proxyInterfaces">
        <value>com.bytebite.dao.RestaurantDAO</value>
    </property>
    <property name="interceptorNames">
        <list>
            <value>hibernateInterceptor</value>
            <value>restaurantDAOTarget</value>
        </list>
    </property>
</bean>
</code>```

And i have to somehow reference these (which were in hibernate.cfg.xml). Could I connect the hibernate context to hibernate.cfg.xml? would that help?

hibernate.cfg.xml (what remains of it anyway. where should i put this?)

```<code>    <!-- Hibernate Search -->
    <property name="hibernate.search.default.directory_provider">org.hibernate.search.store.FSDirectoryProvider</property>
    <property name="hibernate.search.default.indexBase">/Users/amandacanyon/Bytebite/Bytebite/.luceneIndex</property>
</code>```

答: See also http://community.jboss.org/wiki/SpringHibernateHibernateSearch (even though this example uses JPA)</p>

Title: Spring Autowiring + Hibernate Search

Body:
I am trying to inject a hibernate session to use with hibernate search and am having trouble figuring out how to setup the spring beans for hibernate search. I am aware that spring does not support hibernate search. I had this working before i decided to use hibernateDAO. Any suggestions would be much appreciated.

public class RestaurantDAOImpl extends HibernateDaoSupport implements RestaurantDAO{

    public String getDishResults(final String query, final String location){
        return getHibernateTemplate().execute( new HibernateCallback<String>() {
            @Override
            public String doInHibernate(Session session) throws HibernateException, SQLException {

              FullTextSession fullTextSession = Search.getFullTextSession(session);
              fullTextSession.beginTransaction();

              QueryBuilder qBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity( Dish.class ).get();

              Query luceneQuery = qBuilder.keyword()
                    .onFields("dishName").matching("Burger")
                    .createQuery();

              ...

              return // code that generates json result based on hibernate search
        });
    }

}

spring context

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource">
        <ref local="dataSource" />
    </property>
    <property name="configLocation">
        <value>hibernate.cfg.xml</value>
    </property>
</bean>
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="hibernateProperties">
        <props>

            <prop key="hibernate.connection.pool_size">1</prop>
            <prop key="hibernate.show_sql">false</prop>
            <prop key="hibernate.connection.autocommit">true</prop>

            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
            <prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/database</prop>
            <prop key="hibernate.connection.username">root</prop>
            <prop key="hibernate.connection.password"></prop>

        </props>
    </property>
    <property name="annotatedClasses">
        <list>
            <value>com.bytebite.entities.Restaurant</value>
            <value>com.bytebite.entities.Dish</value>
        </list>
    </property>

</bean>

<bean id="hibernateInterceptor" class="org.springframework.orm.hibernate3.HibernateInterceptor"
    autowire="byName" />

<bean id="restaurantDAOTarget" class="com.bytebite.dao.RestaurantDAOImpl"
    autowire="byName" />

<bean id="RestaurantDAO" class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="proxyInterfaces">
        <value>com.bytebite.dao.RestaurantDAO</value>
    </property>
    <property name="interceptorNames">
        <list>
            <value>hibernateInterceptor</value>
            <value>restaurantDAOTarget</value>
        </list>
    </property>
</bean>

And i have to somehow reference these (which were in hibernate.cfg.xml). Could I connect the hibernate context to hibernate.cfg.xml? would that help?

hibernate.cfg.xml (what remains of it anyway. where should i put this?)

    <property name="hibernate.search.default.directory_provider">org.hibernate.search.store.FSDirectoryProvider</property>
    <property name="hibernate.search.default.indexBase">/Users/amandacanyon/Bytebite/Bytebite/.luceneIndex</property>


问:
Angular Router - named router-outlets under children routes
I try to use multiple router outlets in my Angular app. I experience problems whenever I try to use multiple router outlets inside my shell container.

The intended behaviour is to have both the main component and the details component to be rendered when I visit their paths:

https://stackblitz.com/edit/angular-ivy-w9omb3?file=src%2Fapp%2Fapp.component.html

However, in this example, the app-routing.module uses a flat route structure without any children routes.

```<code>// app-routing.module.ts in flat solution
const routes: Routes = [
  { path: '', component: EmptyShellComponent },
  {
    path: 'feature1',
    loadChildren: () =>
      import('./feature-one/feature-one.module').then(
        (m) => m.FeatureOneModule
      ),
  },
  {
    path: 'feature2',
    loadChildren: () =>
      import('./feature-two/feature-two.module').then(
        (m) => m.FeatureTwoModule
      ),
  },
];
</code>```

How I want my routes in the app.routing-module to look like:

```<code>//app-routing.module.ts in solution with children routes
const routes: Routes = [
  {
    path: '',
    component: ShellComponent,
    children: [
      { path: '', component: EmptyShellComponent },
      {
        path: 'feature1',
        loadChildren: () =>
          import('./feature-one/feature-one.module').then(
            (m) => m.FeatureOneModule
          ),
      },
      {
        path: 'feature2',
        loadChildren: () =>
          import('./feature-two/feature-two.module').then(
            (m) => m.FeatureTwoModule
          ),
      },
    ],
  },
];
</code>```

However, when I use this structure I don't manage to get the router-outlet for the details to render anything: https://stackblitz.com/edit/angular-ivy-yasztr?file=src%2Fapp%2Fapp-routing.module.ts

What approach should I take to tackle this problem to allow multiple router outlets in the children modules of the shell?

EDIT

A requirement is that I would like to have a designated space for the details view at the shell-level, where one can load different detail components from different modules. Is this possible somehow? I want to be able to view feature1's main component at the same time as I am viewing feature2's details and I want both modules to be lazy loaded.

EDIT 2

By adding an the named router-outlet in the app.component.html I get the following state:

The details from the different module is rendered, but outside of the shell.

Updated stackblitz: https://stackblitz.com/edit/angular-ivy-ahptuq?file=src%2Fapp%2Fapp.component.html

答:
Angular routing can have up to one primary router outlet, and zero or more auxiliary router outlets. To create an auxiliary outlet, just give it a unique name.

<router-outlet></router-outlet>
<router-outlet name="aux"></router-outlet>
```
<p>The primary outlet is optional, you can name them all if you want. From my testing, it looks like Angular will only render one outlet for each unique name.</p>
<p>To assign a path to the <code>aux</code> outlet, just add the <code>outlet</code> property to a <code>Route</code></p>
<pre class="lang-js prettyprint-override"><code>const routes: Routes = [
  {
    path: 'features',
    component: FeatureOneComponent,
  },
  {
    path: 'features',
    component: FeatureTwoComponent,
    outlet: 'aux',
  },
];
</code>```

Now both components appear at the features path.

Another solution would be to just put both components in an enclosing component, and use a single router-outlet to navigate to it.

More info on navigating auxiliary paths here: https://www.techiediaries.com/angular-router-multiple-outlets/#Create_Named_Router_Outlet

If you want to put a router outlet inside of another routed component, you can use the children array: https://blog.devgenius.io/the-art-of-nested-router-outlets-in-angular-dafb38245a30. You don't need to give nested router-outlets unique names.

Body:
I try to use multiple router outlets in my Angular app. I experience problems whenever I try to use multiple router outlets inside my shell container.

The intended behaviour is to have both the main component and the details component to be rendered when I visit their paths:

https://stackblitz.com/edit/angular-ivy-w9omb3?file=src%2Fapp%2Fapp.component.html

However, in this example, the app-routing.module uses a flat route structure without any children routes.

// app-routing.module.ts in flat solution
const routes: Routes = [
  { path: '', component: EmptyShellComponent },
  {
    path: 'feature1',
    loadChildren: () =>
      import('./feature-one/feature-one.module').then(
        (m) => m.FeatureOneModule
      ),
  },
  {
    path: 'feature2',
    loadChildren: () =>
      import('./feature-two/feature-two.module').then(
        (m) => m.FeatureTwoModule
      ),
  },
];

How I want my routes in the app.routing-module to look like:

//app-routing.module.ts in solution with children routes
const routes: Routes = [
  {
    path: '',
    component: ShellComponent,
    children: [
      { path: '', component: EmptyShellComponent },
      {
        path: 'feature1',
        loadChildren: () =>
          import('./feature-one/feature-one.module').then(
            (m) => m.FeatureOneModule
          ),
      },
      {
        path: 'feature2',
        loadChildren: () =>
          import('./feature-two/feature-two.module').then(
            (m) => m.FeatureTwoModule
          ),
      },
    ],
  },
];

However, when I use this structure I don't manage to get the router-outlet for the details to render anything: https://stackblitz.com/edit/angular-ivy-yasztr?file=src%2Fapp%2Fapp-routing.module.ts

What approach should I take to tackle this problem to allow multiple router outlets in the children modules of the shell?

EDIT

A requirement is that I would like to have a designated space for the details view at the shell-level, where one can load different detail components from different modules. Is this possible somehow? I want to be able to view feature1's main component at the same time as I am viewing feature2's details and I want both modules to be lazy loaded.

EDIT 2

By adding an the named router-outlet in the app.component.html I get the following state:

The details from the different module is rendered, but outside of the shell.

Updated stackblitz: https://stackblitz.com/edit/angular-ivy-ahptuq?file=src%2Fapp%2Fapp.component.html

Body:
Angular routing can have up to one primary router outlet, and zero or more auxiliary router outlets. To create an auxiliary outlet, just give it a unique name.

<router-outlet></router-outlet>
<router-outlet name="aux"></router-outlet>

The primary outlet is optional, you can name them all if you want. From my testing, it looks like Angular will only render one outlet for each unique name.

To assign a path to the aux outlet, just add the outlet property to a Route

const routes: Routes = [
  {
    path: 'features',
    component: FeatureOneComponent,
  },
  {
    path: 'features',
    component: FeatureTwoComponent,
    outlet: 'aux',
  },
];

Now both components appear at the features path.

Another solution would be to just put both components in an enclosing component, and use a single router-outlet to navigate to it.

More info on navigating auxiliary paths here: https://www.techiediaries.com/angular-router-multiple-outlets/#Create_Named_Router_Outlet

If you want to put a router outlet inside of another routed component, you can use the children array: https://blog.devgenius.io/the-art-of-nested-router-outlets-in-angular-dafb38245a30. You don't need to give nested router-outlets unique names.


问:
How to fetch data from a specific JSON file?
I have one issue with fetching data from a json file.

The json file has some sub arrays and I want to map it. I created a codesandbox page and need help for mapping the related data: https://codesandbox.io/s/json-data-fetch-c00rf

When you open the link you will see that I have used React fetching with useEffect but it is not restricted with that, that means you can use another thing.

The json data coming from here: https://web-coding-challenge.vercel.joyn.de/api/blocks

Here is the code as well:

```<code>import "./styles.css";
import React, { useState, useEffect } from "react";

export default function App() {
  const [todos, setTodos] = React.useState<any[]>([]);

  React.useEffect(() => {
    fetch(`https://web-coding-challenge.vercel.joyn.de/api/blocks`)
      .then((results) => results.json())
      .then((data) => {
        setTodos(data);
      });
  }, []);

  return (
    <div className="App">
      {todos.map((post: any) => (
        <div>
          <h1>{post.id}</h1>
          <h2>{post.assets.primaryImage.url}</h2>
        </div>
      ))}
    </div>
  );
}

</code>```

答:
The response constains assets as an nested array. So you can use reduce and get all the elements in one array and then iterate it to create list

import "./styles.css";
import React, { useState, useEffect } from "react";

export default function App() {
  const [todos, setTodos] = React.useState<any[]>([]);

  React.useEffect(() => {
    fetch(`https://web-coding-challenge.vercel.joyn.de/api/blocks`)
      .then((results) => results.json())
      .then((data) => {
        const responseData = data.reduce((acc:any,curr:any)=>{
          const assets = curr.assets;
             acc.push(...assets)
          return acc ;
          },[])
        setTodos(responseData);
      });
  }, []);

  return (

      {todos.map((post: any) => (

{post.id}

{post.primaryImage.url}

      ))}

  );
}```

Body:
I have one issue with fetching data from a json file.

The json file has some sub arrays and I want to map it. I created a codesandbox page and need help for mapping the related data: https://codesandbox.io/s/json-data-fetch-c00rf

When you open the link you will see that I have used React fetching with useEffect but it is not restricted with that, that means you can use another thing.

The json data coming from here: https://web-coding-challenge.vercel.joyn.de/api/blocks

Here is the code as well:

import "./styles.css";
import React, { useState, useEffect } from "react";

export default function App() {
  const [todos, setTodos] = React.useState<any[]>([]);

  React.useEffect(() => {
    fetch(`https://web-coding-challenge.vercel.joyn.de/api/blocks`)
      .then((results) => results.json())
      .then((data) => {
        setTodos(data);
      });
  }, []);

  return (

      {todos.map((post: any) => (

{post.id}

{post.assets.primaryImage.url}

      ))}

  );
}

Body:
The response constains assets as an nested array. So you can use reduce and get all the elements in one array and then iterate it to create list

import "./styles.css";
import React, { useState, useEffect } from "react";

export default function App() {
  const [todos, setTodos] = React.useState<any[]>([]);

  React.useEffect(() => {
    fetch(`https://web-coding-challenge.vercel.joyn.de/api/blocks`)
      .then((results) => results.json())
      .then((data) => {
        const responseData = data.reduce((acc:any,curr:any)=>{
          const assets = curr.assets;
             acc.push(...assets)
          return acc ;
          },[])
        setTodos(responseData);
      });
  }, []);

  return (
    <div className="App">
      {todos.map((post: any) => (
        <div>
          <h1>{post.id}</h1>
          <h2>{post.primaryImage.url}</h2>
        </div>
      ))}
    </div>
  );
}


问:
How to add double jump to my movement script in unity3d?
Im trying to learn coding and watch youtube tutorials learn to code and I came across this code that I put in my prototype game, Im just asking what should I add to make my character do a double jump?

Code:

```<code>public class fpsmovement : MonoBehaviour
{

private float yaw = 0.0f, pitch = 0.0f;
private Rigidbody rb;

[SerializeField] float movementspeed = 5.0f, sensitivity = 2.0f;
// Start is called before the first frame update
void Start()
{
    Cursor.lockState = CursorLockMode.Locked;
    rb = gameObject.GetComponent<Rigidbody>();
}

// Update is called once per frame
void Update()
{
    if (Input.GetKey(KeyCode.Space) && Physics.Raycast(rb.transform.position, Vector3.down, 1 + 0.001f))
        rb.velocity = new Vector3(rb.velocity.x, 5.0f, rb.velocity.z);
    Look();
}

void FixedUpdate()
{
    Movement();
}

void Look()
{
    pitch -= Input.GetAxisRaw("Mouse Y") * sensitivity;
    pitch = Mathf.Clamp(pitch, -90.0f, 90.0f);
    yaw += Input.GetAxisRaw("Mouse X") * sensitivity;
    Camera.main.transform.localRotation = Quaternion.Euler(pitch, yaw, 0);
}

void Movement()
{
    Vector2 axis = new Vector2(Input.GetAxis("Vertical"), Input.GetAxis("Horizontal")).normalized * movementspeed;
    Vector3 forward = new Vector3(-Camera.main.transform.right.z, 0.0f, Camera.main.transform.right.x);
    Vector3 wishDirector = (forward * axis.x + Camera.main.transform.right * axis.y + Vector3.up * rb.velocity.y);
    rb.velocity = wishDirector;
}
</code>```

}

答: First of all you need to check if your player is grounded to be allowed to jump. You problably have a player which can jump again forever like a rocket right now. Then you need to create a boolean variable to check if the player can double jump. Set the variable to true when you jump and set the variable to false when you do the 2nd jump. Also, to allow jump, you should check if the player is grounded OR if can doublejump. There is a lot of tutorials on youtube about this topic, I hope you find the code needed easily.</p>

Body:
Im trying to learn coding and watch youtube tutorials learn to code and I came across this code that I put in my prototype game, Im just asking what should I add to make my character do a double jump?

Code:

public class fpsmovement : MonoBehaviour
{

private float yaw = 0.0f, pitch = 0.0f;
private Rigidbody rb;

[SerializeField] float movementspeed = 5.0f, sensitivity = 2.0f;
// Start is called before the first frame update
void Start()
{
    Cursor.lockState = CursorLockMode.Locked;
    rb = gameObject.GetComponent<Rigidbody>();
}

// Update is called once per frame
void Update()
{
    if (Input.GetKey(KeyCode.Space) && Physics.Raycast(rb.transform.position, Vector3.down, 1 + 0.001f))
        rb.velocity = new Vector3(rb.velocity.x, 5.0f, rb.velocity.z);
    Look();
}

void FixedUpdate()
{
    Movement();
}

void Look()
{
    pitch -= Input.GetAxisRaw("Mouse Y") * sensitivity;
    pitch = Mathf.Clamp(pitch, -90.0f, 90.0f);
    yaw += Input.GetAxisRaw("Mouse X") * sensitivity;
    Camera.main.transform.localRotation = Quaternion.Euler(pitch, yaw, 0);
}

void Movement()
{
    Vector2 axis = new Vector2(Input.GetAxis("Vertical"), Input.GetAxis("Horizontal")).normalized * movementspeed;
    Vector3 forward = new Vector3(-Camera.main.transform.right.z, 0.0f, Camera.main.transform.right.x);
    Vector3 wishDirector = (forward * axis.x + Camera.main.transform.right * axis.y + Vector3.up * rb.velocity.y);
    rb.velocity = wishDirector;
}

}


问:
What is the best way to create/reverse a linked list?
I'm a beginner at programming and I've learnt how to reverse a linked list.
Below is the code I used to make a linked list with random values and reverse it. I was wondering what the best way to do this would be. Thanks for your suggestions! Have a great day!</p>
```<code>#include<stdio.h>
#include<stdlib.h>
#include<time.h>

// node
typedef struct node{
    int number;
    struct node *next;
}node;

// functions
node *reversedList(node *head);
void printList(node *head);
node *create(int size);

int main(void)
{
    srand(time(0));
    // ........
}

node *reversedList(node *curr)
{
    // a->b->c->d
    // d->c->b->a
    node *previous = NULL;
    while(curr->next != NULL)
    {
        node *curr_temp = curr->next;
        curr->next = previous;
        previous = curr;
        curr = curr_temp;
    }
    curr->next = previous;
    return curr;
}

void printList(node *head)
{
    if (head == NULL)
        return;
    printf("%d ",head->number);
    printList(head->next);
}

node *create(int size)
{
    if(size == 0)
        return NULL;
    node *n = malloc(sizeof(node));
    n->number = rand() % 10;
    n->next = create(size - 1);
    return n;
}
</code>```

答:
The best way to reverse a singly-linked list is to reverse it without invoking undefined behavior

In your function reversedList you do not check whether the passed pointer curr is equal to NULL. So the expression in the while loop

```<code>while(curr->next != NULL)
</code>```

can invoke undefined behavior.

The function can be defined the following way

```<code>node * reversedList( node *head )
{
    // a->b->c->d
    // d->c->b->a

    node *curr = head;
    head = NULL;

    while ( curr != NULL )
    {
        Node *tmp = curr;
        curr = curr->next;
        tmp->next = head;
        head = tmp;
    }

    return head;
}
</code>```

Pay attention to that the parameter of the recursive function printList should be declared with the qualifier const because the list is not changed within the function

```<code>void printList(cosnt node *head);
</code>```

I would declare and define the recursive function the following way

```<code>FILE * printList( const node *head, FILE *fp )
{
    if ( head )
    {
        fprintf( fp, "%d ", head->number );

        printList( head->next, fp );
    }

    return fp;
}
</code>```

and in main you could write

```<code>fputc( '\n', printList( head, stdout ) );
</code>```

Using such a function you could output the list in any stream including a file stream.

Body:
I'm a beginner at programming and I've learnt how to reverse a linked list.
Below is the code I used to make a linked list with random values and reverse it. I was wondering what the best way to do this would be. Thanks for your suggestions! Have a great day!

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

// node
typedef struct node{
    int number;
    struct node *next;
}node;

// functions
node *reversedList(node *head);
void printList(node *head);
node *create(int size);

int main(void)
{
    srand(time(0));
    // ........
}

node *reversedList(node *curr)
{
    // a->b->c->d
    // d->c->b->a
    node *previous = NULL;
    while(curr->next != NULL)
    {
        node *curr_temp = curr->next;
        curr->next = previous;
        previous = curr;
        curr = curr_temp;
    }
    curr->next = previous;
    return curr;
}

void printList(node *head)
{
    if (head == NULL)
        return;
    printf("%d ",head->number);
    printList(head->next);
}

node *create(int size)
{
    if(size == 0)
        return NULL;
    node *n = malloc(sizeof(node));
    n->number = rand() % 10;
    n->next = create(size - 1);
    return n;
}

Body:
The best way to reverse a singly-linked list is to reverse it without invoking undefined behavior

In your function reversedList you do not check whether the passed pointer curr is equal to NULL. So the expression in the while loop

while(curr->next != NULL)

can invoke undefined behavior.

The function can be defined the following way

node * reversedList( node *head )
{
    // a->b->c->d
    // d->c->b->a

    node *curr = head;
    head = NULL;

    while ( curr != NULL )
    {
        Node *tmp = curr;
        curr = curr->next;
        tmp->next = head;
        head = tmp;
    }

    return head;
}

Pay attention to that the parameter of the recursive function printList should be declared with the qualifier const because the list is not changed within the function

void printList(cosnt node *head);

I would declare and define the recursive function the following way

FILE * printList( const node *head, FILE *fp )
{
    if ( head )
    {
        fprintf( fp, "%d ", head->number );

        printList( head->next, fp );
    }

    return fp;
}

and in main you could write

fputc( '\n', printList( head, stdout ) );

Using such a function you could output the list in any stream including a file stream.


问:
How intercept session get attribute?
I was trying to implement persistence for sessions. I want to basically store the session data in a db and currently I'm using HttpSessionAttributeListener to store value in db when a new session is created.

I want to know how to retrieve the session from database ie how do I override the getSession attribute to retrieve from database.

答:
Try to pass a parameter of type HttpSession to your controller.

Then access it using :

```<code>session.getAttribut(atr)
</code>```

And modify it using

```<code>session.setAttribut(atr,"value")
</code>```

Title: How intercept session get attribute?

Body:
Try to pass a parameter of type HttpSession to your controller.

Then access it using :

session.getAttribut(atr)

And modify it using

session.setAttribut(atr,"value")