问:
How to Create Random and Tags Posts on File System Generated Posts NextJS

Hello guys, i might need help to create random and specific tags posts on my Case. I in working create products showcase using NextJS and Generating markdown files into static posts using File System Module (fs) on my project to generate post page.

Since the generated posts was created by markdown files and doesn't have indexes, how to create some random posts component or some tags filtered posts since it doesn't have indexes to use math?

Repository : https://github.com/dendense/indie-showcase
Demo : aero-navy.com

I've tried using lodash module to create randomize post
`

```<code>const _ = require("lodash");
            const randomizePost = data.map((post) => {
              const { title, path } = post;
              return (
                <PostList key={`${title}`} title={title} path={path}></PostList>
              );
            });
            let result = _.sampleSize(randomizePost, 4);
            return <ul className="list-group post-list">{result}</ul>;
</code>```

`

But still no idea, please help

Body:
Hello guys, i might need help to create random and specific tags posts on my Case. I in working create products showcase using NextJS and Generating markdown files into static posts using File System Module (fs) on my project to generate post page.

Since the generated posts was created by markdown files and doesn't have indexes, how to create some random posts component or some tags filtered posts since it doesn't have indexes to use math?

Repository : https://github.com/dendense/indie-showcase
Demo : aero-navy.com

I've tried using lodash module to create randomize post
`

const _ = require("lodash");
            const randomizePost = data.map((post) => {
              const { title, path } = post;
              return (
                <PostList key={`${title}`} title={title} path={path}></PostList>
              );
            });
            let result = _.sampleSize(randomizePost, 4);
            return
{result}
;

`

But still no idea, please help


来源: stackexchange

问:
How to achieve search in code for dynamic-created text using PHP code as shortcode in WordPress?
I need to move certain articles on my website, all of them, to another unique category. I am using specific phrases which are at bottom of every article, but after code execution, only two articles are moved to a new category, not all of them.

Also when I search through all posts using the native Dashboard-All posts option, it returns only those two articles, not all of them. I assume that is because the text is not stored in the database because it shows only when the post renders itself on the front end.

How can I include dynamically created text in my code?

My code, just for reference:

```<code><?php
// Move to the category Breaking News.
$target_category_id = 1982;

// Get all posts that contain the search phrase from Syndication.
$posts = get_posts(
    array(
        's'              => 'and has been published here with permission',
        'post_status'    => 'any',
        'posts_per_page' => -1, // This will retrieve all posts.
    )
);

// Loop through the posts and move them to the target category.
foreach ( $posts as $post ) {
    // Remove the post from any existing categories.
    $current_categories = wp_get_post_categories( $post->ID );
    wp_remove_object_terms( $post->ID, $current_categories, 'category' );

    // Add the post to the target category.
    wp_set_post_categories( $post->ID, array( $target_category_id ), true );
}
</code>```

That specific phrase is created dynamically because I am using the WP Broadcast plugin to add text at the bottom of every broadcasted article, but I am not sure if that phrase is stored in a database or that text is dynamically populated (created) every time post is rendered on the frontend.

This is the code I am using to generate a message (and has been published here with permission) at the bottom of every article:

```<code><?php
function broadcasted_from() {
    // Check that Broadcast is enabled.
    if ( ! function_exists( 'ThreeWP_Broadcast' ) ) {
        return;
    }

    // Load the broadcast data for this post.
    global $post;
    $broadcast_data = ThreeWP_Broadcast()->get_post_broadcast_data( get_current_blog_id(), $post->ID );
    // This post must be a child. Check for a parent.
    $parent = $broadcast_data->get_linked_parent();
    if ( ! $parent ) {
        return;
    }

    // Fetch the permalink
    switch_to_blog( $parent['blog_id'] );
    $blog_name = get_bloginfo( 'name' );
    $permalink = get_post_permalink( $parent['post_id'] );
    restore_current_blog();

    // And now assemble a text.
    $r = sprintf( 'This article appeared in <a href="%s">%s</a> and has been published here with permission.', $permalink, $blog_name );
    return $r;
}
add_shortcode( 'broadcasted_from', 'broadcasted_from' );

add_filter(
    'the_content',
    function( $content ) {
        // Get the broadcast from the text.
        $sc_text = do_shortcode( '[broadcasted_from]' );
        // Add the text to the content.
        $content .= $sc_text;
        // Return the expanded content.
        return $content;
    }
);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to move certain articles on my website, all of them, to another unique category. I am using specific phrases which are at bottom of every article, but after code execution, only two articles are moved to a new category, not all of them.

Also when I search through all posts using the native Dashboard-All posts option, it returns only those two articles, not all of them. I assume that is because the text is not stored in the database because it shows only when the post renders itself on the front end.

How can I include dynamically created text in my code?

My code, just for reference:

<?php
// Move to the category Breaking News.
$target_category_id = 1982;

// Get all posts that contain the search phrase from Syndication.
$posts = get_posts(
    array(
        's'              => 'and has been published here with permission',
        'post_status'    => 'any',
        'posts_per_page' => -1, // This will retrieve all posts.
    )
);

// Loop through the posts and move them to the target category.
foreach ( $posts as $post ) {
    // Remove the post from any existing categories.
    $current_categories = wp_get_post_categories( $post->ID );
    wp_remove_object_terms( $post->ID, $current_categories, 'category' );

    // Add the post to the target category.
    wp_set_post_categories( $post->ID, array( $target_category_id ), true );
}

That specific phrase is created dynamically because I am using the WP Broadcast plugin to add text at the bottom of every broadcasted article, but I am not sure if that phrase is stored in a database or that text is dynamically populated (created) every time post is rendered on the frontend.

This is the code I am using to generate a message (and has been published here with permission) at the bottom of every article:

<?php
function broadcasted_from() {
    // Check that Broadcast is enabled.
    if ( ! function_exists( 'ThreeWP_Broadcast' ) ) {
        return;
    }

    // Load the broadcast data for this post.
    global $post;
    $broadcast_data = ThreeWP_Broadcast()->get_post_broadcast_data( get_current_blog_id(), $post->ID );
    // This post must be a child. Check for a parent.
    $parent = $broadcast_data->get_linked_parent();
    if ( ! $parent ) {
        return;
    }

    // Fetch the permalink
    switch_to_blog( $parent['blog_id'] );
    $blog_name = get_bloginfo( 'name' );
    $permalink = get_post_permalink( $parent['post_id'] );
    restore_current_blog();

    // And now assemble a text.
    $r = sprintf( 'This article appeared in %s and has been published here with permission.', $permalink, $blog_name );
    return $r;
}
add_shortcode( 'broadcasted_from', 'broadcasted_from' );

add_filter(
    'the_content',
    function( $content ) {
        // Get the broadcast from the text.
        $sc_text = do_shortcode( '[broadcasted_from]' );
        // Add the text to the content.
        $content .= $sc_text;
        // Return the expanded content.
        return $content;
    }
);


问:
Error: Could not find or load main class HelloApp
I'm a beginner trying to learn to program in Java. I'm using the book Java All In One for Dummies. The book has me using Textpad to write and compile the code. I've got the following simple program:

```<code>public class HelloApp  {

    public static void main(String[] args)  {

        printHello("World");
        }

    public static void printHello(String greetee) {

        System.out.println("Hello " + greetee);

     }
}
</code>```

I saved the files for the java application in at the following path. D:\program files\java. When I compile the app with the Textpad compiler, it compiles without any errors. I have the files saved in the following folder: D:\program files\java. When I try to run the app from the Run Java Application command in Textpad, it gives me the error message "Error: Could not find or load main class HelloApp.java". When I run the app from the command prompt using the java HelloApp.java, it runs fine displaying "Hello World" Why does it work when I run it using the java HelloApp.java command which is what I assume the "run java application" command in Textpad does, and not work using the command in Textpad? What am I doing wrong?

I tried resaving and recompiling the application. Then I ran it directly from the command prompt. It worked when running directly from the command prompt but it won't work when trying to run from the "Run Java Application" command in Textpad.

I assumed it would work as it seems like I'm doing the exact same thing from Textpad as I am from using the java HelloApp.java command at the windows command prompt.

Body:
I'm a beginner trying to learn to program in Java. I'm using the book Java All In One for Dummies. The book has me using Textpad to write and compile the code. I've got the following simple program:

public class HelloApp  {

    public static void main(String[] args)  {

        printHello("World");
        }

    public static void printHello(String greetee) {

        System.out.println("Hello " + greetee);

     }
}

I saved the files for the java application in at the following path. D:\program files\java. When I compile the app with the Textpad compiler, it compiles without any errors. I have the files saved in the following folder: D:\program files\java. When I try to run the app from the Run Java Application command in Textpad, it gives me the error message "Error: Could not find or load main class HelloApp.java". When I run the app from the command prompt using the java HelloApp.java, it runs fine displaying "Hello World" Why does it work when I run it using the java HelloApp.java command which is what I assume the "run java application" command in Textpad does, and not work using the command in Textpad? What am I doing wrong?

I tried resaving and recompiling the application. Then I ran it directly from the command prompt. It worked when running directly from the command prompt but it won't work when trying to run from the "Run Java Application" command in Textpad.

I assumed it would work as it seems like I'm doing the exact same thing from Textpad as I am from using the java HelloApp.java command at the windows command prompt.


问:
memcache get value with random result
I try to get value with a key without any updated but everytime get different value.
I am not sure it's bug of memcache or php.

environment: php7.4.30 & memcache 4.0.5.2
code:

```<code>$oMemcache=new Memcache();
$oMemcache->connect($ip,$port);
$a=$oMemcache->get($key);//string(1) '1'
$b=$oMemcache->get($key);//string(0) ''
$c=$oMemcache->get($key);//string(1) '1'
</code>```

Title: memcache get value with random result

Body:
I try to get value with a key without any updated but everytime get different value.
I am not sure it's bug of memcache or php.

environment: php7.4.30 & memcache 4.0.5.2
code:

$oMemcache=new Memcache();
$oMemcache->connect($ip,$port);
$a=$oMemcache->get($key);//string(1) '1'
$b=$oMemcache->get($key);//string(0) ''
$c=$oMemcache->get($key);//string(1) '1'


问:
How to send server side encryption customer keys while uploading an object to S3 using a POST request?
I have been trying to upload a file to a pre-signed AWS-S3 POST URL that my server generates. During the upload I want the file to be encrypted by a key provided by my user.
These is the info I have been asked to send along with the request:
When you use SSE-C, you must provide encryption key information using the following request headers

My key is: TEST123
I used online generators to generate the following:
The base64 encoding of the key is: VEVTVDEyMw==
The MD5 hash of the key is: 22b75d6007e06f4a959d1b1d69b4c4bd
The base64 encoding of the md5 hash of the key is: MjJiNzVkNjAwN2UwNmY0YTk1OWQxYjFkNjliNGM0YmQ=

Here's the request I sent to the pre-signed URL:
Screenshot of the Postman request

I get the following response:
Screenshot of the response

I couldn't figure out how is the hash not matching. I tried to reverify multiple times but still arrive at the same response. How do I do this?

The upload file should be encrypted by a key provided by my user. That is server-side encryption with customer-provided keys (SSE-C).


问:
Youtube-dl (Forbidden 403 error, not a common solution)
I am using youtube-dl for downloading videos from youtube mostly. It is latest version on my Mac.

This time I wanted to download some video presentation from conference I am participating. They are using zoom client in Chrome browser.

I am not able to download video with presentation

I used the following steps:

There are two video streams on the same webpage (one for presenter, one for presentation material)

youtube-dl captures only first part with presenter view.

There are no other information from json file about second video (no playlist, no other ids).

I used another software to download a video (VideoDuke).

It shows that there are two videos with different size (presenter and presentation).

I am forbidden to download both of them (youtube-dl could download the first one, by use original URL).

I can copy video address from VideoDuke and use it for youtube-dl.

I receive error "Forbidden 403" with youtube-dl on both of videos (different links from original URL).

--rm-cache-dir does not help.

if I use --verbose on original URL, I can see that it is invoking downloader on the first video with the same URL the VideoDuke produced, and it can download the file.

Is it possible to invoke downloader on the second URL provided by VideoDuke. I can also get similar URL from inspector in Google Chrome.

Last year I participated in the same conference and the original URL was similar, although that time there were some true/false statements I could tweak and download exactly the presentation video, and not the presenter. This year, that option disappeared.


问:
I want to save client details in application database from spi registation flow in keycloak
I want to save client details in application database which were collected from spi registation flow after otp autherization in keycloak. Actually I want to know about the way of calling rest API post method inside a spi registation form using java

I'm expecting the way of implementing client detail save methodology using the data collected from sign up flow like form.


问:
How to override the semantic UI Form Input Color?
I have been trying to override a semantic UI CSS property in a form input element. I want to change the background color in the input field to white. It keeps showing yellow. I just am testing out different colors and borders trying to get them to work. But nothing does. I have been trying to change it for hours now. Any suggestions?

I have tried the following CSS (and many other things) and none of it works. I am expecting for the background color of the semantic UI form input selector to change because I am trying to over ride it with CSS.

CSS

```<code>input {
  background-color: blue !important;
}

ui.input {

  background-color: blue !important;

}
#root > div > div > div.form-container > div > div > form{
  background-color: blue !important;
}
#root > div > div > div.form-container > div > div > form > div:nth-child(1) > div{
  background-color: yellow !important;
}

#root > div > div > div.form-container > div > div > form > div:nth-child(2){
  background-color: yellowgreen !important;
}

div.ui.grid.container > .form-container > .ui.stackable > form{
   background-color: magenta !important;
  }
</code>```

HTML CODE

```<code><div className="form-container">
          <div className="ui stackable">
            <div className="row">
              <Form
                onSubmit={onSubmit}
                noValidate
                className={loading ? "loading" : ""}
              >
                <h1>Log In</h1>
                <Form.Input
                  label="Username"
                  placeholder="Username.."
                  name="username"
                  type="text"
                  value={values.username}
                  error={errors.username ? true : false}
                  onChange={onChange}
                />
                <Form.Input
                  label="Password"
                  placeholder="Password.."
                  name="password"
                  type="password"
                  value={values.password}
                  error={errors.password ? true : false}
                  onChange={onChange}
                />
                <Button
                  onClick={() => Redirect("/")}
                  type="submit"
                  id="login-btn"
                  primary
                >
                  Log In
                </Button>
              </Form>
              <Button
                onClick={() => history.push("/register")}
                id="register-btn"
                primary
              >
                Register
              </Button>
              {Object.keys(errors).length > 0 && (
                <div className="ui error message">
                  <ul className="list">
                    {Object.values(errors).map((value) => (
                      <li key={value}>{value}</li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

</code>```

Body:
I have been trying to override a semantic UI CSS property in a form input element. I want to change the background color in the input field to white. It keeps showing yellow. I just am testing out different colors and borders trying to get them to work. But nothing does. I have been trying to change it for hours now. Any suggestions?

I have tried the following CSS (and many other things) and none of it works. I am expecting for the background color of the semantic UI form input selector to change because I am trying to over ride it with CSS.

CSS

input {
  background-color: blue !important;
}

ui.input {

  background-color: blue !important;

}
#root > div > div > div.form-container > div > div > form{
  background-color: blue !important;
}
#root > div > div > div.form-container > div > div > form > div:nth-child(1) > div{
  background-color: yellow !important;
}

#root > div > div > div.form-container > div > div > form > div:nth-child(2){
  background-color: yellowgreen !important;
}

div.ui.grid.container > .form-container > .ui.stackable > form{
   background-color: magenta !important;
  }

HTML CODE

              <Form
                onSubmit={onSubmit}
                noValidate
                className={loading ? "loading" : ""}
              >

Log In

                <Form.Input
                  label="Username"
                  placeholder="Username.."
                  name="username"
                  type="text"
                  value={values.username}
                  error={errors.username ? true : false}
                  onChange={onChange}
                />
                <Form.Input
                  label="Password"
                  placeholder="Password.."
                  name="password"
                  type="password"
                  value={values.password}
                  error={errors.password ? true : false}
                  onChange={onChange}
                />
                <Button
                  onClick={() => Redirect("/")}
                  type="submit"
                  id="login-btn"
                  primary
                >
                  Log In
                </Button>
              </Form>
              <Button
                onClick={() => history.push("/register")}
                id="register-btn"
                primary
              >
                Register
              </Button>
              {Object.keys(errors).length > 0 && (

                    {Object.values(errors).map((value) => (

{value}

                    ))}

              )}


问:
Can a shinytheme be a reactive value?
I'd like to have a shinytheme that changes whenever I hold a key. Is it possible to make themes in shiny reactive values?

I have not been able to figure out any possibilities yet. But when I hold the key I want the shiny theme to change to dark and when the key is not held I want it to be white.

Title: Can a shinytheme be a reactive value?


问:
convert json nsdictionary into useable array
I have been trying to find the most efficient way to convert a JSON response into a useable array that can be referenced as a UITableView data source.  The sample here is from the World Weather Online free weather service.

I have no problems in doing the JSON conversion using Jonathan Wights TouchJSON method but now that I have an NSarray of NSDictionaries I can't seem to find an efficient way to move the data into an array except by brute force.  That is I can get any value from the nested NSDictionaries but the only way I can build a usable array is to take each value individually and place it into the correct location in my array.  I can do that with a seperate object that builds an array with strings that represent each of the values in the JSON reponse, but there must be a better way of doing this than having to use brute force.

When I try the recomended methods I get "data" as the key and the rest of the output as the value.  I then make a new dictionary of the objectforkey:@"data" and it only gives me an array of the 4 keys "nearest_area", "current_condition", "weather" and "request".  And if I try and make a new NSDictionary from the newly created NSDictionary it gives me an error.

Is there a way to take the nested NSDictionaries and place the keys and values in the nested NSDictionary into an nsarray?

Heres the code

```<code>   - (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *webResult = [[NSString alloc] initWithData:receivedWeatherData encoding:NSUTF8StringEncoding];
    NSError *theError = NULL;
    receivedDictionary = [NSMutableDictionary dictionaryWithJSONString:webResult error:&theError];
    NSLog(@"\n%@\n",receivedDictionary);
</code>```

Here is the output converted into an NSArray of NSDictionarys

```<code>  {
    data =     {
        "current_condition" =         (
                        {
                cloudcover = 50;
                humidity = 44;
                "observation_time" = "01:24 AM";
                precipMM = "0.0";
                pressure = 1000;
                "temp_C" = 14;
                "temp_F" = 57;
                visibility = 10;
                weatherCode = 116;
                weatherDesc =                 (
                                        {
                        value = "Partly Cloudy";
                    }
                );
                weatherIconUrl =                 (
                                        {
                        value = "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png";
                    }
                );
                winddir16Point = NW;
                winddirDegree = 310;
                windspeedKmph = 20;
                windspeedMiles = 13;
            }
        );
        "nearest_area" =         (
                        {
                areaName =                 (
                                        {
                        value = Hobart;
                    }
                );
                country =                 (
                                        {
                        value = Australia;
                    }
                );
                latitude = "-42.920";
                longitude = "147.330";
                population = 204863;
                region =                 (
                                        {
                        value = Tasmania;
                    }
                );
                weatherUrl =                 (
                                        {
                        value = "http://free.worldweatheronline.com/weather/Australia/106511/Hobart/110625/info.aspx";
                    }
                );
            }
        );
        request =         (
                        {
                query = "Lat -42.92 and Lon 147.33";
                type = LatLon;
            }
        );
        weather =         (
                        {
                date = "2011-09-20";
                precipMM = "2.4";
                tempMaxC = 12;
                tempMaxF = 54;
                tempMinC = 7;
                tempMinF = 45;
                weatherCode = 116;
                weatherDesc =                 (
                                        {
                        value = "Partly Cloudy";
                    }
                );
                weatherIconUrl =                 (
                                        {
                        value = "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png";
                    }
                );
                winddir16Point = W;
                winddirDegree = 277;
                winddirection = W;
                windspeedKmph = 23;
                windspeedMiles = 14;
            }
        );
    };
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have been trying to find the most efficient way to convert a JSON response into a useable array that can be referenced as a UITableView data source.  The sample here is from the World Weather Online free weather service.

I have no problems in doing the JSON conversion using Jonathan Wights TouchJSON method but now that I have an NSarray of NSDictionaries I can't seem to find an efficient way to move the data into an array except by brute force.  That is I can get any value from the nested NSDictionaries but the only way I can build a usable array is to take each value individually and place it into the correct location in my array.  I can do that with a seperate object that builds an array with strings that represent each of the values in the JSON reponse, but there must be a better way of doing this than having to use brute force.

When I try the recomended methods I get "data" as the key and the rest of the output as the value.  I then make a new dictionary of the objectforkey:@"data" and it only gives me an array of the 4 keys "nearest_area", "current_condition", "weather" and "request".  And if I try and make a new NSDictionary from the newly created NSDictionary it gives me an error.

Is there a way to take the nested NSDictionaries and place the keys and values in the nested NSDictionary into an nsarray?

Heres the code

   - (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *webResult = [[NSString alloc] initWithData:receivedWeatherData encoding:NSUTF8StringEncoding];
    NSError *theError = NULL;
    receivedDictionary = [NSMutableDictionary dictionaryWithJSONString:webResult error:&theError];
    NSLog(@"\n%@\n",receivedDictionary);

Here is the output converted into an NSArray of NSDictionarys

  {
    data =     {
        "current_condition" =         (
                        {
                cloudcover = 50;
                humidity = 44;
                "observation_time" = "01:24 AM";
                precipMM = "0.0";
                pressure = 1000;
                "temp_C" = 14;
                "temp_F" = 57;
                visibility = 10;
                weatherCode = 116;
                weatherDesc =                 (
                                        {
                        value = "Partly Cloudy";
                    }
                );
                weatherIconUrl =                 (
                                        {
                        value = "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png";
                    }
                );
                winddir16Point = NW;
                winddirDegree = 310;
                windspeedKmph = 20;
                windspeedMiles = 13;
            }
        );
        "nearest_area" =         (
                        {
                areaName =                 (
                                        {
                        value = Hobart;
                    }
                );
                country =                 (
                                        {
                        value = Australia;
                    }
                );
                latitude = "-42.920";
                longitude = "147.330";
                population = 204863;
                region =                 (
                                        {
                        value = Tasmania;
                    }
                );
                weatherUrl =                 (
                                        {
                        value = "http://free.worldweatheronline.com/weather/Australia/106511/Hobart/110625/info.aspx";
                    }
                );
            }
        );
        request =         (
                        {
                query = "Lat -42.92 and Lon 147.33";
                type = LatLon;
            }
        );
        weather =         (
                        {
                date = "2011-09-20";
                precipMM = "2.4";
                tempMaxC = 12;
                tempMaxF = 54;
                tempMinC = 7;
                tempMinF = 45;
                weatherCode = 116;
                weatherDesc =                 (
                                        {
                        value = "Partly Cloudy";
                    }
                );
                weatherIconUrl =                 (
                                        {
                        value = "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png";
                    }
                );
                winddir16Point = W;
                winddirDegree = 277;
                winddirection = W;
                windspeedKmph = 23;
                windspeedMiles = 14;
            }
        );
    };
}


问:
C++ and OpenVDB FloatGrid to Vec3SGrid and back to FloatGrid
Here is a basic sample converting them and dumping the result into a mesh:

```<code>// FloatGrid  to Vec3SGrid
openvdb::Vec3SGrid::Ptr Vec3SGrid = openvdb::Vec3SGrid::create();
Vec3SGrid->setTransform( floatGridA->transformPtr());
Vec3SGrid->tree().root().setBackground(openvdb::Vec3f(floatGridA->background()),true);
for (auto itAll =  floatGridA ->cbeginValueOn(); itAll; ++itAll) {
        auto pos = itAll.getCoord();
        auto valueAll = itAll.getValue();
        auto Vec3s = Vec3SGrid->tree().getValue(pos);
        Vec3s[0] = valueAll;
        Vec3SGrid->tree().setValue(pos, Vec3s);
 }

// Back to FloatGrid
openvdb::FloatGrid::Ptr floatGridB = openvdb::FloatGrid::create();
floatGridB->setTransform( Vec3SGrid->transformPtr());
floatGridB->tree().root().setBackground(Vec3SGrid->background()[0], true);
for (auto it = grid->cbeginValueOn(); it; ++it) {
      auto pos = it.getCoord();
      auto Vec3s = it.getValue();
       floatGridB->tree().setValue(pos, Vec3s[0]);
}
OpenVDBMesh meshA, meshB;
openvdb::tools::volumeToMesh(*floatGridA ,  meshA.points,  meshA.faces,  meshA.quads, iso, adapt, flag_relax);
openvdb::tools::volumeToMesh(*floatGridB ,  meshB.points,  meshB.faces,  meshB.quads, iso, adapt, flag_relax);
</code>```

Unfortunately the besides I've copied transform too, the result on both meshes are different.

Any idea on that? thank you!

Body:
Here is a basic sample converting them and dumping the result into a mesh:

// FloatGrid  to Vec3SGrid
openvdb::Vec3SGrid::Ptr Vec3SGrid = openvdb::Vec3SGrid::create();
Vec3SGrid->setTransform( floatGridA->transformPtr());
Vec3SGrid->tree().root().setBackground(openvdb::Vec3f(floatGridA->background()),true);
for (auto itAll =  floatGridA ->cbeginValueOn(); itAll; ++itAll) {
        auto pos = itAll.getCoord();
        auto valueAll = itAll.getValue();
        auto Vec3s = Vec3SGrid->tree().getValue(pos);
        Vec3s[0] = valueAll;
        Vec3SGrid->tree().setValue(pos, Vec3s);
 }

// Back to FloatGrid
openvdb::FloatGrid::Ptr floatGridB = openvdb::FloatGrid::create();
floatGridB->setTransform( Vec3SGrid->transformPtr());
floatGridB->tree().root().setBackground(Vec3SGrid->background()[0], true);
for (auto it = grid->cbeginValueOn(); it; ++it) {
      auto pos = it.getCoord();
      auto Vec3s = it.getValue();
       floatGridB->tree().setValue(pos, Vec3s[0]);
}
OpenVDBMesh meshA, meshB;
openvdb::tools::volumeToMesh(*floatGridA ,  meshA.points,  meshA.faces,  meshA.quads, iso, adapt, flag_relax);
openvdb::tools::volumeToMesh(*floatGridB ,  meshB.points,  meshB.faces,  meshB.quads, iso, adapt, flag_relax);

Unfortunately the besides I've copied transform too, the result on both meshes are different.

Any idea on that? thank you!


问:
React native expo. How to render a .glb 3D Model from an URL?
I come from web develop using React and for 3D, the <model-viewer> package.

I'm working now with react native expo and I have worked for this project since a year.

Now I'm trying to implement the visualization of 3D, using the expo-three package. Because, it's difficult to understand the doc, I was trying to search an example, but I did't find anything useful.

I tried to search in SO, but the only similar question I found:

 haven't a solution

or an answer

or they use a different file

or are not reproducible

or are without expo

or are examples without file rendering

or are just react and not react native solutions

In other places are full native, but I can't use this command react-native link react-native-3d-model-view because I'm using expo and I don't want to code deep native.

Therefore. I'm asking for a full .js file (not code pieces) example only using react native expo packages like three, expo-three, and expo-gl for rendering a .glb 3D model from a url in a react native app. I have spent a lot of time trying to achieve this. I will be very grateful for this!
Here is an example url for a .glb file

I know that it is posible because of an outdate solution's issue in GitHub. Answering to the solution of eject expo in this question's comments

I have successfully render a blue rotating cube but not a file:

```<code>import React from "react";
import { View } from "react-native";
import {
  Scene,
  Mesh,
  MeshBasicMaterial,
  PerspectiveCamera,
  BoxBufferGeometry,
} from "three";
import { Renderer } from "expo-three";
import { GLView } from "expo-gl";

const App = () => {
  const onContextCreate = async (gl) => {
    // three.js implementation.
    const scene = new Scene();
    const camera = new PerspectiveCamera(
      75,
      gl.drawingBufferWidth / gl.drawingBufferHeight,
      0.1,
      1000
    );
    gl.canvas = {
      width: gl.drawingBufferWidth,
      height: gl.drawingBufferHeight,
    };

    // set camera position away from cube
    camera.position.z = 2;

    const renderer = new Renderer({ gl });
    // set size of buffer to be equal to drawing buffer width
    renderer.setSize(gl.drawingBufferWidth, gl.drawingBufferHeight);

    // create cube
    // define geometry
    const geometry = new BoxBufferGeometry(1, 1, 1);
    const material = new MeshBasicMaterial({
      color: "cyan",
    });

    const cube = new Mesh(geometry, material);

    // add cube to scene
    scene.add(cube);

    // create render function
    const render = () => {
      requestAnimationFrame(render);
      // create rotate functionality
      // rotate around x axis
      cube.rotation.x += 0.01;

      // rotate around y axis
      cube.rotation.y += 0.01;

      renderer.render(scene, camera);
      gl.endFrameEXP();
    };

    // call render
    render();
  };

  return (
    <View>
      <GLView
        onContextCreate={onContextCreate}
        // set height and width of GLView
        style={{ width: 400, height: 400 }}
      />
    </View>
  );
};

export default App;

</code>```

If you read this, upvote the change in expo

Body:
I come from web develop using React and for 3D, the <model-viewer> package.

I'm working now with react native expo and I have worked for this project since a year.

Now I'm trying to implement the visualization of 3D, using the expo-three package. Because, it's difficult to understand the doc, I was trying to search an example, but I did't find anything useful.

I tried to search in SO, but the only similar question I found:

 haven't a solution

or an answer

or they use a different file

or are not reproducible

or are without expo

or are examples without file rendering

or are just react and not react native solutions

In other places are full native, but I can't use this command react-native link react-native-3d-model-view because I'm using expo and I don't want to code deep native.

Therefore. I'm asking for a full .js file (not code pieces) example only using react native expo packages like three, expo-three, and expo-gl for rendering a .glb 3D model from a url in a react native app. I have spent a lot of time trying to achieve this. I will be very grateful for this!
Here is an example url for a .glb file

I know that it is posible because of an outdate solution's issue in GitHub. Answering to the solution of eject expo in this question's comments

I have successfully render a blue rotating cube but not a file:

import React from "react";
import { View } from "react-native";
import {
  Scene,
  Mesh,
  MeshBasicMaterial,
  PerspectiveCamera,
  BoxBufferGeometry,
} from "three";
import { Renderer } from "expo-three";
import { GLView } from "expo-gl";

const App = () => {
  const onContextCreate = async (gl) => {
    // three.js implementation.
    const scene = new Scene();
    const camera = new PerspectiveCamera(
      75,
      gl.drawingBufferWidth / gl.drawingBufferHeight,
      0.1,
      1000
    );
    gl.canvas = {
      width: gl.drawingBufferWidth,
      height: gl.drawingBufferHeight,
    };

    // set camera position away from cube
    camera.position.z = 2;

    const renderer = new Renderer({ gl });
    // set size of buffer to be equal to drawing buffer width
    renderer.setSize(gl.drawingBufferWidth, gl.drawingBufferHeight);

    // create cube
    // define geometry
    const geometry = new BoxBufferGeometry(1, 1, 1);
    const material = new MeshBasicMaterial({
      color: "cyan",
    });

    const cube = new Mesh(geometry, material);

    // add cube to scene
    scene.add(cube);

    // create render function
    const render = () => {
      requestAnimationFrame(render);
      // create rotate functionality
      // rotate around x axis
      cube.rotation.x += 0.01;

      // rotate around y axis
      cube.rotation.y += 0.01;

      renderer.render(scene, camera);
      gl.endFrameEXP();
    };

    // call render
    render();
  };

  return (
    <View>
      <GLView
        onContextCreate={onContextCreate}
        // set height and width of GLView
        style={{ width: 400, height: 400 }}
      />
    </View>
  );
};

export default App;

If you read this, upvote the change in expo


问:
To progress the highlighted view on basis of tableview content height while scrolling in Swift

I'm increasing the width constraint of green view and increasing its width while scrolling the tableView till very bottom. I tried but not getting exact values:

```<code>  override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {

    let height = self.tableView?.contentSize.height

    if array.count > 0{
        //var hh = CGFloat((tableView?.indexPathsForVisibleRows?.last!.row)!)
        let totalHeight = ((tableView?.contentSize.height)!)
        let totalWidth = (UIScreen.main.bounds.width)
        let ratio = totalWidth / totalHeight

        let val = round(CGFloat(globalIndex) / (totalHeight - UIScreen.main.bounds.height) * 100);

        viewWidthConstraint.constant = CGFloat(globalIndex) * ratio *  100
    }
  }
</code>```

Body:
I'm increasing the width constraint of green view and increasing its width while scrolling the tableView till very bottom. I tried but not getting exact values:

  override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {

    let height = self.tableView?.contentSize.height

    if array.count > 0{
        //var hh = CGFloat((tableView?.indexPathsForVisibleRows?.last!.row)!)
        let totalHeight = ((tableView?.contentSize.height)!)
        let totalWidth = (UIScreen.main.bounds.width)
        let ratio = totalWidth / totalHeight

        let val = round(CGFloat(globalIndex) / (totalHeight - UIScreen.main.bounds.height) * 100);

        viewWidthConstraint.constant = CGFloat(globalIndex) * ratio *  100
    }
  }


问:
Can't resolve './server.component.css'
I created the following component:

```<code>import { Component } from "@angular/core";

@Component({
    selector: 'app-server',
    template: `<h1>Some Information</h1>`,
    styleUrls: ['./server.component.css']
})
export class Servercomponent{

}
</code>```

When I try to compile my app, I get the following error:

```<code>ERROR in ./src/app/server/server.component.ts
Module not found: Error: Can't resolve './server.component.css' in 'E:\Angular\angularapp\angularapp\src\app\server'
i ｢wdm｣: Failed to compile.
</code>```

Do you have any idea what the problem could be?

Title: Can't resolve './server.component.css'

Body:
I created the following component:

import { Component } from "@angular/core";

@Component({
    selector: 'app-server',
    template: `<h1>Some Information</h1>`,
    styleUrls: ['./server.component.css']
})
export class Servercomponent{

}

When I try to compile my app, I get the following error:

ERROR in ./src/app/server/server.component.ts
Module not found: Error: Can't resolve './server.component.css' in 'E:\Angular\angularapp\angularapp\src\app\server'
i ｢wdm｣: Failed to compile.

Do you have any idea what the problem could be?


问:
the api is not started, getting this error error: [app] Application is crashed: EntityMetadataNotFound: No metadata for "User" was found
I build the app, the build was successful, I console log env.app.dirs.entities it returns
[
'C:\Users\XXX\Documents\projects\ecommerce\Spurtcommerce_1.0_community_alpha\api\dist\api\models\.js',
'C:\Users\XXX\Documents\projects\ecommerce\Spurtcommerce_1.0_community_alpha\api\dist\plugin-manager\models\.js'
]
Now the api is not started, getting this error error: [app] Application is crashed: EntityMetadataNotFound: No metadata for "User" was found.

If i use npm run start then it works but when try npm start serve it doesn't works


问:
How do i fix "No module Found 'speech_recognition' " after doing pip install SpeechRecognition in my pycharm IDE
I want to import speech_recognition, but it's saying No Module Found. i have already installed pip install SpeechRecognition. what can i do to avoid this error?

Installing with pip3, but it say requirements satisfied.


问:
How to get url after add_rewrite_rule in wordpress
I have a post id is 3585 with permalink is https://test.com/apply-now/course
I add a params cid for new rewrite url

```<code>add_rewrite_rule(
    '^apply-now/course/([a-z0-9\-_]+)/?$',
    'index.php?pagename=course&cid=$matches[1]',
    'top'
);
</code>```

I want get a sample url with cid

```<code>$id = 123;
$new_url = add_query_arg('cid', $id, get_permalink(3585));
</code>```

Result is: https://test.com/apply-now/course/?cid=123

How to fix it https://test.com/apply-now/course/123

Body:
I have a post id is 3585 with permalink is https://test.com/apply-now/course
I add a params cid for new rewrite url

add_rewrite_rule(
    '^apply-now/course/([a-z0-9\-_]+)/?$',
    'index.php?pagename=course&cid=$matches[1]',
    'top'
);

I want get a sample url with cid

$id = 123;
$new_url = add_query_arg('cid', $id, get_permalink(3585));

Result is: https://test.com/apply-now/course/?cid=123

How to fix it https://test.com/apply-now/course/123


问:
Error while loading block dataset to train model
I have a NumPy array, which I am trying to read as a block dataset. My NumPy array dimensions are as follows :

```<code>(24312, 32, 32)
</code>```

Now, when I run the following code,
class BlockDataset(Dataset):
"""
Creates block dataset of 32X32 images with 3 channels
requires numpy and cv2 to work
"""

```<code>def __init__(self, file_path, train=True, transform=None):

    print('Loading block data')
    self.data = np.load(file_path, allow_pickle=True)
    #self.data = np.transpose(self.data,(0,2,3,1))
    print(self.data.shape)
    print('Done loading block data')

    n = self.data.shape[0]
    cutoff = n/1 #changed from 10 to 5
   # self.data = data[:-cutoff] if train else data[-cutoff:]
    self.transform = transform

def __getitem__(self, index):
    img = self.data[index]
    if self.transform is not None:
        img = self.transform(img)
    label = 0
    return img, label

def __len__(self):
    return len(self.data)
</code>```

It throws up the following error :

```<code>RuntimeError: output with shape [1, 32, 32] doesn't match the broadcast shape [3, 32, 32]
</code>```

How to resolve this ?

Body:
I have a NumPy array, which I am trying to read as a block dataset. My NumPy array dimensions are as follows :

(24312, 32, 32)

Now, when I run the following code,
class BlockDataset(Dataset):
"""
Creates block dataset of 32X32 images with 3 channels
requires numpy and cv2 to work
"""

def __init__(self, file_path, train=True, transform=None):

    print('Loading block data')
    self.data = np.load(file_path, allow_pickle=True)
    #self.data = np.transpose(self.data,(0,2,3,1))
    print(self.data.shape)
    print('Done loading block data')

    n = self.data.shape[0]
    cutoff = n/1 #changed from 10 to 5
   # self.data = data[:-cutoff] if train else data[-cutoff:]
    self.transform = transform

def __getitem__(self, index):
    img = self.data[index]
    if self.transform is not None:
        img = self.transform(img)
    label = 0
    return img, label

def __len__(self):
    return len(self.data)

It throws up the following error :

RuntimeError: output with shape [1, 32, 32] doesn't match the broadcast shape [3, 32, 32]

How to resolve this ?


问:
Reviews showing on the reviewer's own profile page instead of the profile that it was written on
I am adding a simple review function on my Social platform Django project, where Users can write a review on another user's profile. But after posting the review, it's only showing on the profile page of the user that I'm currently signed in to.

This is my models.py

```<code>  ` class Review(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    reviewmsg = models.TextField(null=True, blank=True)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.reviewmsg)`
</code>```

views.py

```<code>  ` def userProfile(request, pk):
    user = User.objects.get(id=pk)
    rooms = user.room_set.all()
    reviews = user.review_set.all()

    if request.method == 'POST':
        review = Review.objects.create(
            user=request.user,
            reviewmsg=request.POST.get('reviewmsg')
        )
        return redirect('user-profile', pk=user.id)

    context = {'user':user, 'rooms':rooms, 'reviews':reviews}
    return render(request, 'pages/profile.html', context)`
</code>```

excerpt from my profile page template

```<code>  ` <div>
    {% for review in reviews %}
    <div class="comment-sect" style="margin-top: 0.5rem;">

    <div class="comment-photo" style="margin: auto;">
    <a href="{% url 'user-profile' review.user.id %}">
    <div class="profile-photo">
    <img src="{{review.user.avatar.url}}">
    </div>
    </a>
    </div>

    <div class="comment-info" style="width: 300px;">

    <small>@{{review.user}}</small>
    <small>{{review.created|timesince}} ago </small>

    <p style="margin-bottom:0;">{{review.reviewmsg}}</p>

    </div>

    </div><!--end of comment-sect-->

    {% endfor %}

    <div class="comment-form" style="margin-top: 0.5rem; text-align:center;">
    <form method="POST" action="">
    {% csrf_token %}

    <div>Submit a Review
    <input type="text" name="reviewmsg" placeholder="What do you think about this User?"/>

    </div>
    </form>
    </div>`
</code>```

EDITED
As mentioned by @lain Shelvington, I agree that I need to add another ForeignKey to my models. I tried updating the models.py to:

```<code>     user = models.ForeignKey(User, on_delete=models.CASCADE)

 class Review(models.Model):
     user = models.ForeignKey(User, on_delete=models.CASCADE)
     profile = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True)
     reviewmsg = models.TextField(null=True, blank=True)
     updated = models.DateTimeField(auto_now=True)
     created = models.DateTimeField(auto_now_add=True)

     def __str__(self):
         return str(self.reviewmsg)
</code>```

and views.py to:

```<code>         user = User.objects.get(id=pk)
         rooms = user.room_set.all()
         reviews = user.review_set.all()

         if request.method == 'POST':
             review = Review.objects.create(
                 user=request.user,
                 profile=user,
                 reviewmsg=request.POST.get('reviewmsg')
             )
             return redirect('user-profile', pk=user.id)

         context = {'user':user, 'rooms':rooms, 'reviews':reviews}
         return render(request, 'pages/profile.html', context)
</code>```

but ended up with error:

ValueError at /profile/7/
Cannot assign "<User: celeste>": "Review.profile" must be a "Profile" instance

Body:
I am adding a simple review function on my Social platform Django project, where Users can write a review on another user's profile. But after posting the review, it's only showing on the profile page of the user that I'm currently signed in to.

This is my models.py

  ` class Review(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    reviewmsg = models.TextField(null=True, blank=True)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.reviewmsg)`

views.py

  ` def userProfile(request, pk):
    user = User.objects.get(id=pk)
    rooms = user.room_set.all()
    reviews = user.review_set.all()

    if request.method == 'POST':
        review = Review.objects.create(
            user=request.user,
            reviewmsg=request.POST.get('reviewmsg')
        )
        return redirect('user-profile', pk=user.id)

    context = {'user':user, 'rooms':rooms, 'reviews':reviews}
    return render(request, 'pages/profile.html', context)`

excerpt from my profile page template

  `

    {% for review in reviews %}

    @{{review.user}}
    {{review.created|timesince}} ago

{{review.reviewmsg}}

    {% endfor %}

    <form method="POST" action="">
    {% csrf_token %}

Submit a Review
    <input type="text" name="reviewmsg" placeholder="What do you think about this User?"/>

    </form>

`

EDITED
As mentioned by @lain Shelvington, I agree that I need to add another ForeignKey to my models. I tried updating the models.py to:

     user = models.ForeignKey(User, on_delete=models.CASCADE)

 class Review(models.Model):
     user = models.ForeignKey(User, on_delete=models.CASCADE)
     profile = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True)
     reviewmsg = models.TextField(null=True, blank=True)
     updated = models.DateTimeField(auto_now=True)
     created = models.DateTimeField(auto_now_add=True)

     def __str__(self):
         return str(self.reviewmsg)

and views.py to:

         user = User.objects.get(id=pk)
         rooms = user.room_set.all()
         reviews = user.review_set.all()

         if request.method == 'POST':
             review = Review.objects.create(
                 user=request.user,
                 profile=user,
                 reviewmsg=request.POST.get('reviewmsg')
             )
             return redirect('user-profile', pk=user.id)

         context = {'user':user, 'rooms':rooms, 'reviews':reviews}
         return render(request, 'pages/profile.html', context)

but ended up with error:

ValueError at /profile/7/
Cannot assign "<User: celeste>": "Review.profile" must be a "Profile" instance


问:
How do I 'destroy' a sprite with a timer or stopwatch? (TechSmart)
I already destroyed sprites in previous lines, and coded a timer, but now it won't work.
time check for 3 secs so the screen will change

I tried to use the same method, I deleted some things, changed previous lines, but the sprites will not delete within the timer.
using the same method to destroy two sprites


问:
Can't open xls with python "AssertionError"
I'm trying to open an xls file from a site and I can't open, when i download in my local machine it opens fine with LibreOffice.

```<code>import requests
from bs4 import BeautifulSoup
import pandas as pd

resp = requests.get('https://www.prefeitura.sp.gov.br/cidade/secretarias/upload/02FEV2021.xls')
with open('test1.xls', 'wb') as output:
    output.write(resp.content)

pd.read_excel('/content/test1.xls')
</code>```

AssertionError

Tried with openpyxl

```<code>from openpyxl import load_workbook
wb = load_workbook('/content/test1.xls')
</code>```

Error: InvalidFileException: openpyxl does not support the old .xls file format, please use xlrd to read this file, or convert it to the more recent .xlsx file format.

And with xlrd

```<code>import xlrd
wb = xlrd.open_workbook('/content/test1.xls')
</code>```

AssertionError

Body:
I'm trying to open an xls file from a site and I can't open, when i download in my local machine it opens fine with LibreOffice.

import requests
from bs4 import BeautifulSoup
import pandas as pd

resp = requests.get('https://www.prefeitura.sp.gov.br/cidade/secretarias/upload/02FEV2021.xls')
with open('test1.xls', 'wb') as output:
    output.write(resp.content)

pd.read_excel('/content/test1.xls')

AssertionError

Tried with openpyxl

from openpyxl import load_workbook
wb = load_workbook('/content/test1.xls')

Error: InvalidFileException: openpyxl does not support the old .xls file format, please use xlrd to read this file, or convert it to the more recent .xlsx file format.

And with xlrd

import xlrd
wb = xlrd.open_workbook('/content/test1.xls')

AssertionError


问:
Is it possible to use AWS service account in dotnet application instead AWS credentials
Currently, my dotnet application is using AWS credentials but I would like to replace it with service account token. I don't see a way to do that in AWS documentation.</p>


问:
$lookup and $group on Mongodb Aggregation
So i have an document of answers from user with structure like this:

[{
  "_id": {
    "$oid": "636e685d1e1b4aa82f7e87c7"
  },
  "userId": {
    "$oid": "6369b17b11e02557349d8e37"
  },
  "formId": {
    "$oid": "6361d3bf914c7e5a21efa190"
  },
  "title": "Order Kerja Produksi (KSNI)",
  "username": "22000510",
  "date": "2022-11-11",
  "createdAt": 1668180061,
  "updatedAt": 1668180061,
  "__v": 0,
  "position": "Foreman",
  "department": "Production"
},
{
  "_id": {
    "$oid": "636e699c1e1b4aa82f7e87cb"
  },
  "userId": {
    "$oid": "6369b17b11e02557349d8e37"
  },
  "formId": {
    "$oid": "6361d3bf914c7e5a21efa190"
  },
  "title": "Order Kerja Produksi (KSNI)",
  "username": "22000510",
  "date": "2022-11-11",
  "createdAt": 1668180380,
  "updatedAt": 1668180380,
  "__v": 0,
  "department": "Production",
  "position": "Foreman"
},
{
  "_id": {
    "$oid": "636e6ace1e1b4aa82f7e87cf"
  },
  "userId": {
    "$oid": "6369b17b11e02557349d8e37"
  },
  "formId": {
    "$oid": "6361d3bf914c7e5a21efa190"
  },
  "title": "Order Kerja Produksi (KSNI)",
  "username": "22000510",
  "date": "2022-11-11",
  "createdAt": 1668180686,
  "updatedAt": 1668180686,
  "__v": 0,
  "department": "Production",
  "position": "Foreman"
}
]
```
<p>each NIK has assigned with SPV on the Users document, that have structure like this:</p>
<pre class="lang-js prettyprint-override"><code>{
  "_id": {
    "$oid": "6369b17b11e02557349d8de6"
  },
  "password": "$2b$10$whBbgZRMsIMCgKy/EJAwXefSdZNnrK5b.cSOYXTqu7g5a2uwCddKm",
  "NIK": "19000298",
  "department": "Production",
  "__v": 0,
  "createdAt": 1667871099,
  "updatedAt": 1667871099,
  "plant": "RANC",
  "Gedung_Zona": "No Status",
  "SPV": "JAMJAM J",
  "Sector": "2"
},
{
  "_id": {
    "$oid": "6369b17b11e02557349d8de7"
  },
  "password": "$2b$10$whBbgZRMsIMCgKy/EJAwXefSdZNnrK5b.cSOYXTqu7g5a2uwCddKm",
  "NIK": "20000100",
  "Group_Shift": "R1",
  "role": "user",
  "__v": 0,
  "createdAt": 1667871099,
  "updatedAt": 1670974129,
  "plant": "RANC",
  "Gedung_Zona": "No Status",
  "SPV": "JAMJAM J",
  "Sector": "3"
},
]
</code>```

I want to aggregate the answers from answers document with condition from users document where condition like this:

{$match:{SPV:"SPV_name"}}
```
<p>Is that a possible way to produce it into this kind of response with condition above using <code>$lookup</code> and <code>$group</code>?</p>
<p>If thats possible any help on how to produce that?</p>
<p>any help will be very thankful</p>
<p>Here is what i want the response from the query..</p>
<pre class="lang-js prettyprint-override"><code>{
  _id:1243135421412,
  formId:123123123123,
  title:"title of the question",
  username:22004627,
  date:2022-10-10,
  createdAt:1234125525,
  SPV:"SPV_NAME",
},
{
  _id:1243135421412,
  formId:123123123123,
  title:"title of the question",
  username:22004777,
  date:2022-10-12,
  createdAt:1234125525,
  SPV:"SPV_NAME",
}
</code>```

here is my try but it keeps returning error :

```<code>MongoServerError: Expression $arrayElemAt takes exactly 2 arguments. 1 were passed in.
</code>```

Here is my try:

```<code>db.answers.aggregate([{$lookup:{from:"users",pipeline:[{$match:{SPV:"JAMJAM JAMALUDIN"}}],as:"data"}}])
</code>```

Body:
So i have an document of answers from user with structure like this:

[{
  "_id": {
    "$oid": "636e685d1e1b4aa82f7e87c7"
  },
  "userId": {
    "$oid": "6369b17b11e02557349d8e37"
  },
  "formId": {
    "$oid": "6361d3bf914c7e5a21efa190"
  },
  "title": "Order Kerja Produksi (KSNI)",
  "username": "22000510",
  "date": "2022-11-11",
  "createdAt": 1668180061,
  "updatedAt": 1668180061,
  "__v": 0,
  "position": "Foreman",
  "department": "Production"
},
{
  "_id": {
    "$oid": "636e699c1e1b4aa82f7e87cb"
  },
  "userId": {
    "$oid": "6369b17b11e02557349d8e37"
  },
  "formId": {
    "$oid": "6361d3bf914c7e5a21efa190"
  },
  "title": "Order Kerja Produksi (KSNI)",
  "username": "22000510",
  "date": "2022-11-11",
  "createdAt": 1668180380,
  "updatedAt": 1668180380,
  "__v": 0,
  "department": "Production",
  "position": "Foreman"
},
{
  "_id": {
    "$oid": "636e6ace1e1b4aa82f7e87cf"
  },
  "userId": {
    "$oid": "6369b17b11e02557349d8e37"
  },
  "formId": {
    "$oid": "6361d3bf914c7e5a21efa190"
  },
  "title": "Order Kerja Produksi (KSNI)",
  "username": "22000510",
  "date": "2022-11-11",
  "createdAt": 1668180686,
  "updatedAt": 1668180686,
  "__v": 0,
  "department": "Production",
  "position": "Foreman"
}
]

each NIK has assigned with SPV on the Users document, that have structure like this:

{
  "_id": {
    "$oid": "6369b17b11e02557349d8de6"
  },
  "password": "$2b$10$whBbgZRMsIMCgKy/EJAwXefSdZNnrK5b.cSOYXTqu7g5a2uwCddKm",
  "NIK": "19000298",
  "department": "Production",
  "__v": 0,
  "createdAt": 1667871099,
  "updatedAt": 1667871099,
  "plant": "RANC",
  "Gedung_Zona": "No Status",
  "SPV": "JAMJAM J",
  "Sector": "2"
},
{
  "_id": {
    "$oid": "6369b17b11e02557349d8de7"
  },
  "password": "$2b$10$whBbgZRMsIMCgKy/EJAwXefSdZNnrK5b.cSOYXTqu7g5a2uwCddKm",
  "NIK": "20000100",
  "Group_Shift": "R1",
  "role": "user",
  "__v": 0,
  "createdAt": 1667871099,
  "updatedAt": 1670974129,
  "plant": "RANC",
  "Gedung_Zona": "No Status",
  "SPV": "JAMJAM J",
  "Sector": "3"
},
]

I want to aggregate the answers from answers document with condition from users document where condition like this:

{$match:{SPV:"SPV_name"}}

Is that a possible way to produce it into this kind of response with condition above using $lookup and $group?

If thats possible any help on how to produce that?

any help will be very thankful

Here is what i want the response from the query..

{
  _id:1243135421412,
  formId:123123123123,
  title:"title of the question",
  username:22004627,
  date:2022-10-10,
  createdAt:1234125525,
  SPV:"SPV_NAME",
},
{
  _id:1243135421412,
  formId:123123123123,
  title:"title of the question",
  username:22004777,
  date:2022-10-12,
  createdAt:1234125525,
  SPV:"SPV_NAME",
}

here is my try but it keeps returning error :

MongoServerError: Expression $arrayElemAt takes exactly 2 arguments. 1 were passed in.

Here is my try:

db.answers.aggregate([{$lookup:{from:"users",pipeline:[{$match:{SPV:"JAMJAM JAMALUDIN"}}],as:"data"}}])


问:
Is there a utPLSQL way to mock dependencies like in other unit testing frameworks?
In tSQLt, you can isolate dependencies for unit testing using procedures like FakeTable to create a dummy version of whatever your test subject depends on, that contains only data you specify. This is just like using Justmock or Moq in .NET unit testing.

The only thing remotely close to this that I've seen for utPLSQL is copying the dependencies to a temp version in the setup procedure, creating the dummy version manually, and then replacing it with the temp version in the teardown, all using EXECUTE IMMEDIATE.

Is there a more convenient way to do this, short of just creating a procedure to do this myself?


问:
R Shiny -- Error in readLines: 'con' is not a connection
I am trying to run the following code, but keep getting this error:

Error in readLines: 'con' is not a connection

The following is my program:

```<code>library(shiny)
library(shinyFiles)

ui <- fluidPage(
sidebarLayout(

sidebarPanel(
width = 2,
fileInput("file1", "Choose the first HTML File", accept = ".html")
),

    mainPanel(
      p("File Name"),
      verbatimTextOutput("file_name"),
      htmlOutput(outputId = 'result')
    )

)
)

server <- function(input, output) {
  file <- reactive({input$file1})
  req(file)
   if(is.null( reactive(input$file1$datapath))) return(NULL)
  rawHTML <- reactive(paste(readLines(input$file1$datapath), collapse="\n"))

  output$file_name <- renderText({
    print(rawHTML)
  })

  output$result <- renderUI({
    getPage<-function() {
      return(includeHTML( input$file1$datapath))
    }
    output$inc<-renderUI({getPage()})
  })

}

runApp(list(ui = ui, server = server), launch.browser =T)
</code>```

I want to read the html code from an external file, and save the code as a string.  Is there a solution for this?

Body:
I am trying to run the following code, but keep getting this error:

Error in readLines: 'con' is not a connection

The following is my program:

library(shiny)
library(shinyFiles)

ui <- fluidPage(
sidebarLayout(

sidebarPanel(
width = 2,
fileInput("file1", "Choose the first HTML File", accept = ".html")
),

    mainPanel(
      p("File Name"),
      verbatimTextOutput("file_name"),
      htmlOutput(outputId = 'result')
    )

)
)

server <- function(input, output) {
  file <- reactive({input$file1})
  req(file)
   if(is.null( reactive(input$file1$datapath))) return(NULL)
  rawHTML <- reactive(paste(readLines(input$file1$datapath), collapse="\n"))

  output$file_name <- renderText({
    print(rawHTML)
  })

  output$result <- renderUI({
    getPage<-function() {
      return(includeHTML( input$file1$datapath))
    }
    output$inc<-renderUI({getPage()})
  })

}

runApp(list(ui = ui, server = server), launch.browser =T)

I want to read the html code from an external file, and save the code as a string.  Is there a solution for this?


问:
Exception when use future and promise in the same thread
I got an exception when using a future and a promise in the same thread, while using c++20.

The exception is throwed when prom.set_value(111);

```<code>terminate called after throwing an instance of 'std::system_error'
  what():  Unknown error -1
</code>```
```<code>#include <future>
#include <iostream>

int main() {
  std::promise<int> prom;
  std::future<int> fut = prom.get_future();
  std::cout << "1 ok" << std::endl;
  prom.set_value(111);
  std::cout << "2 ok" << std::endl;
  std::cout << fut.get() << std::endl;
  return 0;
}
</code>```

Run the above code on https://onlinegdb.com/gZp3cOOvj

Body:
I got an exception when using a future and a promise in the same thread, while using c++20.

The exception is throwed when prom.set_value(111);

terminate called after throwing an instance of 'std::system_error'
  what():  Unknown error -1

#include <future>
#include <iostream>

int main() {
  std::promise<int> prom;
  std::future<int> fut = prom.get_future();
  std::cout << "1 ok" << std::endl;
  prom.set_value(111);
  std::cout << "2 ok" << std::endl;
  std::cout << fut.get() << std::endl;
  return 0;
}

Run the above code on https://onlinegdb.com/gZp3cOOvj


问:
I can not configure out "red color" tag for ejs file in vscode
I am configuring node.js project in VScode.
I installed some packages for node project and react.

but when I added ejs template file, it shows me red color at the beginning tag "<%".

screenshot here

I want to make it perfect. it looks bad.


问:
Add hyperlink to AnchoredText
I have made a diagram with matplotlib and added AnchoredText for labeling. I want to add hyperlinks to these labels, but not in a way that the whole label is a hyperlink - say, only a certain word of the label.

I know that I can use the url parameter in AnchoredText, but this is what makes the whole label a hyperlink, which is what I'm trying to avoid.

```<code>from matplotlib import pyplot as plt
from matplotlib.offsetbox import AnchoredText, AnnotationBbox, TextArea

fig_width = 16
fig_height = 9

fig = plt.figure(figsize=(fig_width, fig_height))

fig.add_axes(
    (0, 0, 1, 1),
    alpha=1,
    xticks=[],
    yticks=[],
)

fig.get_axes()[-1].set_xlim(0, fig_width)
fig.get_axes()[-1].set_ylim(0, fig_height)

fig.add_axes(
    (0.1, 0.1, 0.4, 0.4),
    alpha=1,
    xticks=[],
    yticks=[],
)

axis = fig.get_axes()[-1]

label = AnchoredText(
        s="Click here",
        frameon=False,
        loc="upper left",
        prop=dict(url="https://www.google.com"),
    )

axis.add_artist(label)

fig.savefig('diagram.svg')
</code>```

In this case, let's say I want only the word "here" to be clickable out of the "Click here" AnchoredText.

I have looked at other, related, questions already but none address this specific problem. Perhaps there isn't a way to do this, I'm just not sure what other approach to take.

Title: Add hyperlink to AnchoredText

Body:
I have made a diagram with matplotlib and added AnchoredText for labeling. I want to add hyperlinks to these labels, but not in a way that the whole label is a hyperlink - say, only a certain word of the label.

I know that I can use the url parameter in AnchoredText, but this is what makes the whole label a hyperlink, which is what I'm trying to avoid.

from matplotlib import pyplot as plt
from matplotlib.offsetbox import AnchoredText, AnnotationBbox, TextArea

fig_width = 16
fig_height = 9

fig = plt.figure(figsize=(fig_width, fig_height))

fig.add_axes(
    (0, 0, 1, 1),
    alpha=1,
    xticks=[],
    yticks=[],
)

fig.get_axes()[-1].set_xlim(0, fig_width)
fig.get_axes()[-1].set_ylim(0, fig_height)

fig.add_axes(
    (0.1, 0.1, 0.4, 0.4),
    alpha=1,
    xticks=[],
    yticks=[],
)

axis = fig.get_axes()[-1]

label = AnchoredText(
        s="Click here",
        frameon=False,
        loc="upper left",
        prop=dict(url="https://www.google.com"),
    )

axis.add_artist(label)

fig.savefig('diagram.svg')

In this case, let's say I want only the word "here" to be clickable out of the "Click here" AnchoredText.

I have looked at other, related, questions already but none address this specific problem. Perhaps there isn't a way to do this, I'm just not sure what other approach to take.


问:
SQL Server 2019 Can't create external table for a CSV file in Azure Storage Blob: An unexpected error has occurred while creating or attaching to JVM
I have loaded a test CSV file to the Azure Storage Blob container. I followed the MS instructions to create the DATABASE SCOPED CREDENTIAL, EXTERNAL DATA SOURCE then EXTERNAL TABLE.

I got the following error when I tried to create the EXTERNAL TABLE:

```<code>Msg 105019, Level 16, State 1, Line 67
External file access failed due to internal error: 'Error occurred while accessing HDFS: An unexpected error has occurred while creating or attaching to JVM. Details: System.DllNotFoundException: Unable to load DLL 'jvm.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
   at JNI.JavaVM.JNI_GetCreatedJavaVMs(IntPtr& pVM, Int32 jSize1, Int32& jSize2)
   at Microsoft.SqlServer.DataWarehouse.Hadoop.HadoopBridge.JavaBridge.LoadOrAttachJVM()'
</code>```

I have reinstall JDK on the server, but it won't help.

Body:
I have loaded a test CSV file to the Azure Storage Blob container. I followed the MS instructions to create the DATABASE SCOPED CREDENTIAL, EXTERNAL DATA SOURCE then EXTERNAL TABLE.

I got the following error when I tried to create the EXTERNAL TABLE:

Msg 105019, Level 16, State 1, Line 67
External file access failed due to internal error: 'Error occurred while accessing HDFS: An unexpected error has occurred while creating or attaching to JVM. Details: System.DllNotFoundException: Unable to load DLL 'jvm.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
   at JNI.JavaVM.JNI_GetCreatedJavaVMs(IntPtr& pVM, Int32 jSize1, Int32& jSize2)
   at Microsoft.SqlServer.DataWarehouse.Hadoop.HadoopBridge.JavaBridge.LoadOrAttachJVM()'

I have reinstall JDK on the server, but it won't help.


问:
Getting multiple columns from TWO tables using a WHERE EXISTS statement
I'm trying to use two name column's in tables and find the similarities/differences using SQL Server. I would like to print a list of students Table 1 that are not present in Table 2, along with all their respective scores and grade. However I am having trouble populating multiple columns with my current script. My script does not populate the test scores but instead prints only NULL values. I've included the table format's and where I am with my both script's so far. Right now, all the score fields are printing NULL values even when they have populated fields in Table2.

TABLE_1_Today's_List

Name1

Kevin

James

Roger

Bob

TABLE_2_Combined_Scores

Name2
Grade
Score_1
Score_2
Score_3
Score_4

Kevin
10
25
34
12
45

Bob
9
25
23
65
87

Roger
10
43
54
25
98

James
12
43
54
25
98

Students in Table 1 that are also in Table 2:

```<code>SELECT c.Name1, Score_1,Score_2,Score_3,Score_4
FROM TABLE_1_Today's_List c
WHERE EXISTS (SELECT c2.Name2,Score_1,Score_2,Score_3,Score_4
FROM TABLE_2_Combined_Scores c2
WHERE c2.Name2 = c.Name1
and Grade = '10');
</code>```

^This script returns NULL values for all the Score fields but correctly maps the students in both tables. I would like to populate the the Score fields with the results from Table2

Students in Table 1 that are not in Table 2:

```<code>SELECT c.Name1, Score_1,Score_2,Score_3,Score_4
FROM TABLE_1_Today's_List c
WHERE NOT EXISTS (SELECT c2.Name2,Score_1,Score_2,Score_3,Score_4
FROM TABLE_2_Combined_Scores c2
WHERE c2.Name2 = c.Name1
and Grade = '10');
</code>```

^This script returns NULL values for all the Score fields but correctly maps the students in table1 but not table2. I would like to populate the the Score fields with the results from Table2

Ideal Output:

Name1
Score_1
Score_2
Score_3
Score_4

Kevin
25
34
12
45

Roger
43
54
25
98

Body:
I'm trying to use two name column's in tables and find the similarities/differences using SQL Server. I would like to print a list of students Table 1 that are not present in Table 2, along with all their respective scores and grade. However I am having trouble populating multiple columns with my current script. My script does not populate the test scores but instead prints only NULL values. I've included the table format's and where I am with my both script's so far. Right now, all the score fields are printing NULL values even when they have populated fields in Table2.

TABLE_1_Today's_List

Name1

Kevin

James

Roger

Bob

TABLE_2_Combined_Scores

Name2
Grade
Score_1
Score_2
Score_3
Score_4

Kevin
10
25
34
12
45

Bob
9
25
23
65
87

Roger
10
43
54
25
98

James
12
43
54
25
98

Students in Table 1 that are also in Table 2:

SELECT c.Name1, Score_1,Score_2,Score_3,Score_4
FROM TABLE_1_Today's_List c
WHERE EXISTS (SELECT c2.Name2,Score_1,Score_2,Score_3,Score_4
FROM TABLE_2_Combined_Scores c2
WHERE c2.Name2 = c.Name1
and Grade = '10');

^This script returns NULL values for all the Score fields but correctly maps the students in both tables. I would like to populate the the Score fields with the results from Table2

Students in Table 1 that are not in Table 2:

SELECT c.Name1, Score_1,Score_2,Score_3,Score_4
FROM TABLE_1_Today's_List c
WHERE NOT EXISTS (SELECT c2.Name2,Score_1,Score_2,Score_3,Score_4
FROM TABLE_2_Combined_Scores c2
WHERE c2.Name2 = c.Name1
and Grade = '10');

^This script returns NULL values for all the Score fields but correctly maps the students in table1 but not table2. I would like to populate the the Score fields with the results from Table2

Ideal Output:

Name1
Score_1
Score_2
Score_3
Score_4

Kevin
25
34
12
45

Roger
43
54
25
98


问:
Uncaught (in promise) IntegrationError: Please call Stripe() with your publishable key. You used an empty string
I'm assuming next.js isn't picking up the variables in my .env file? But I don't know how to fix that. Please and thank you for your time!

stripe.js

```<code>import Stripe from 'stripe';

const stripe = new Stripe(process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY);
</code>```

getStripe.js

```<code>import { loadStripe } from '@stripe/stripe-js';

let stripePromise;

const getStripe = () => {
  if (!stripePromise) {
    stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY);
  }

  return stripePromise;
}

export default getStripe;
</code>```

.env

```<code>NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY = *******

NEXT_PUBLIC_STRIPE_SECRET_KEY = *********
</code>```

I've seen from similar posts that maybe I just need to change the .env file to ".env.local" but I tried that and it didn't seem to work. I just  changed the name on the file, are there more steps to that?

I've also tried clearing the cache, restarting the whole project.

Body:
I'm assuming next.js isn't picking up the variables in my .env file? But I don't know how to fix that. Please and thank you for your time!

stripe.js

import Stripe from 'stripe';

const stripe = new Stripe(process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY);

getStripe.js

import { loadStripe } from '@stripe/stripe-js';

let stripePromise;

const getStripe = () => {
  if (!stripePromise) {
    stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY);
  }

  return stripePromise;
}

export default getStripe;

.env

NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY = *******

NEXT_PUBLIC_STRIPE_SECRET_KEY = *********

I've seen from similar posts that maybe I just need to change the .env file to ".env.local" but I tried that and it didn't seem to work. I just  changed the name on the file, are there more steps to that?

I've also tried clearing the cache, restarting the whole project.


问:
Avoid Select options to be duplicated in vuejs
I am getting duplicate options in a multi select dropdown (select2).
I have a parent and a child select dropdowns. Everytime I select child option its parent gets populated too.
Eg : With Category & Subcategory dropdowns if I select 2 subcat from same category, its category gets populated twice.

<select style="width: 100%" multiple v-model="item.host_groups" v-select2 class="form-control select2" v-bind:id="'tmp_hostgroup_'+index" >
<option v-for=" option in hosts.host_mapping" v-if="item.hosts.includes(option.host_name)" :value="option.host_group" :key="option.host_group">@{{ option.host_group }}</option>
</select>
```
<p>I have binded the value but still, see duplicates.</p>
<p>As in the screenshot below everytime I select Item that belong to same group the Item Group gets selected multiple times ending up with duplicates (AA in pic)</p>
<p><img src="https://i.stack.imgur.com/Y5gyd.png" alt="enter image description here" /></p>
<p>I also have onchange of select2</p>
```     directives: {
                select2: {
                    inserted: function(el) {
                        $(el).select2({
                            width: 'resolve',
                            allowClear: true,
                        }).on('select2:select', function() {
                            const event = new Event('change', {bubbles : true, cancelable: true}) ;
                            el.dispatchEvent(event);
                        });
                    }
                },
```

Body:
I am getting duplicate options in a multi select dropdown (select2).
I have a parent and a child select dropdowns. Everytime I select child option its parent gets populated too.
Eg : With Category & Subcategory dropdowns if I select 2 subcat from same category, its category gets populated twice.

<select style="width: 100%" multiple v-model="item.host_groups" v-select2 class="form-control select2" v-bind:id="'tmp_hostgroup_'+index" >
<option v-for=" option in hosts.host_mapping" v-if="item.hosts.includes(option.host_name)" :value="option.host_group" :key="option.host_group">@{{ option.host_group }}</option>
</select>

I have binded the value but still, see duplicates.

As in the screenshot below everytime I select Item that belong to same group the Item Group gets selected multiple times ending up with duplicates (AA in pic)

I also have onchange of select2

     directives: {
                select2: {
                    inserted: function(el) {
                        $(el).select2({
                            width: 'resolve',
                            allowClear: true,
                        }).on('select2:select', function() {
                            const event = new Event('change', {bubbles : true, cancelable: true}) ;
                            el.dispatchEvent(event);
                        });
                    }
                },


问:
How to get Stochastic Gradient Descent result in contour plot
```<code>import numpy as np
from matplotlib import pyplot as plt
xk = np.linspace(-1,1,100)
yk= 2 * xk + 3 + np.random.rand(len(xk))
x1,x2 = np.meshgrid(xk,yk)

F = (x1 - 2) ** 2 + 2 * (x2 - 3) ** 2
fig=plt.figure()
surf = fig.add_subplot(1,1,1, projection='3d')
surf.plot_surface(x1,x2,F)
surf.contour(x1,x2,F)

fig, surf=plt.subplots()
plt.contour(x1, x2, F, 20)

m = 0
c = 0
learning_rate=0.01

</code>```

I think my problem to get the correct result is from here, but I cant find where is the problem

```<code>for k in range(10):
    shuffel_index=np.random.permutation(len(xk))
    xk = xk[shuffel_index]
    yk = yk[shuffel_index]
    for i in range(len(xk)):
       grad_m = - 2 * xk[i] * (yk[i] - (np.dot(m,xk[i]) + c))
       grad_c = - 2 * (yk[i] - (np.dot(m,xk[i])+c))
       m = m - learning_rate * grad_m
       c = c - learning_rate * grad_c
       surf.plot(np.array([xk[0], yk[0]]),np.array([xk[1], yk[1]]),'ko-')
       if (k != 10 or i != len(xk)):
         surf.plot(np.array([xk[0], yk[0]]),np.array([xk[1], yk[1]]),'ko-')
    plt.show()
</code>```

This is my result for the above code

And I wish to get the result like I do for gradient descent algorithm. The example of my gradient descent result.

May I know where is my error?

Body:
import numpy as np
from matplotlib import pyplot as plt
xk = np.linspace(-1,1,100)
yk= 2 * xk + 3 + np.random.rand(len(xk))
x1,x2 = np.meshgrid(xk,yk)

F = (x1 - 2) ** 2 + 2 * (x2 - 3) ** 2
fig=plt.figure()
surf = fig.add_subplot(1,1,1, projection='3d')
surf.plot_surface(x1,x2,F)
surf.contour(x1,x2,F)

fig, surf=plt.subplots()
plt.contour(x1, x2, F, 20)

m = 0
c = 0
learning_rate=0.01

I think my problem to get the correct result is from here, but I cant find where is the problem

for k in range(10):
    shuffel_index=np.random.permutation(len(xk))
    xk = xk[shuffel_index]
    yk = yk[shuffel_index]
    for i in range(len(xk)):
       grad_m = - 2 * xk[i] * (yk[i] - (np.dot(m,xk[i]) + c))
       grad_c = - 2 * (yk[i] - (np.dot(m,xk[i])+c))
       m = m - learning_rate * grad_m
       c = c - learning_rate * grad_c
       surf.plot(np.array([xk[0], yk[0]]),np.array([xk[1], yk[1]]),'ko-')
       if (k != 10 or i != len(xk)):
         surf.plot(np.array([xk[0], yk[0]]),np.array([xk[1], yk[1]]),'ko-')
    plt.show()

This is my result for the above code

And I wish to get the result like I do for gradient descent algorithm. The example of my gradient descent result.

May I know where is my error?


问:
Take effect from step 1 to step 3 wizard
I'm currently using twitter bootstrap wizard as this template, so my wizard structure is something like this:

```<code>form
      step1
        checkbox
        button next
      step2
        inputs
        button next
      step3
      submit
</code>```

The checkboxes are defined as:

```<code>@{
                    foreach (var test in @Html.GetEnumSelectList<length>())
                    {
                        <div class="form-check form-check-inline mb-3">
                            <input id="@test.Text" type="checkbox" value="@test.Value" name="selectedTest" class="form-check-input">
                            <label for="@test.Text" class="form-check-label">@test.Text</label>
                        </div>
                    }
                }
</code>```

So I want to get change step 3, style: none to style: block if one of these checkboxes is checked as:

```<code>    <script>
    let id;

                $("input[type=checkbox]").on("change", function () {
                    id = $(this).attr("id");
                    const text = document.getElementById(id);
                    if ($(this).is(":checked")) {
                        text.style.display = "block";
                    }
                    else
                    {
                        text.style.display = "none";
                        const IsChecked = $("input[type=checkbox]");
                        let show = "none";
                        for (let i = 0; i < IsChecked.length; i++) {
                            if (IsChecked[i].checked) {
                                show = "block";
                            }
                            break;
                        }
                    }
                })
      </script>
</code>```

But oh surprise, the HTML of step 3 is not available yet until I go to step 3, how can tell step 1 to do the change into step 3 when the checkbox of step 1 is checked?

Body:
I'm currently using twitter bootstrap wizard as this template, so my wizard structure is something like this:

form
      step1
        checkbox
        button next
      step2
        inputs
        button next
      step3
      submit

The checkboxes are defined as:

@{
                    foreach (var test in @Html.GetEnumSelectList<length>())
                    {

                            <input id="@test.Text" type="checkbox" value="@test.Value" name="selectedTest" class="form-check-input">
                            @test.Text

                    }
                }

So I want to get change step 3, style: none to style: block if one of these checkboxes is checked as:

But oh surprise, the HTML of step 3 is not available yet until I go to step 3, how can tell step 1 to do the change into step 3 when the checkbox of step 1 is checked?


问:
How to determine if a jar is an uber-jar？
Once we get a jar, how do we determine whether it is a normal jar or an uber-jar?

Is there an automated way to tell, other than by looking at them one by one?


问:
Getting 0 Unknown Error on Angular/Cordova app for Android
I have an Angular app that works fine in browser then used Cordova to make an apk from that, when I check this app the login is visible but when I try to enter I get this error:

I tried several solutions from other posts:

1.- android:usesCleartextTraffic="true" in AndroidManifest.xml

2.- cleartextTrafficPermitted in a network_security_config.xml file and including it in AndroidManifest.xml

3.- Added all this in config.xml:

<access origin="*" />
<allow-navigation href="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />```

4.- Added a configNotWorking.xml file

5.- remove platform (android) and adding it again

But none of them seems to be working

What could be the issue and how can I solve it?

Thanks.

Ps: Im kinda new with Cordova but I used it a couple of times for html5 apps with no problem

Body:
I have an Angular app that works fine in browser then used Cordova to make an apk from that, when I check this app the login is visible but when I try to enter I get this error:

I tried several solutions from other posts:

1.- android:usesCleartextTraffic="true" in AndroidManifest.xml

2.- cleartextTrafficPermitted in a network_security_config.xml file and including it in AndroidManifest.xml

3.- Added all this in config.xml:

<access origin="*" />
<allow-navigation href="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />

4.- Added a configNotWorking.xml file

5.- remove platform (android) and adding it again

But none of them seems to be working

What could be the issue and how can I solve it?

Thanks.

Ps: Im kinda new with Cordova but I used it a couple of times for html5 apps with no problem


问:
Hibernate merge adds instance to database in contrast to update
Hibernate session.update() is deprecated and the recommended function to use is merge().
Update() only updates the database if an entry with the primary key exists and throws an exception if not. Merge() adds a new instance if the entry is not in the database.

Is there a similar method to update() which only updates the database if the entry exists and throws an exception otherwise?


问:
Get availableAudioDeviceList React Native
I'm using react-native-incall-manager and React-Native-WebRTC to make audio calls.
I want to know the available audio device list to choose an audio route.
I was only discovered:

Event {"availableAudioDeviceList": "["WIRED_HEADSET","EARPIECE","SPEAKER_PHONE"]", "selectedAudioDevice": "EARPIECE"}

when call

```<code>      DeviceEventEmitter.addListener('onAudioDeviceChanged', function (data) {
        console.log('Event', data);
      });
</code>```

I just want to know

availableAudioDeviceList

without listener event. How can I do that?
Thank you.

Body:
I'm using react-native-incall-manager and React-Native-WebRTC to make audio calls.
I want to know the available audio device list to choose an audio route.
I was only discovered:

Event {"availableAudioDeviceList": "["WIRED_HEADSET","EARPIECE","SPEAKER_PHONE"]", "selectedAudioDevice": "EARPIECE"}

when call

      DeviceEventEmitter.addListener('onAudioDeviceChanged', function (data) {
        console.log('Event', data);
      });

I just want to know

availableAudioDeviceList

without listener event. How can I do that?
Thank you.


问:
Redocly OpenAPI structure error. Property `openapi` is not expected here
I am trying to create an api documentation using redocly.

On my openapi.yaml it is linking to a yaml that has the api docs called kpi-documentation.yaml

link/$ref in openapi.yaml

```<code>  /kpiDocumentation:
    $ref: paths/kpi-documentation.yaml
</code>```

I have an error in my visual studio code redocly preview extension that says

```<code>We found structural problems in your definition, please check the files below before running the preview.
File: /Users/xx/Desktop/Projects/api-docs/openapi/paths/kpi-documentation.yaml
Problem: Property `openapi` is not expected here.

File: /Users/xx/Desktop/Projects/api-docs/openapi/paths/kpi-documentation.yaml
Problem: Property `info` is not expected here.

File: /Users/xx/Desktop/Projects/api-docs/openapi/paths/kpi-documentation.yaml
Problem: Property `paths` is not expected here.

File: /Users/xx/Desktop/Projects/api-docs/openapi/paths/kpi-documentation.yaml
Problem: Property `components` is not expected here.
</code>```

Part of code that I have in the kpi-documentation.yaml that appears to be throwing the error is

```<code>openapi: "3.1"
info:
  title: KPI API
  version: '1.0'
  description: Documentation of API endpoints of KPI
servers:
  - url: https://api.redocly.com
paths:
</code>```

I have checked the documentation on the redocly website and it looks like my yaml structure is fine.

Also to note the kpi-documentation previews fine by itself when using the preview, but not when I preview the openapi.yaml which is the root file that needs to work.

https://redocly.com/docs/openapi-visual-reference/openapi/#OAS-3.0

rootfile

openapi.yaml

```<code>openapi: 3.1.0
info:
  version: 1.0.0
  title: KPI API documentation
  termsOfService: 'https://example.com/terms/'
  contact:
    name: Brendan
    url: 'http://example.com/contact'
  license:
    name: Apache 2.0
    url: 'http://www.apache.org/licenses/LICENSE-2.0.html'
  x-logo:
    url: 'https://www.feedgy.solar/wp-content/uploads/2022/07/Sans-titre-1.png'
tags:
  - name: Insert Service 1
    description: Example echo operations.
  - name: Insert Service 2
    description: Operations about users.
  - name: Insert Service 3
    description: This is a tag description.
  - name: Insert Service 4
    description: This is a tag description.
servers:
  - url: 'https://{tenant}/api/v1'
    variables:
      tenant:
        default: www
        description: Your tenant id
  - url: 'https://example.com/api/v1'
paths:
  '/users/{username}':
    $ref: 'paths/users_{username}.yaml'
  /echo:
    $ref: paths/echo.yaml
  /pathItem:
    $ref: paths/path-item.yaml
  /pathItemWithExamples:
    $ref: paths/path-item-with-examples.yaml
  /kpiDocumentation:
    $ref: 'paths/kpi-documentation.yaml'
</code>```

pathitem file

kpi-documentation.yaml

```<code>openapi: "3.1"
info:
  title: KPI API
  version: '1.0'
  description: Documentation of API endpoints of KPI
servers:
  - url: https://api.redocly.com
paths:
  "/api/v1/corrected-performance-ratio/plants/{id}":
    get:
      summary: Same as the Performance Ratio, but the ratio is done using Corrected Reference Yield, so it considers thermal losses in the panels as normal. The WCPR represents the losses in the BoS (balance of system), so everything from the panel DC output to the AC output.
      operationId: corrected_performance_ratio_plants_retrieve
      parameters:
        - in: query
          name: date_end
          schema:
            type: string
            format: date
          required: true
        - in: query
          name: date_start
          schema:
            type: string
            format: date
          required: true
        - in: query
          name: frequency
          schema:
            enum:
              - H
              - D
              - M
              - Y
            type: string
            default: H
            minLength: 1
        - in: path
          name: id
          schema:
            type: integer
          description: A unique integer value identifying this plant.
          required: true
        - in: query
          name: threshold
          schema:
            type: integer
            default: 50
      tags:
        - corrected-performance-ratio
      security:
        - tokenAuth: []
        - cookieAuth: []
        - {}
      responses:
        "200":
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/KPIResponse"
          description: ""
  "/api/v1/corrected-performance-ratio/plants/{id}/inverters":
</code>```

Body:
I am trying to create an api documentation using redocly.

On my openapi.yaml it is linking to a yaml that has the api docs called kpi-documentation.yaml

link/$ref in openapi.yaml

  /kpiDocumentation:
    $ref: paths/kpi-documentation.yaml

I have an error in my visual studio code redocly preview extension that says

We found structural problems in your definition, please check the files below before running the preview.
File: /Users/xx/Desktop/Projects/api-docs/openapi/paths/kpi-documentation.yaml
Problem: Property `openapi` is not expected here.

File: /Users/xx/Desktop/Projects/api-docs/openapi/paths/kpi-documentation.yaml
Problem: Property `info` is not expected here.

File: /Users/xx/Desktop/Projects/api-docs/openapi/paths/kpi-documentation.yaml
Problem: Property `paths` is not expected here.

File: /Users/xx/Desktop/Projects/api-docs/openapi/paths/kpi-documentation.yaml
Problem: Property `components` is not expected here.

Part of code that I have in the kpi-documentation.yaml that appears to be throwing the error is

openapi: "3.1"
info:
  title: KPI API
  version: '1.0'
  description: Documentation of API endpoints of KPI
servers:
  - url: https://api.redocly.com
paths:

I have checked the documentation on the redocly website and it looks like my yaml structure is fine.

Also to note the kpi-documentation previews fine by itself when using the preview, but not when I preview the openapi.yaml which is the root file that needs to work.

https://redocly.com/docs/openapi-visual-reference/openapi/#OAS-3.0

rootfile

openapi.yaml

openapi: 3.1.0
info:
  version: 1.0.0
  title: KPI API documentation
  termsOfService: 'https://example.com/terms/'
  contact:
    name: Brendan
    url: 'http://example.com/contact'
  license:
    name: Apache 2.0
    url: 'http://www.apache.org/licenses/LICENSE-2.0.html'
  x-logo:
    url: 'https://www.feedgy.solar/wp-content/uploads/2022/07/Sans-titre-1.png'
tags:
  - name: Insert Service 1
    description: Example echo operations.
  - name: Insert Service 2
    description: Operations about users.
  - name: Insert Service 3
    description: This is a tag description.
  - name: Insert Service 4
    description: This is a tag description.
servers:
  - url: 'https://{tenant}/api/v1'
    variables:
      tenant:
        default: www
        description: Your tenant id
  - url: 'https://example.com/api/v1'
paths:
  '/users/{username}':
    $ref: 'paths/users_{username}.yaml'
  /echo:
    $ref: paths/echo.yaml
  /pathItem:
    $ref: paths/path-item.yaml
  /pathItemWithExamples:
    $ref: paths/path-item-with-examples.yaml
  /kpiDocumentation:
    $ref: 'paths/kpi-documentation.yaml'

pathitem file

kpi-documentation.yaml

openapi: "3.1"
info:
  title: KPI API
  version: '1.0'
  description: Documentation of API endpoints of KPI
servers:
  - url: https://api.redocly.com
paths:
  "/api/v1/corrected-performance-ratio/plants/{id}":
    get:
      summary: Same as the Performance Ratio, but the ratio is done using Corrected Reference Yield, so it considers thermal losses in the panels as normal. The WCPR represents the losses in the BoS (balance of system), so everything from the panel DC output to the AC output.
      operationId: corrected_performance_ratio_plants_retrieve
      parameters:
        - in: query
          name: date_end
          schema:
            type: string
            format: date
          required: true
        - in: query
          name: date_start
          schema:
            type: string
            format: date
          required: true
        - in: query
          name: frequency
          schema:
            enum:
              - H
              - D
              - M
              - Y
            type: string
            default: H
            minLength: 1
        - in: path
          name: id
          schema:
            type: integer
          description: A unique integer value identifying this plant.
          required: true
        - in: query
          name: threshold
          schema:
            type: integer
            default: 50
      tags:
        - corrected-performance-ratio
      security:
        - tokenAuth: []
        - cookieAuth: []
        - {}
      responses:
        "200":
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/KPIResponse"
          description: ""
  "/api/v1/corrected-performance-ratio/plants/{id}/inverters":


问:
Failed to create provisioning profile, "personel team" keyword lost

personel team" lost. and not working

failed to create provisioning profile. There are no devices registered in your account on the developer website. Select a device run destination to have Xcode register it.

how to fix this ı spend 2 day..