问:
Wordpress how can we get the featured image or other attached media from post
I am trying to get the featured image of my custom post type. I also have attachments in my custom post however I am not able to see the data. Am I using the wrong query method? In my json output I see general information however it is missing information such as feature image link.

```<code>add_filter("wcra_pictures_callback", "wcra_pictures_callback_handler");

function wcra_pictures_callback_handler($param) {
  //$param = All GET/POST values will be received from endpoint

    // WP QUERY
    $query = new WP_Query([
        'post_type' => $param['post_type'],
        'author' => $param['user_id'],
        'author_name' => $param['author'],
        'orderby' => $param['orderby'],
        'order'   => $param['order'],
        'posts_per_page' => $param['posts_per_page'],
    ]);

    // // Get Posts
    // $posts = get_posts([
    //     'post_type' => $param['post_type'],
    //     'author' => $param['user_id'],
    //     'author_name' => $param['author'],
    //     'orderby' => $param['orderby'],
    //     'order'   => $param['order'],
    //     'posts_per_page' => $param['posts_per_page'],
    // ]);

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

current out does not include data showing any attachments or links or feature image. How can I get that information.

```<code>{
   "status": "OK",
   "response": "Response OK",
   "code": 200,
   "data": {
       "query": {
           "post_type": "picture",
           "author": null,
           "author_name": null,
           "orderby": null,
           "order": null,
           "posts_per_page": null
       },
       "query_vars": {
           "post_type": "picture",
           "author": "",
           "author_name": "",
           "orderby": null,
           "order": "DESC",
           "posts_per_page": 10,
           "error": "",
           "m": "",
           "p": 0,
           "post_parent": "",
           "subpost": "",
           "subpost_id": "",
           "attachment": "",
           "attachment_id": 0,
           "name": "",
           "pagename": "",
           "page_id": 0,
           "second": "",
           "minute": "",
           "hour": "",
           "day": 0,
           "monthnum": 0,
           "year": 0,
           "w": 0,
           "category_name": "",
           "tag": "",
           "cat": "",
           "tag_id": "",
           "feed": "",
           "tb": "",
           "paged": 0,
           "meta_key": "",
           "meta_value": "",
           "preview": "",
           "s": "",
           "sentence": "",
           "title": "",
           "fields": "",
           "menu_order": "",
           "embed": "",
           "category__in": [],
           "category__not_in": [],
           "category__and": [],
           "post__in": [],
           "post__not_in": [],
           "post_name__in": [],
           "tag__in": [],
           "tag__not_in": [],
           "tag__and": [],
           "tag_slug__in": [],
           "tag_slug__and": [],
           "post_parent__in": [],
           "post_parent__not_in": [],
           "author__in": [],
           "author__not_in": [],
           "ignore_sticky_posts": false,
           "suppress_filters": false,
           "cache_results": true,
           "update_post_term_cache": true,
           "lazy_load_term_meta": true,
           "update_post_meta_cache": true,
           "nopaging": false,
           "comments_per_page": "50",
           "no_found_rows": false
       },
       "tax_query": {
           "queries": [],
           "relation": "AND",
           "queried_terms": [],
           "primary_table": "SQTSXGdhposts",
           "primary_id_column": "ID"
       },
       "meta_query": {
           "queries": [],
           "relation": null,
           "meta_table": null,
           "meta_id_column": null,
           "primary_table": null,
           "primary_id_column": null
       },
       "date_query": false,
       "request": "SELECT SQL_CALC_FOUND_ROWS DISTINCT SQTSXGdhposts.ID FROM SQTSXGdhposts  LEFT JOIN SQTSXGdhpostmeta AS myarmjoin ON (SQTSXGdhposts.ID = myarmjoin.post_id AND myarmjoin.meta_key = 'arm_access_plan' )  WHERE 1=1  AND ((SQTSXGdhposts.post_type = 'picture' AND (SQTSXGdhposts.post_status = 'publish' OR SQTSXGdhposts.post_status = 'acf-disabled'))) AND ( myarmjoin.post_id IS NULL )  ORDER BY SQTSXGdhposts.post_date DESC LIMIT 0, 10",
       "posts": [
           {
               "ID": 254,
               "post_author": "2",
               "post_date": "2022-02-07 16:53:39",
               "post_date_gmt": "2022-02-07 16:53:39",
               "post_content": "",
               "post_title": "Aurora_BG_7",
               "post_excerpt": "",
               "post_status": "publish",
               "comment_status": "open",
               "ping_status": "closed",
               "post_password": "",
               "post_name": "aurora_bg_7",
               "to_ping": "",
               "pinged": "",
               "post_modified": "2022-02-07 16:53:39",
               "post_modified_gmt": "2022-02-07 16:53:39",
               "post_content_filtered": "",
               "post_parent": 0,
               "guid": "https://cloud.elmc.app/picture/aurora_bg_7",
               "menu_order": 0,
               "post_type": "picture",
               "post_mime_type": "",
               "comment_count": "0",
               "filter": "raw"
           },
           {
               "ID": 249,
               "post_author": "2",
               "post_date": "2022-02-07 16:46:58",
               "post_date_gmt": "2022-02-07 16:46:58",
               "post_content": "",
               "post_title": "134909",
               "post_excerpt": "",
               "post_status": "publish",
               "comment_status": "open",
               "ping_status": "closed",
               "post_password": "",
               "post_name": "134909",
               "to_ping": "",
               "pinged": "",
               "post_modified": "2022-02-07 16:46:58",
               "post_modified_gmt": "2022-02-07 16:46:58",
               "post_content_filtered": "",
               "post_parent": 0,
               "guid": "https://cloud.elmc.app/picture/134909",
               "menu_order": 0,
               "post_type": "picture",
               "post_mime_type": "",
               "comment_count": "0",
               "filter": "raw"
           },
           {
               "ID": 147,
               "post_author": "1",
               "post_date": "2022-02-06 21:36:28",
               "post_date_gmt": "2022-02-06 21:36:28",
               "post_content": "",
               "post_title": "Scene 4 On",
               "post_excerpt": "",
               "post_status": "publish",
               "comment_status": "open",
               "ping_status": "closed",
               "post_password": "",
               "post_name": "scene-4-on",
               "to_ping": "",
               "pinged": "",
               "post_modified": "2022-02-06 21:36:28",
               "post_modified_gmt": "2022-02-06 21:36:28",
               "post_content_filtered": "",
               "post_parent": 0,
               "guid": "https://cloud.elmc.app/picture/scene-4-on",
               "menu_order": 0,
               "post_type": "picture",
               "post_mime_type": "",
               "comment_count": "0",
               "filter": "raw"
           },
           {
               "ID": 142,
               "post_author": "2",
               "post_date": "2022-02-06 03:49:57",
               "post_date_gmt": "2022-02-06 03:49:57",
               "post_content": "",
               "post_title": "No_video",
               "post_excerpt": "",
               "post_status": "publish",
               "comment_status": "open",
               "ping_status": "closed",
               "post_password": "",
               "post_name": "no_video",
               "to_ping": "",
               "pinged": "",
               "post_modified": "2022-02-06 03:49:57",
               "post_modified_gmt": "2022-02-06 03:49:57",
               "post_content_filtered": "",
               "post_parent": 0,
               "guid": "https://cloud.elmc.app/picture/no_video",
               "menu_order": 0,
               "post_type": "picture",
               "post_mime_type": "",
               "comment_count": "0",
               "filter": "raw"
           }
       ],
       "post_count": 4,
       "current_post": -1,
       "in_the_loop": false,
       "post": {
           "ID": 254,
           "post_author": "2",
           "post_date": "2022-02-07 16:53:39",
           "post_date_gmt": "2022-02-07 16:53:39",
           "post_content": "",
           "post_title": "Aurora_BG_7",
           "post_excerpt": "",
           "post_status": "publish",
           "comment_status": "open",
           "ping_status": "closed",
           "post_password": "",
           "post_name": "aurora_bg_7",
           "to_ping": "",
           "pinged": "",
           "post_modified": "2022-02-07 16:53:39",
           "post_modified_gmt": "2022-02-07 16:53:39",
           "post_content_filtered": "",
           "post_parent": 0,
           "guid": "https://cloud.elmc.app/picture/aurora_bg_7",
           "menu_order": 0,
           "post_type": "picture",
           "post_mime_type": "",
           "comment_count": "0",
           "filter": "raw"
       },
       "comment_count": 0,
       "current_comment": -1,
       "found_posts": 4,
       "max_num_pages": 1,
       "max_num_comment_pages": 0,
       "is_single": false,
       "is_preview": false,
       "is_page": false,
       "is_archive": true,
       "is_date": false,
       "is_year": false,
       "is_month": false,
       "is_day": false,
       "is_time": false,
       "is_author": false,
       "is_category": false,
       "is_tag": false,
       "is_tax": false,
       "is_search": false,
       "is_feed": false,
       "is_comment_feed": false,
       "is_trackback": false,
       "is_home": false,
       "is_privacy_policy": false,
       "is_404": false,
       "is_embed": false,
       "is_paged": false,
       "is_admin": false,
       "is_attachment": false,
       "is_singular": false,
       "is_robots": false,
       "is_favicon": false,
       "is_posts_page": false,
       "is_post_type_archive": true,
       "thumbnails_cached": false
   }
}
</code>```

答:
You use the_post_thumbnail to output a featured image of a post while inside a while loop where you are changing the current post (by calling $query->the_post())

Outside of a 'WordPress' loop you can use get_the_post_thumbnail which accepts a post id as the first parameter.

Examples

Please note, in the two first examples the functions return the image within an  tag, not the url of the image.

This would be suited to your situation as you have an instance of WP_Query to loop through.

$query = new WP_Query($args);

while($query->have_posts()){
    $query->the_post();
    the_post_thumbnail('full', ['class' => 'my image classes']); // 'full' is original uploaded size I believe.

    // Need image as a variable?
    // $image = get_the_post_thumbnail(get_the_ID(), 'full', ['class' => 'my image class'];
}
wp_reset_postdata(); // reset usage of 'the_post()'
```
<p>Alternative: iterate using <code>foreach</code> on the array of posts.</p>
<pre class="lang-php prettyprint-override"><code>$query = new WP_Query($args);

$posts = $query->posts; // now an array of posts
foreach($posts as $post){
    $image = get_the_post_thumbnail($post->ID, 'full', ['class' => 'my image classes'];
}
</code>```

Obtaining image URL string only

// Inside 'WordPress' loop
$image = get_the_post_thumbnail_url(get_the_ID(), 'full');

// Inside foreach loop
$image = get_the_post_thumbnail_url($post->ID, 'full);
```

Documentation references

get_the_post_thumbnail

get_the_post_thumbnail_url

the_post_thumbnail

WP_Query

Explanation of 'the_post' functionality

Body:
I am trying to get the featured image of my custom post type. I also have attachments in my custom post however I am not able to see the data. Am I using the wrong query method? In my json output I see general information however it is missing information such as feature image link.

add_filter("wcra_pictures_callback", "wcra_pictures_callback_handler");

function wcra_pictures_callback_handler($param) {
  //$param = All GET/POST values will be received from endpoint

    // WP QUERY
    $query = new WP_Query([
        'post_type' => $param['post_type'],
        'author' => $param['user_id'],
        'author_name' => $param['author'],
        'orderby' => $param['orderby'],
        'order'   => $param['order'],
        'posts_per_page' => $param['posts_per_page'],
    ]);

    // // Get Posts
    // $posts = get_posts([
    //     'post_type' => $param['post_type'],
    //     'author' => $param['user_id'],
    //     'author_name' => $param['author'],
    //     'orderby' => $param['orderby'],
    //     'order'   => $param['order'],
    //     'posts_per_page' => $param['posts_per_page'],
    // ]);

  return $query;
}

current out does not include data showing any attachments or links or feature image. How can I get that information.

{
   "status": "OK",
   "response": "Response OK",
   "code": 200,
   "data": {
       "query": {
           "post_type": "picture",
           "author": null,
           "author_name": null,
           "orderby": null,
           "order": null,
           "posts_per_page": null
       },
       "query_vars": {
           "post_type": "picture",
           "author": "",
           "author_name": "",
           "orderby": null,
           "order": "DESC",
           "posts_per_page": 10,
           "error": "",
           "m": "",
           "p": 0,
           "post_parent": "",
           "subpost": "",
           "subpost_id": "",
           "attachment": "",
           "attachment_id": 0,
           "name": "",
           "pagename": "",
           "page_id": 0,
           "second": "",
           "minute": "",
           "hour": "",
           "day": 0,
           "monthnum": 0,
           "year": 0,
           "w": 0,
           "category_name": "",
           "tag": "",
           "cat": "",
           "tag_id": "",
           "feed": "",
           "tb": "",
           "paged": 0,
           "meta_key": "",
           "meta_value": "",
           "preview": "",
           "s": "",
           "sentence": "",
           "title": "",
           "fields": "",
           "menu_order": "",
           "embed": "",
           "category__in": [],
           "category__not_in": [],
           "category__and": [],
           "post__in": [],
           "post__not_in": [],
           "post_name__in": [],
           "tag__in": [],
           "tag__not_in": [],
           "tag__and": [],
           "tag_slug__in": [],
           "tag_slug__and": [],
           "post_parent__in": [],
           "post_parent__not_in": [],
           "author__in": [],
           "author__not_in": [],
           "ignore_sticky_posts": false,
           "suppress_filters": false,
           "cache_results": true,
           "update_post_term_cache": true,
           "lazy_load_term_meta": true,
           "update_post_meta_cache": true,
           "nopaging": false,
           "comments_per_page": "50",
           "no_found_rows": false
       },
       "tax_query": {
           "queries": [],
           "relation": "AND",
           "queried_terms": [],
           "primary_table": "SQTSXGdhposts",
           "primary_id_column": "ID"
       },
       "meta_query": {
           "queries": [],
           "relation": null,
           "meta_table": null,
           "meta_id_column": null,
           "primary_table": null,
           "primary_id_column": null
       },
       "date_query": false,
       "request": "SELECT SQL_CALC_FOUND_ROWS DISTINCT SQTSXGdhposts.ID FROM SQTSXGdhposts  LEFT JOIN SQTSXGdhpostmeta AS myarmjoin ON (SQTSXGdhposts.ID = myarmjoin.post_id AND myarmjoin.meta_key = 'arm_access_plan' )  WHERE 1=1  AND ((SQTSXGdhposts.post_type = 'picture' AND (SQTSXGdhposts.post_status = 'publish' OR SQTSXGdhposts.post_status = 'acf-disabled'))) AND ( myarmjoin.post_id IS NULL )  ORDER BY SQTSXGdhposts.post_date DESC LIMIT 0, 10",
       "posts": [
           {
               "ID": 254,
               "post_author": "2",
               "post_date": "2022-02-07 16:53:39",
               "post_date_gmt": "2022-02-07 16:53:39",
               "post_content": "",
               "post_title": "Aurora_BG_7",
               "post_excerpt": "",
               "post_status": "publish",
               "comment_status": "open",
               "ping_status": "closed",
               "post_password": "",
               "post_name": "aurora_bg_7",
               "to_ping": "",
               "pinged": "",
               "post_modified": "2022-02-07 16:53:39",
               "post_modified_gmt": "2022-02-07 16:53:39",
               "post_content_filtered": "",
               "post_parent": 0,
               "guid": "https://cloud.elmc.app/picture/aurora_bg_7",
               "menu_order": 0,
               "post_type": "picture",
               "post_mime_type": "",
               "comment_count": "0",
               "filter": "raw"
           },
           {
               "ID": 249,
               "post_author": "2",
               "post_date": "2022-02-07 16:46:58",
               "post_date_gmt": "2022-02-07 16:46:58",
               "post_content": "",
               "post_title": "134909",
               "post_excerpt": "",
               "post_status": "publish",
               "comment_status": "open",
               "ping_status": "closed",
               "post_password": "",
               "post_name": "134909",
               "to_ping": "",
               "pinged": "",
               "post_modified": "2022-02-07 16:46:58",
               "post_modified_gmt": "2022-02-07 16:46:58",
               "post_content_filtered": "",
               "post_parent": 0,
               "guid": "https://cloud.elmc.app/picture/134909",
               "menu_order": 0,
               "post_type": "picture",
               "post_mime_type": "",
               "comment_count": "0",
               "filter": "raw"
           },
           {
               "ID": 147,
               "post_author": "1",
               "post_date": "2022-02-06 21:36:28",
               "post_date_gmt": "2022-02-06 21:36:28",
               "post_content": "",
               "post_title": "Scene 4 On",
               "post_excerpt": "",
               "post_status": "publish",
               "comment_status": "open",
               "ping_status": "closed",
               "post_password": "",
               "post_name": "scene-4-on",
               "to_ping": "",
               "pinged": "",
               "post_modified": "2022-02-06 21:36:28",
               "post_modified_gmt": "2022-02-06 21:36:28",
               "post_content_filtered": "",
               "post_parent": 0,
               "guid": "https://cloud.elmc.app/picture/scene-4-on",
               "menu_order": 0,
               "post_type": "picture",
               "post_mime_type": "",
               "comment_count": "0",
               "filter": "raw"
           },
           {
               "ID": 142,
               "post_author": "2",
               "post_date": "2022-02-06 03:49:57",
               "post_date_gmt": "2022-02-06 03:49:57",
               "post_content": "",
               "post_title": "No_video",
               "post_excerpt": "",
               "post_status": "publish",
               "comment_status": "open",
               "ping_status": "closed",
               "post_password": "",
               "post_name": "no_video",
               "to_ping": "",
               "pinged": "",
               "post_modified": "2022-02-06 03:49:57",
               "post_modified_gmt": "2022-02-06 03:49:57",
               "post_content_filtered": "",
               "post_parent": 0,
               "guid": "https://cloud.elmc.app/picture/no_video",
               "menu_order": 0,
               "post_type": "picture",
               "post_mime_type": "",
               "comment_count": "0",
               "filter": "raw"
           }
       ],
       "post_count": 4,
       "current_post": -1,
       "in_the_loop": false,
       "post": {
           "ID": 254,
           "post_author": "2",
           "post_date": "2022-02-07 16:53:39",
           "post_date_gmt": "2022-02-07 16:53:39",
           "post_content": "",
           "post_title": "Aurora_BG_7",
           "post_excerpt": "",
           "post_status": "publish",
           "comment_status": "open",
           "ping_status": "closed",
           "post_password": "",
           "post_name": "aurora_bg_7",
           "to_ping": "",
           "pinged": "",
           "post_modified": "2022-02-07 16:53:39",
           "post_modified_gmt": "2022-02-07 16:53:39",
           "post_content_filtered": "",
           "post_parent": 0,
           "guid": "https://cloud.elmc.app/picture/aurora_bg_7",
           "menu_order": 0,
           "post_type": "picture",
           "post_mime_type": "",
           "comment_count": "0",
           "filter": "raw"
       },
       "comment_count": 0,
       "current_comment": -1,
       "found_posts": 4,
       "max_num_pages": 1,
       "max_num_comment_pages": 0,
       "is_single": false,
       "is_preview": false,
       "is_page": false,
       "is_archive": true,
       "is_date": false,
       "is_year": false,
       "is_month": false,
       "is_day": false,
       "is_time": false,
       "is_author": false,
       "is_category": false,
       "is_tag": false,
       "is_tax": false,
       "is_search": false,
       "is_feed": false,
       "is_comment_feed": false,
       "is_trackback": false,
       "is_home": false,
       "is_privacy_policy": false,
       "is_404": false,
       "is_embed": false,
       "is_paged": false,
       "is_admin": false,
       "is_attachment": false,
       "is_singular": false,
       "is_robots": false,
       "is_favicon": false,
       "is_posts_page": false,
       "is_post_type_archive": true,
       "thumbnails_cached": false
   }
}

Body:
You use the_post_thumbnail to output a featured image of a post while inside a while loop where you are changing the current post (by calling $query->the_post())

Outside of a 'WordPress' loop you can use get_the_post_thumbnail which accepts a post id as the first parameter.

Examples

Please note, in the two first examples the functions return the image within an  tag, not the url of the image.

This would be suited to your situation as you have an instance of WP_Query to loop through.

$query = new WP_Query($args);

while($query->have_posts()){
    $query->the_post();
    the_post_thumbnail('full', ['class' => 'my image classes']); // 'full' is original uploaded size I believe.

    // Need image as a variable?
    // $image = get_the_post_thumbnail(get_the_ID(), 'full', ['class' => 'my image class'];
}
wp_reset_postdata(); // reset usage of 'the_post()'

Alternative: iterate using foreach on the array of posts.

$query = new WP_Query($args);

$posts = $query->posts; // now an array of posts
foreach($posts as $post){
    $image = get_the_post_thumbnail($post->ID, 'full', ['class' => 'my image classes'];
}

Obtaining image URL string only

// Inside 'WordPress' loop
$image = get_the_post_thumbnail_url(get_the_ID(), 'full');

// Inside foreach loop
$image = get_the_post_thumbnail_url($post->ID, 'full);

Documentation references

get_the_post_thumbnail

get_the_post_thumbnail_url

the_post_thumbnail

WP_Query

Explanation of 'the_post' functionality


来源: stackexchange

问:
Can I configure a turn on/off on a GKE node?
I have a GKE cluster with 1 node-pool and 2 nodes in it, one with node affinity to only accept pods of production and the other to development and testing pods. For financial purposes, I want to configure like a cronJob or something similar on the dev/test node so I can spend less money but I don't know if that's possible.</p>

答:
Yes, it is possible. But you should separate production and development nodes into different pools. Then you can fire up a cronjob, target that to come up in the production pool, and use that to perform the following actions:

Turn off autoscaling on the development pool (if you use autoscaling, that is)

Set the node pool size of the development pool to 0

Remember to fire up another cronjob to reverse the steps:

Scale up development pool to 1

Enable autoscaling on the development pool

ContentLicense: CC BY-SA 4.0


问:
rxjs trigger one observable before the other one conditionaly
I am seeking for help or a clue for an issue with rxjs that I am not able to solve.

Basically, I want to trigger an observable and complete before the original one trigger.

Case: I am working on a project in which I have two profiles, say profileA, profileB.
Sometimes profileA has some properties that I need to pass to the profileB in order to get the profileB. And at the end, I combine the both profiles and return the orignal observable.

Usually, I cache the profileA in localStorage and I can get the profileB.

```<code>getProfileB() {
  const url = `${..}/xyz/${this.profileB.username}/userData`
  return this.http.get(anUrl); // and returns the observale to the next destination
}
</code>```

But sometimes could be that the profileA is not available in the localstorage, so in that case, first I have to find fetch the profileA and then continue with the profileB fetching.

I would like to use the following approch. Since I don't about

```<code>getProfileA() {
  return this.http.get(anUrlForProfileA);
}

getProfileB() {
  const url = `${..}/xyz/${this.profileB.username}/userData`
  return this.http.get(anUrl).pipe(
    aPipeOperator() => {
    // the null could be the mean that continue with the current Observable, whereas concatenateFirst means, first completes the getProfileA observable and then continue with the original one.
      return this.profileA?.username?.length > 0? concatenateFirst(this.getProfileA()) : null;

    }
  );
}
</code>```

I am little struggling with the rxjs, and it is also difficult for me to explain, so please help me. This issue could solve me other problems too.

Thanks

答:
[Edit]: Since you want to use your profileA in your profileB request, you should use SwitchMap, as Jason Goemaat said. Here is another example a bit different for a better beginner comprehension than his one :

export class AppComponent implements OnInit {
  ngOnInit() {
    this.getProfileB();
  }

  getProfileA(): Observable<{ name: string, profile: string }> {
    return of({ profile: "A", name: 'Quentin' });
  }

  getProfileB() {
    this.getProfileA().pipe(
      switchMap(profileA => {
        // ProfileA is completed, you can acces its value
        console.log(profileA);
        // return another observable (For you, your api call for ProfileB)
        return of({profile: "B", name: "John", profileA});
      }),
    ).subscribe(profileB => {
      // Get profileB value here
      console.log(profileB);
    })
  }
}
```
<hr />
<p>From your example, it looks like you could use <code>forkjoin()</code>. It wait for all the observables to complete before to continue, so you could so something like that:</p>
<pre class="lang-js prettyprint-override"><code>forkJoin(getProfileA(), this.http.get(anUrlForProfileB)).pipe(
  mergeMap(obs => { //... use obs[0] and obs[1] to access your observable values}
);
</code>```

Body:
I am seeking for help or a clue for an issue with rxjs that I am not able to solve.

Basically, I want to trigger an observable and complete before the original one trigger.

Case: I am working on a project in which I have two profiles, say profileA, profileB.
Sometimes profileA has some properties that I need to pass to the profileB in order to get the profileB. And at the end, I combine the both profiles and return the orignal observable.

Usually, I cache the profileA in localStorage and I can get the profileB.

getProfileB() {
  const url = `${..}/xyz/${this.profileB.username}/userData`
  return this.http.get(anUrl); // and returns the observale to the next destination
}

But sometimes could be that the profileA is not available in the localstorage, so in that case, first I have to find fetch the profileA and then continue with the profileB fetching.

I would like to use the following approch. Since I don't about

getProfileA() {
  return this.http.get(anUrlForProfileA);
}

getProfileB() {
  const url = `${..}/xyz/${this.profileB.username}/userData`
  return this.http.get(anUrl).pipe(
    aPipeOperator() => {
    // the null could be the mean that continue with the current Observable, whereas concatenateFirst means, first completes the getProfileA observable and then continue with the original one.
      return this.profileA?.username?.length > 0? concatenateFirst(this.getProfileA()) : null;

    }
  );
}

I am little struggling with the rxjs, and it is also difficult for me to explain, so please help me. This issue could solve me other problems too.

Thanks

Body:
[Edit]: Since you want to use your profileA in your profileB request, you should use SwitchMap, as Jason Goemaat said. Here is another example a bit different for a better beginner comprehension than his one :

export class AppComponent implements OnInit {
  ngOnInit() {
    this.getProfileB();
  }

  getProfileA(): Observable<{ name: string, profile: string }> {
    return of({ profile: "A", name: 'Quentin' });
  }

  getProfileB() {
    this.getProfileA().pipe(
      switchMap(profileA => {
        // ProfileA is completed, you can acces its value
        console.log(profileA);
        // return another observable (For you, your api call for ProfileB)
        return of({profile: "B", name: "John", profileA});
      }),
    ).subscribe(profileB => {
      // Get profileB value here
      console.log(profileB);
    })
  }
}

From your example, it looks like you could use forkjoin(). It wait for all the observables to complete before to continue, so you could so something like that:

forkJoin(getProfileA(), this.http.get(anUrlForProfileB)).pipe(
  mergeMap(obs => { //... use obs[0] and obs[1] to access your observable values}
);


问:
DRF: nested Serializer error on create argument after ** must be a mapping, not str
I have a model that connects a school model and a user model through a foreign key, and on creating if a student is being created I want the user foreign key to be set as the instance and also a school to be chosen by its id however i can't solve this error

```<code>TypeError at /api/users/student_register/
django.db.models.manager.BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method() argument after ** must be a mapping, not str

class User(AbstractBaseUser, PermissionsMixin):
     ....
    email = models.EmailField(
    is_superuser = models.BooleanField(default=False)
    last_login = models.DateTimeField(
        _("last login"), auto_now=True, auto_now_add=False)

class School(models.Model):

    PROVINCE = (
        ...
    )

    SCHOOLTYPE = (
       ....
    )
    name = models.CharField(_("Name"), max_length=150, blank=False, null=True)
    abbr = models.CharField(
        _("Abbrivation"), max_length=10, blank=False, null=True)
    zone = models.CharField(
        _("Zone"), max_length=50, choices=PROVINCE)
    Schooltype = models.CharField(
        _("School type"), max_length=50, choices=SCHOOLTYPE)
    schoolemail = models.EmailField(
        _("School email"), max_length=254, blank=False, null=True) editable=False)

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

this applied model is what is connecting the user and the student model together and it is what i am using though the nested serializer to create the users

```<code>class Applied(models.Model):
    class TYPES(models.TextChoices):
        STUDENT = "STUDENT", "Student"
        WORKER = "WORKER", "Worker"
    type = models.CharField(_("type"), choices=TYPES.choices,
                            max_length=150, blank=False, null=True)
    user = models.ForeignKey(User, verbose_name=_(
        "useris"), related_name='useris', on_delete=models.PROTECT, blank=True, null=True)
    school = models.ForeignKey(School, verbose_name=_(
        'school'), related_name="applied", on_delete=models.CASCADE, blank=True, null=True)
</code>```

serializers.py

```<code>class StudentSchoolSerializer(serializers.ModelSerializer):
    user = serializers.CharField()
    school = serializers.CharField()
    type = serializers.HiddenField(
        default=Applied.TYPES.STUDENT
    )

    class Meta:
        model = Applied
        fields = ['school', 'type', 'user']

# register a student
class RegisterSerializerStudent(serializers.ModelSerializer):
    applied = StudentSchoolSerializer(required=True)
    password = serializers.CharField(
        write_only=True, required=True, validators=[validate_password])
    firstname = serializers.CharField(required=True)
    middlename = serializers.CharField(required=True)
    lastname = serializers.CharField(required=True)

    class Meta:
        model = User
        fields = ('firstname', 'middlename', 'sex', 'grade', 'image', 'room', 'type', 'lastname', 'age', 'password',
                    'phone', 'applied')
        extra_kwargs = {'password': {'write_only': True},
                        'firstname': {'required': True},
                        'middelname': {'required': True},
                        'lastname': {'required': True},
                        'age': {'min_value': 1, 'max_value': 100}
                        }

    def create(self, validated_data):
        def create_new_id_number():
            S = 10
            not_unique = True
            while not_unique:
                unique_id = ''.join(random.choices(
                    string.ascii_uppercase + string.digits, k=S))
                if not User.objects.filter(student_id=unique_id):
                    not_unique = False
                return unique_id
        applied = validated_data.pop('applied')
        user = User.objects.create(
            student_id=create_new_id_number(),
            firstname=validated_data['firstname'],
            middlename=validated_data['middlename'],
            lastname=validated_data['lastname'],
            age=validated_data['age'],
            phone=validated_data['phone'],
            image=validated_data['image'],
            room=validated_data['room'],
            sex=validated_data['sex'],
            is_active='True',
            type=User.TYPES.STUDENT,
        )
        user.set_password(validated_data['password'])
        user.save()
        for applies in applied:
            Applied.objects.create(**applies, user=user)
        return user
</code>```

create method throws the error, creates a User instance but not the Applied instance

答:
applied = validated_data.pop('applied') contained the value of "applied" in your serializer. You did not call StudentSchoolSerializer with the many=true option. So when you do

for applies in applied:
    Applied.objects.create(**applies, user=user)
```

applies is actually a str, not a dict. So you can't use **.

If you are sending only one "applied", you can save it directly
Applied.objects.create(**applied, user=user)

Body:
I have a model that connects a school model and a user model through a foreign key, and on creating if a student is being created I want the user foreign key to be set as the instance and also a school to be chosen by its id however i can't solve this error

TypeError at /api/users/student_register/
django.db.models.manager.BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method() argument after ** must be a mapping, not str

class User(AbstractBaseUser, PermissionsMixin):
     ....
    email = models.EmailField(
    is_superuser = models.BooleanField(default=False)
    last_login = models.DateTimeField(
        _("last login"), auto_now=True, auto_now_add=False)

class School(models.Model):

    PROVINCE = (
        ...
    )

    SCHOOLTYPE = (
       ....
    )
    name = models.CharField(_("Name"), max_length=150, blank=False, null=True)
    abbr = models.CharField(
        _("Abbrivation"), max_length=10, blank=False, null=True)
    zone = models.CharField(
        _("Zone"), max_length=50, choices=PROVINCE)
    Schooltype = models.CharField(
        _("School type"), max_length=50, choices=SCHOOLTYPE)
    schoolemail = models.EmailField(
        _("School email"), max_length=254, blank=False, null=True) editable=False)

    def __str__(self):
        return self.name

this applied model is what is connecting the user and the student model together and it is what i am using though the nested serializer to create the users

class Applied(models.Model):
    class TYPES(models.TextChoices):
        STUDENT = "STUDENT", "Student"
        WORKER = "WORKER", "Worker"
    type = models.CharField(_("type"), choices=TYPES.choices,
                            max_length=150, blank=False, null=True)
    user = models.ForeignKey(User, verbose_name=_(
        "useris"), related_name='useris', on_delete=models.PROTECT, blank=True, null=True)
    school = models.ForeignKey(School, verbose_name=_(
        'school'), related_name="applied", on_delete=models.CASCADE, blank=True, null=True)

serializers.py

class StudentSchoolSerializer(serializers.ModelSerializer):
    user = serializers.CharField()
    school = serializers.CharField()
    type = serializers.HiddenField(
        default=Applied.TYPES.STUDENT
    )

    class Meta:
        model = Applied
        fields = ['school', 'type', 'user']

# register a student
class RegisterSerializerStudent(serializers.ModelSerializer):
    applied = StudentSchoolSerializer(required=True)
    password = serializers.CharField(
        write_only=True, required=True, validators=[validate_password])
    firstname = serializers.CharField(required=True)
    middlename = serializers.CharField(required=True)
    lastname = serializers.CharField(required=True)

    class Meta:
        model = User
        fields = ('firstname', 'middlename', 'sex', 'grade', 'image', 'room', 'type', 'lastname', 'age', 'password',
                    'phone', 'applied')
        extra_kwargs = {'password': {'write_only': True},
                        'firstname': {'required': True},
                        'middelname': {'required': True},
                        'lastname': {'required': True},
                        'age': {'min_value': 1, 'max_value': 100}
                        }

    def create(self, validated_data):
        def create_new_id_number():
            S = 10
            not_unique = True
            while not_unique:
                unique_id = ''.join(random.choices(
                    string.ascii_uppercase + string.digits, k=S))
                if not User.objects.filter(student_id=unique_id):
                    not_unique = False
                return unique_id
        applied = validated_data.pop('applied')
        user = User.objects.create(
            student_id=create_new_id_number(),
            firstname=validated_data['firstname'],
            middlename=validated_data['middlename'],
            lastname=validated_data['lastname'],
            age=validated_data['age'],
            phone=validated_data['phone'],
            image=validated_data['image'],
            room=validated_data['room'],
            sex=validated_data['sex'],
            is_active='True',
            type=User.TYPES.STUDENT,
        )
        user.set_password(validated_data['password'])
        user.save()
        for applies in applied:
            Applied.objects.create(**applies, user=user)
        return user

create method throws the error, creates a User instance but not the Applied instance

Body:
applied = validated_data.pop('applied') contained the value of "applied" in your serializer. You did not call StudentSchoolSerializer with the many=true option. So when you do

for applies in applied:
    Applied.objects.create(**applies, user=user)

applies is actually a str, not a dict. So you can't use **.

If you are sending only one "applied", you can save it directly
Applied.objects.create(**applied, user=user)


问:
How to find the average rating for each category within each group?
I have a dataframe that contains ratings for games and they are divided into categories and whether or not the game is a solo game or not.

```<code>category <- c("Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle")
solo <- c("solo","solo","solo","double","double","double","solo","solo","solo","double","double","double","solo","solo","solo","double","double","double")
rating <- c(8,7,6,5,3,3,2,1,10,3,4,5,6,3,2,1,3,1)
df <- as.data.frame(rating)
df$solo <- solo
df$category <- category
</code>```

My question is, how do I get the average rating for each category that belongs to each grouping (solo/double)? Solo Party and Double Party should have different avg ratings for example.

答:
After grouping by 'category' and 'solo', get the mean

```<code>library(dplyr)
df <- df %>%
  group_by(category, solo) %>%
  mutate(avg = mean(rating, na.rm = TRUE)) %>%
  ungroup
</code>```

-output

```<code>df
# A tibble: 18 × 4
   rating solo   category    avg
    <dbl> <chr>  <chr>     <dbl>
 1      8 solo   Party      5.33
 2      7 solo   Adventure  3.67
 3      6 solo   Puzzle     6
 4      5 double Party      3
 5      3 double Adventure  3.33
 6      3 double Puzzle     3
 7      2 solo   Party      5.33
 8      1 solo   Adventure  3.67
 9     10 solo   Puzzle     6
10      3 double Party      3
11      4 double Adventure  3.33
12      5 double Puzzle     3
13      6 solo   Party      5.33
14      3 solo   Adventure  3.67
15      2 solo   Puzzle     6
16      1 double Party      3
17      3 double Adventure  3.33
18      1 double Puzzle     3
</code>```

Body:
I have a dataframe that contains ratings for games and they are divided into categories and whether or not the game is a solo game or not.

category <- c("Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle")
solo <- c("solo","solo","solo","double","double","double","solo","solo","solo","double","double","double","solo","solo","solo","double","double","double")
rating <- c(8,7,6,5,3,3,2,1,10,3,4,5,6,3,2,1,3,1)
df <- as.data.frame(rating)
df$solo <- solo
df$category <- category

My question is, how do I get the average rating for each category that belongs to each grouping (solo/double)? Solo Party and Double Party should have different avg ratings for example.

Body:
After grouping by 'category' and 'solo', get the mean

library(dplyr)
df <- df %>%
  group_by(category, solo) %>%
  mutate(avg = mean(rating, na.rm = TRUE)) %>%
  ungroup

-output

df
# A tibble: 18 × 4
   rating solo   category    avg
    <dbl> <chr>  <chr>     <dbl>
 1      8 solo   Party      5.33
 2      7 solo   Adventure  3.67
 3      6 solo   Puzzle     6
 4      5 double Party      3
 5      3 double Adventure  3.33
 6      3 double Puzzle     3
 7      2 solo   Party      5.33
 8      1 solo   Adventure  3.67
 9     10 solo   Puzzle     6
10      3 double Party      3
11      4 double Adventure  3.33
12      5 double Puzzle     3
13      6 solo   Party      5.33
14      3 solo   Adventure  3.67
15      2 solo   Puzzle     6
16      1 double Party      3
17      3 double Adventure  3.33
18      1 double Puzzle     3


问:
Getting json keys from an array from an object using ArduinoJson
I'm having trouble getting the keys (and values) from "prefs" in the following json.

```<code>{
  "cmd": "set",
  "prefs": [
    {
      "coins": 4
    },
    {
      "enable": true
    }
  ]
}
</code>```

Code to process json:

```<code>    DynamicJsonDocument doc(1024);
    deserializeJson(doc,"{\"cmd\":\"set\",\"prefs\":[{\"coins\":4},{\"enable\":true}]}");
    JsonObject root=doc.as<JsonObject>();
    for (JsonPair kv : root) {
        Serial.println(kv.key().c_str());
        Serial.println(kv.value().as<char*>());
    }
    JsonObject prefs=doc["prefs"];
    for (JsonPair kv : prefs) {
        Serial.println("here\n");
        Serial.println(kv.key().c_str());
//        Serial.println(kv.value().as<const char*>());
    }
</code>```

I would expect to see the following output:

```<code>cmd
set
prefs
coins
enable
</code>```

But I only get what seems to be an empty prefs object:

```<code>cmd
set
prefs
</code>```

The example shown in the official docs almost gets me there, and is what I have in my code. This example from github is similar, but I can't seem to adapt it to my case.

答:
Since prefs is an array, convert it to JsonArray

JsonArray prefs = doc["prefs"].as<JsonArray>();
for (JsonObject a : prefs) {
    for (JsonPair kv : a) {
        Serial.println(kv.key().c_str());
        if (kv.value().is<int>()) {
            Serial.println(kv.value().as<int>());
        }
        else {
            Serial.println(kv.value().as<bool>());
        }
    }
}
```

Body:
I'm having trouble getting the keys (and values) from "prefs" in the following json.

{
  "cmd": "set",
  "prefs": [
    {
      "coins": 4
    },
    {
      "enable": true
    }
  ]
}

Code to process json:

    DynamicJsonDocument doc(1024);
    deserializeJson(doc,"{\"cmd\":\"set\",\"prefs\":[{\"coins\":4},{\"enable\":true}]}");
    JsonObject root=doc.as<JsonObject>();
    for (JsonPair kv : root) {
        Serial.println(kv.key().c_str());
        Serial.println(kv.value().as<char*>());
    }
    JsonObject prefs=doc["prefs"];
    for (JsonPair kv : prefs) {
        Serial.println("here\n");
        Serial.println(kv.key().c_str());
//        Serial.println(kv.value().as<const char*>());
    }

I would expect to see the following output:

cmd
set
prefs
coins
enable

But I only get what seems to be an empty prefs object:

cmd
set
prefs

The example shown in the official docs almost gets me there, and is what I have in my code. This example from github is similar, but I can't seem to adapt it to my case.


问:
Javascript function performance question with promises
I have two promises running at the end of the main code, but one runs in the catch using an arrow function and the other runs directly, do you know the difference between one and the other?

```<code>const main = async () => {
  const promisseTeste1 = () => new Promise((resolve, reject) => {
    reject("ERRO")
  });

  const promisseTeste2 = () => new Promise((resolve, reject) => {
    promisseTeste1().then().catch(reject)
  });

  // Method 1
  promisseTeste2().then().catch(console.log)

  // Method 2
  promisseTeste2().then().catch(e => console.log(e))
}

main()
</code>```

I wanted to know if there is any performance issue or even a possible problem that may occur using method 1.

答:
If you're using console.log, then in any browser that isn't utterly obsolete, there won't be an issue.

In some very old browsers, having console.log being called with something other than a calling context of console was an issue - but many would consider this not to be something worth worrying about.

For the general case of passing an already-declared function instead of creating an anonymous inline function, one potential gotcha is (similar to previously) the this value inside the callback if passing in / calling an object method. The this value will be the object when invoking it inline, and globalThis (or undefined in strict mode) if passing it in directly.

const obj = {
  prop: 'val',
  method() {
    console.log(this.prop);
  }
};

const main = async () => {
  // Method 1
  Promise.reject().then().catch(obj.method)

  // Method 2
  Promise.reject().then().catch(e => obj.method(e))
}

main()```

Although not related to the core of your question, as you see in the above snippet, I've avoided the explicit Promise construction antipattern, and recommend you do the same.

if there is any performance issue

Not remotely. Unless you're in a tight loop or doing multiple DOM manipulations, performance of a segment of code almost certainly isn't even worth considering - better to focus on code readability and maintainability.

For the even more general issue of doing .method(callback) instead of .method(value => callback(value)), be wary of functions whose behavior changes depending on how many arguments are passed in (which is why .map(parseInt) doesn't work) Luckily this isn't an issue with .then and .catch, because they only ever pass one argument to the callback.

Body:
I have two promises running at the end of the main code, but one runs in the catch using an arrow function and the other runs directly, do you know the difference between one and the other?

const main = async () => {
  const promisseTeste1 = () => new Promise((resolve, reject) => {
    reject("ERRO")
  });

  const promisseTeste2 = () => new Promise((resolve, reject) => {
    promisseTeste1().then().catch(reject)
  });

  // Method 1
  promisseTeste2().then().catch(console.log)

  // Method 2
  promisseTeste2().then().catch(e => console.log(e))
}

main()

I wanted to know if there is any performance issue or even a possible problem that may occur using method 1.

Body:
If you're using console.log, then in any browser that isn't utterly obsolete, there won't be an issue.

In some very old browsers, having console.log being called with something other than a calling context of console was an issue - but many would consider this not to be something worth worrying about.

For the general case of passing an already-declared function instead of creating an anonymous inline function, one potential gotcha is (similar to previously) the this value inside the callback if passing in / calling an object method. The this value will be the object when invoking it inline, and globalThis (or undefined in strict mode) if passing it in directly.

const obj = {
  prop: 'val',
  method() {
    console.log(this.prop);
  }
};

const main = async () => {
  // Method 1
  Promise.reject().then().catch(obj.method)

  // Method 2
  Promise.reject().then().catch(e => obj.method(e))
}

main()

Although not related to the core of your question, as you see in the above snippet, I've avoided the explicit Promise construction antipattern, and recommend you do the same.

if there is any performance issue

Not remotely. Unless you're in a tight loop or doing multiple DOM manipulations, performance of a segment of code almost certainly isn't even worth considering - better to focus on code readability and maintainability.

For the even more general issue of doing .method(callback) instead of .method(value => callback(value)), be wary of functions whose behavior changes depending on how many arguments are passed in (which is why .map(parseInt) doesn't work) Luckily this isn't an issue with .then and .catch, because they only ever pass one argument to the callback.


问:
How to iterate excel sheet cell values with a specific given range in C#?
I have tried the below code but it returns only the first row cell values and the script does not return any cell values starting from second row onwards..

The specific range I'm using here is "BE1:BS1". So basically I would need all the cell values that comes under this range.

xl.Worksheet worksheet = null;
worksheet = workbook.Worksheets[sheetValue] as xl.Worksheet;
//xl.Range range = worksheet.UsedRange;
xl.Range range = (xl.Range)worksheet.get_Range("BE1:BS1");

foreach(xl.Range row in range.Rows)
{
    for (int j = 0; j < row.Columns.Count; j++)
    {
        str = (string)(range.Cells[1, j + 1] as xl.Range).Value2;
        Report.Info(str.ToString());
    }
}
```

答:
I think the problem is that your range is only 1 row!

```<code>worksheet.get_Range("BE1:BS1")
</code>```

try worksheet.get_Range("BE1:BS14") to proof it.

Body:
I think the problem is that your range is only 1 row!

worksheet.get_Range("BE1:BS1")

try worksheet.get_Range("BE1:BS14") to proof it.


问:
Viper is not considering the mapstructure tags in my structs on umarshalling
when I use the Unmarshal method of Viper to fill my struct with the values in my Yaml file, All struct fileds were still empty, I searched many solutions, but all of them didn't work at all :(

I tried changing the tag mapstructure to yaml and structure , still didn't work...

main.go:

```<code>type Test struct {
    T TConfig `mapstructure:"apiserver"`
}

type TConfig struct {
    Address int `mapstructure:"host"`
    Port    int `mapstructure:"port"`
}
func main() {
    var aaa *Test
    viper.AutomaticEnv()
    viper.AddConfigPath("./")
    viper.SetConfigName("config")
    if err := viper.ReadInConfig(); err != nil {
        panic(err)
    }
    if err := viper.Unmarshal(&aaa); err != nil {
        fmt.Println("read config error:", err)
    }
    fmt.Println("config:", aaa)
}
</code>```

config.yml:

```<code>apiserver:
  - host: localhost
  - port: 8080
</code>```

output:

```<code>read config error: 1 error(s) decoding:

* 'apiserver' expected a map, got 'slice'
config: <nil>
</code>```

Please someone help me fix the bug!

答:
Remove the dashes in your config file. That indicates an array or slice of values.

This should work:

```<code>apiserver:
  host: localhost
  port: 8080
</code>```

Also you have Address set to int value; in the config file it is a string: "localhost".

Body:
when I use the Unmarshal method of Viper to fill my struct with the values in my Yaml file, All struct fileds were still empty, I searched many solutions, but all of them didn't work at all :(

I tried changing the tag mapstructure to yaml and structure , still didn't work...

main.go:

type Test struct {
    T TConfig `mapstructure:"apiserver"`
}

type TConfig struct {
    Address int `mapstructure:"host"`
    Port    int `mapstructure:"port"`
}
func main() {
    var aaa *Test
    viper.AutomaticEnv()
    viper.AddConfigPath("./")
    viper.SetConfigName("config")
    if err := viper.ReadInConfig(); err != nil {
        panic(err)
    }
    if err := viper.Unmarshal(&aaa); err != nil {
        fmt.Println("read config error:", err)
    }
    fmt.Println("config:", aaa)
}

config.yml:

apiserver:
  - host: localhost
  - port: 8080

output:

read config error: 1 error(s) decoding:

* 'apiserver' expected a map, got 'slice'
config: <nil>

Please someone help me fix the bug!

Body:
Remove the dashes in your config file. That indicates an array or slice of values.

This should work:

apiserver:
  host: localhost
  port: 8080

Also you have Address set to int value; in the config file it is a string: "localhost".


问:
How to make a pill shape button with HTML and CSS?
I'm trying to design a button that looks like the one in the snippet.  Is the approach taken best practice or is there a more obvious way of doing this?  Seems like a lot of overhead just to get the rounded edges.

#p1,#p2{
   height:25px;
   width:25px;
   border-radius:50% 0 0 50%;
   background-color:blue;
}

#p2{
   border-radius:0 50% 50% 0;
}

button{
   height:25px;
   width:75px;
   background-color:blue;
   border:none;
   color:white;
}

#container{
   display:flex;
   align-items:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='container'>
   <p id='p1'></p>
   <button>Update</button>
   <p id='p2'></p>
</div></code>```

答:
You don't need the
 elements at all, just add the border-radius to the button directly

button{
   height:25px;
   width:110px;
   background-color:blue;
   border:none;
   color:white;
   border-radius: 50px;
}

#container{
   display:flex;
   align-items:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='container'>
   <button>Update</button>
</div></code>```

Body:
I'm trying to design a button that looks like the one in the snippet.  Is the approach taken best practice or is there a more obvious way of doing this?  Seems like a lot of overhead just to get the rounded edges.

#p1,#p2{
   height:25px;
   width:25px;
   border-radius:50% 0 0 50%;
   background-color:blue;
}

#p2{
   border-radius:0 50% 50% 0;
}

button{
   height:25px;
   width:75px;
   background-color:blue;
   border:none;
   color:white;
}

#container{
   display:flex;
   align-items:center;
}

   <button>Update</button>

Body:
You don't need the
 elements at all, just add the border-radius to the button directly

button{
   height:25px;
   width:110px;
   background-color:blue;
   border:none;
   color:white;
   border-radius: 50px;
}

#container{
   display:flex;
   align-items:center;
}

<div id='container'>
   <button>Update</button>
</div>


问:
Rundeck failed to remove remote file in C:\WINDOWS\TEMP\ when the Job times out
Notice that when the Rundeck job triggers a timed out due to running too long, it fails to remove the temp file from my remote window node. Due to this action, the Temp folder has an unnecessary amount of dispatch temp files in the folder. I wondered if their a config setting to remove said files if the job triggers a timed out within Rundeck.

Rundeck is running on Community 3.4.10

答: There is no specific option for that, a good idea you can do is to run a periodic job that cleans that directory.</p>


问:
Concurrency not working in Azure table storage
While working with Azure Table Storage, I'm getting concurrency issues with multiple threads. Each thread is trying to update the same record (Partition key + Row key). In that case, my expectation is that if it is stale data, the library will automatically check the etag and throw an exception 412 Pre-Condition Failed. But, in my situation, it is always updating with last call.

It's worth noting that if I use TableEntityOperation.Replace(entity), it does throw the 412 exception. It seems like TableEntityOperation.InsertorMerge(entity) doesn't check for concurrency.

答:
The reason you are seeing this behavior is because TableEntityOperation.InsertorMerge(entity) method, which is a wrapper over Insert Or Merge Entity REST API operation does not support optimistic concurrency. Only Merge Entity and Update Entity support optimistic concurrency.

From the documentation (emphasis mine):

The Insert Or Merge Entity operation uses the MERGE verb and must be
called using the 2011-08-18 version or newer. In addition, it does not
use the If-Match header. These attributes distinguish this operation
from the Update Entity operation, though the request body is the same
for both operations.


问:
mocha Error: No test files found: "test/" npm ERR! Test failed
I am trying to run mocha tests on linux >
@ test C:\Users\wd.ssh\tel\qa_test\mocha-api-tests

Error: No test files found: "test/"
npm ERR! Test failed.  See above for more details.

here is my package.json

```<code>{
    "scripts": {
        "test": "mocha --reporter mocha-junit-reporter --timeout 60000 --exit",

    },
    "dependencies": {
        "cassandra-driver": "3.5.0",
        "chai": "4.2.0",
        "chai-http": "4.2.0",
        "express": "4.16.4",
        "mocha-junit-reporter": "1.18.0",
        "request-promise": "4.2.2"
    }
}
</code>```

commands used:
npm install --global mocha
npm i
and to run the tests I'm using npm test

Project structure:

答: Mocha automatically searches for folder called test and should be in root folder as package.json</p>

Body:
I am trying to run mocha tests on linux >
@ test C:\Users\wd.ssh\tel\qa_test\mocha-api-tests

Error: No test files found: "test/"
npm ERR! Test failed.  See above for more details.

here is my package.json

{
    "scripts": {
        "test": "mocha --reporter mocha-junit-reporter --timeout 60000 --exit",

    },
    "dependencies": {
        "cassandra-driver": "3.5.0",
        "chai": "4.2.0",
        "chai-http": "4.2.0",
        "express": "4.16.4",
        "mocha-junit-reporter": "1.18.0",
        "request-promise": "4.2.2"
    }
}

commands used:
npm install --global mocha
npm i
and to run the tests I'm using npm test

Project structure:


问:
Flutter navigation from popup menu item
I'm new to flutter and struggling to do some changes in my code.. When I click settings in Popup menu I want to navigate to CreateProfile() page.. I try to add 'on Tap' but it is not working. how should I do this properly.. appreciate your help on this.. below  my code shows how I was try to do the above task.

HomeScreen.dart

```<code> import 'package:flutter/material.dart';
    import 'package:image_uploader/Pages/ChatPage.dart';
    import 'package:image_uploader/Profile/CreateProfile.dart';

    class Homescreen extends StatefulWidget {
      Homescreen({ Key? key }) : super(key: key);

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

    class _HomescreenState extends State<Homescreen> with SingleTickerProviderStateMixin{

      late final TabController _controller;

    @override
    void initState(){

      _controller =TabController(length: 4, vsync:this, initialIndex: 0);
      super.initState();
    }

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text("Whatsapp Clone"),
            actions: [
              IconButton(icon: Icon(Icons.search), onPressed: () {}),
              PopupMenuButton<String>(
                onSelected: (value) {
                  print(value);
                },
                itemBuilder: (BuildContext contesxt) {
                  return [
                    PopupMenuItem(
                      child: Text("New group"),
                      value: "New group",
                    ),
                    PopupMenuItem(
                      child: Text("New broadcast"),
                      value: "New broadcast",
                    ),
                    PopupMenuItem(
                      child: Text("Whatsapp Web"),
                      value: "Whatsapp Web",
                    ),
                    PopupMenuItem(
                      child: Text("Starred messages"),
                      value: "Starred messages",
                    ),
//when I click this settings I want to navifate to createprofile page
                    PopupMenuItem(
                      child: Text("Settings",),
                      value: "Settings",
                      onTap: () => {
                        Navigator.push(context,
                            MaterialPageRoute(builder: (context) => CreateProfile(
                                key: UniqueKey()))),

                      },
                    ),
                  ];
                },
              )
            ],
            bottom: TabBar(
              controller:_controller,
              indicatorColor: Colors.white,
              tabs:[
                Tab(icon: Icon(Icons.camera_alt),),
                Tab(text: "CHATS",),
                Tab(text: "STATUS",),
                Tab(text: "CALLS",),

              ]
            ),
        ),
          body: TabBarView(
            controller: _controller,
            children: [

              Text("Camera"),
              ChatPage(),
              Text("Status"),
              Text("Calls"),
            ],
          ),
        );
      }
    }
</code>```

答:
Just add this to your PopupMenuButton:

```<code>onSelected: (result) {
    if (result == 0) {
        Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => SettingPage()),
        );
    }
},
</code>```

And change your setting button to:

```<code>PopupMenuItem(
    child: Text("Settings"),
    value: 0,
),
</code>```

add this to each popupmenuitem, obviously the first one will be 0...1..etc

Title: Flutter navigation from popup menu item

Body:
I'm new to flutter and struggling to do some changes in my code.. When I click settings in Popup menu I want to navigate to CreateProfile() page.. I try to add 'on Tap' but it is not working. how should I do this properly.. appreciate your help on this.. below  my code shows how I was try to do the above task.

HomeScreen.dart

 import 'package:flutter/material.dart';
    import 'package:image_uploader/Pages/ChatPage.dart';
    import 'package:image_uploader/Profile/CreateProfile.dart';

    class Homescreen extends StatefulWidget {
      Homescreen({ Key? key }) : super(key: key);

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

    class _HomescreenState extends State<Homescreen> with SingleTickerProviderStateMixin{

      late final TabController _controller;

    @override
    void initState(){

      _controller =TabController(length: 4, vsync:this, initialIndex: 0);
      super.initState();
    }

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text("Whatsapp Clone"),
            actions: [
              IconButton(icon: Icon(Icons.search), onPressed: () {}),
              PopupMenuButton<String>(
                onSelected: (value) {
                  print(value);
                },
                itemBuilder: (BuildContext contesxt) {
                  return [
                    PopupMenuItem(
                      child: Text("New group"),
                      value: "New group",
                    ),
                    PopupMenuItem(
                      child: Text("New broadcast"),
                      value: "New broadcast",
                    ),
                    PopupMenuItem(
                      child: Text("Whatsapp Web"),
                      value: "Whatsapp Web",
                    ),
                    PopupMenuItem(
                      child: Text("Starred messages"),
                      value: "Starred messages",
                    ),
//when I click this settings I want to navifate to createprofile page
                    PopupMenuItem(
                      child: Text("Settings",),
                      value: "Settings",
                      onTap: () => {
                        Navigator.push(context,
                            MaterialPageRoute(builder: (context) => CreateProfile(
                                key: UniqueKey()))),

                      },
                    ),
                  ];
                },
              )
            ],
            bottom: TabBar(
              controller:_controller,
              indicatorColor: Colors.white,
              tabs:[
                Tab(icon: Icon(Icons.camera_alt),),
                Tab(text: "CHATS",),
                Tab(text: "STATUS",),
                Tab(text: "CALLS",),

              ]
            ),
        ),
          body: TabBarView(
            controller: _controller,
            children: [

              Text("Camera"),
              ChatPage(),
              Text("Status"),
              Text("Calls"),
            ],
          ),
        );
      }
    }

Body:
Just add this to your PopupMenuButton:

onSelected: (result) {
    if (result == 0) {
        Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => SettingPage()),
        );
    }
},

And change your setting button to:

PopupMenuItem(
    child: Text("Settings"),
    value: 0,
),

add this to each popupmenuitem, obviously the first one will be 0...1..etc


问:
Replace values in a dataframe by values of other dataframe
I have two dataframes, one old and one new. Both dataframes contain the same IDs but the values in the columns can differ amongst the dataframes. The old dataframe contains the 'correct' values and therefor need to be replaced in the new information.

This is the old dataframe:

```<code>structure(list(ID = c(1, 2, 3, 4, 5, 6, 7), a = c("hi", "ho",
NA, "hu", "ha", NA, "he"), b = c(1, 1, NA, 1, 1, NA, 1), c = c("ri",
"ro", NA, "ru", NA, NA, "re"), d = c(2, 2, NA, 2, NA, NA, 2)), row.names = c(NA,
-7L), class = c("tbl_df", "tbl", "data.frame"))

 ID a         b c         d

 1 hi        1 ri        2
 2 ho        1 ro        2
 3 NA       NA NA       NA
 4 hu        1 ru        2
 5 ha        1 NA       NA
 6 NA       NA NA       NA
 7 he        1 re        2
</code>```

And this the new dataframe:

```<code>structure(list(ID = c(1, 2, 3, 4, 5, 6, 7, 10, 11), a = c("hi",
"ho", NA, "hu", "ha", NA, "he", "hii", "hoo"), b = c(3, 1, NA,
1, 1, NA, 1, 1, 1), c = c("ri", "ro", NA, "ru", "ra", NA, "re",
NA, "roo"), d = c(3, 2, NA, 2, 2, NA, 2, NA, 2)), row.names = c(NA,
-9L), class = c("tbl_df", "tbl", "data.frame"))

  ID a         b c         d
     1 hi        3 ri        3
     2 ho        1 ro        2
     3 NA       NA NA       NA
     4 hu        1 ru        2
     5 ha        1 ra        2
     6 NA       NA NA       NA
     7 he        1 re        2
    10 hii       1 NA       NA
    11 hoo       1 roo       2
</code>```

The IDs from the old df are included in the new df but in the new df there are also new IDs. These need to be included in the final output.
The values that are different in the new df need to be replaced by the values in the old df. Also, new data can be added in the columns (ID number 5 has new data in columns c and d). These also need to be included in the final output.

The final output should look like:

```<code>structure(list(ID = c(1, 2, 3, 4, 5, 6, 7, 10, 11), a = c("hi",
"ho", NA, "hu", "ha", NA, "he", "hii", "hoo"), b = c(1, 1, NA,
1, 1, NA, 1, 1, 1), c = c("ri", "ro", NA, "ru", "ra", NA, "re",
NA, "roo"), d = c(2, 2, NA, 2, 2, NA, 2, NA, 2)), row.names = c(NA,
-9L), class = c("tbl_df", "tbl", "data.frame"))

  ID a         b c         d
     1 hi        1 ri        2
     2 ho        1 ro        2
     3 NA       NA NA       NA
     4 hu        1 ru        2
     5 ha        1 ra        2
     6 NA       NA NA       NA
     7 he        1 re        2
    10 hii       1 NA       NA
    11 hoo       1 roo       2
</code>```

Can anyone help achieve this? I've seen the function match but this seems to only work for certain columns.

Thanks a lot!

答:
Call first sample df old_df, call second new_df. It sounds like essentially you want to update rows in new_df with values from old_df, retaining all non-matching rows in new_df:

```<code>library(dplyr)
new_df %>% rows_update(old_df, by = "ID")
</code>```

Gives:

```<code># A tibble: 9 x 5
     ID a         b c         d
  <dbl> <chr> <dbl> <chr> <dbl>
1     1 hi        1 ri        2
2     2 ho        1 ro        2
3     3 NA       NA NA       NA
4     4 hu        1 ru        2
5     5 ha        1 NA       NA
6     6 NA       NA NA       NA
7     7 he        1 re        2
8    10 hii       1 NA       NA
9    11 hoo       1 roo       2
</code>```

Body:
I have two dataframes, one old and one new. Both dataframes contain the same IDs but the values in the columns can differ amongst the dataframes. The old dataframe contains the 'correct' values and therefor need to be replaced in the new information.

This is the old dataframe:

structure(list(ID = c(1, 2, 3, 4, 5, 6, 7), a = c("hi", "ho",
NA, "hu", "ha", NA, "he"), b = c(1, 1, NA, 1, 1, NA, 1), c = c("ri",
"ro", NA, "ru", NA, NA, "re"), d = c(2, 2, NA, 2, NA, NA, 2)), row.names = c(NA,
-7L), class = c("tbl_df", "tbl", "data.frame"))

 ID a         b c         d

 1 hi        1 ri        2
 2 ho        1 ro        2
 3 NA       NA NA       NA
 4 hu        1 ru        2
 5 ha        1 NA       NA
 6 NA       NA NA       NA
 7 he        1 re        2

And this the new dataframe:

structure(list(ID = c(1, 2, 3, 4, 5, 6, 7, 10, 11), a = c("hi",
"ho", NA, "hu", "ha", NA, "he", "hii", "hoo"), b = c(3, 1, NA,
1, 1, NA, 1, 1, 1), c = c("ri", "ro", NA, "ru", "ra", NA, "re",
NA, "roo"), d = c(3, 2, NA, 2, 2, NA, 2, NA, 2)), row.names = c(NA,
-9L), class = c("tbl_df", "tbl", "data.frame"))

  ID a         b c         d
     1 hi        3 ri        3
     2 ho        1 ro        2
     3 NA       NA NA       NA
     4 hu        1 ru        2
     5 ha        1 ra        2
     6 NA       NA NA       NA
     7 he        1 re        2
    10 hii       1 NA       NA
    11 hoo       1 roo       2

The IDs from the old df are included in the new df but in the new df there are also new IDs. These need to be included in the final output.
The values that are different in the new df need to be replaced by the values in the old df. Also, new data can be added in the columns (ID number 5 has new data in columns c and d). These also need to be included in the final output.

The final output should look like:

structure(list(ID = c(1, 2, 3, 4, 5, 6, 7, 10, 11), a = c("hi",
"ho", NA, "hu", "ha", NA, "he", "hii", "hoo"), b = c(1, 1, NA,
1, 1, NA, 1, 1, 1), c = c("ri", "ro", NA, "ru", "ra", NA, "re",
NA, "roo"), d = c(2, 2, NA, 2, 2, NA, 2, NA, 2)), row.names = c(NA,
-9L), class = c("tbl_df", "tbl", "data.frame"))

  ID a         b c         d
     1 hi        1 ri        2
     2 ho        1 ro        2
     3 NA       NA NA       NA
     4 hu        1 ru        2
     5 ha        1 ra        2
     6 NA       NA NA       NA
     7 he        1 re        2
    10 hii       1 NA       NA
    11 hoo       1 roo       2

Can anyone help achieve this? I've seen the function match but this seems to only work for certain columns.

Thanks a lot!

Body:
Call first sample df old_df, call second new_df. It sounds like essentially you want to update rows in new_df with values from old_df, retaining all non-matching rows in new_df:

library(dplyr)
new_df %>% rows_update(old_df, by = "ID")

Gives:

# A tibble: 9 x 5
     ID a         b c         d
  <dbl> <chr> <dbl> <chr> <dbl>
1     1 hi        1 ri        2
2     2 ho        1 ro        2
3     3 NA       NA NA       NA
4     4 hu        1 ru        2
5     5 ha        1 NA       NA
6     6 NA       NA NA       NA
7     7 he        1 re        2
8    10 hii       1 NA       NA
9    11 hoo       1 roo       2


问:
How to set password to zip file with libZip
I'm using libZip in my project,
I success to create zip file output, but I'm having difficulty to set a password to a zip file.

I'm calling the zip_set_default_password fucntion and I'm getting the OK response, but when I'm trying to extract it didn't ask for a password.

Code sample:

```<code>int CompressWithPassword(const char * psFileContent, int iFileSize, const char * pcPassword)
{
    zip_source *psZipSource = NULL;
    zip_int64_t iIndex = 0;
    int iError = EOK;
    const char * pcZipOutputPath = "/home/user/Documents/myzip.zip";

    // Open zip file.
    m_psZip =
            zip_open(pcZipOutputPath,
                    ZIP_CREATE /*Create the archive if it does not exist*/,
                    &iError);

    // Zip opend ?
    if(iError != ZIP_ER_OK)
    {
        Close();
        return iError;
    }

    // Generate zip source content.
    psZipSource =
            zip_source_buffer(m_psZip,
                              psFileContent,
                              iFileSize,
                              0);

    // Valid zip source ?
    if(psZipSource == NULL)
    {
        Close();
        iError = -1;
        return iError;
    }

    iIndex =
            zip_file_add(m_psZip,
                         pcZipOutputPath,
                         psZipSource, ZIP_FL_OVERWRITE);
    if(iIndex < 0)
    {
        Close();
        return iIndex;
    }

    // Create password
    int iRetPassword =
                zip_set_default_password(m_psZip, pcPassword);

    // password set ?
    if (iRetPassword == -1)
    {
        Close();
        return iRetPassword;
    }

    // Close zip file.
    Close();

    return iError;
}
</code>```

When I'm calling this function, I'm getting OK and the zip file is created, What I'm missing here?

LibZip version 1.1.3-1, OS: fedora 25

Thanks.

答:
I saw that has a lot of people searching by this question, then i'll make an example of zip_file_set_encryption, the method basically ask for zip archive, file index,encryption method and the password:

```<code>int main(){
    int errCode = 0;
    zip *z = zip_open("package.zip",ZIP_CREATE,&errCode);

    zip_source_t *source;

    char buffer[] = "Hello world!";
    source = zip_source_buffer(z,buffer,strlen(buffer),0);
    zip_file_add(z,"example.txt",source,0);

    /* Available encryption methods:
    ZIP_EM_AES_128
    ZIP_EM_AES_192
    ZIP_EM_AES_256
    */

    zip_file_set_encryption(z,/* Index of the file */ 0,/* Encryption method */ ZIP_EM_AES_256,/* Password to encrypt file */ "myPassword");

    zip_close(z);
};
</code>```

then when i use 7-zip to open the zip file created by my program:

```<code>7z e package.zip
</code>```

It just prompt the password to me, if you type the correct then the files  in your workspace will be filled with the content:

```<code>Enter password (will not be echoed):
</code>```

with the libzip is possible set file password by name, but with a little process before:

```<code>int main(){
    int errCode = 0;
    zip *z = zip_open("package.zip",ZIP_CREATE,&errCode);

    zip_source_t *source;

    char buffer[] = "Hello world!";
    source = zip_source_buffer(z,buffer,strlen(buffer),0);
    zip_file_add(z,"example.txt",source,0);

    source = zip_source_buffer(z,buffer,strlen(buffer),0);
    zip_file_add(z,"example2.txt",source,0);

    // Create struct of file stat
    struct zip_stat st;

    // Fill the struct with the file name that you want
    zip_stat(z,"example2.txt",0,&st);

    // Set the password to the file using index that had got by name

    /* Available encryption methods:
    ZIP_EM_AES_128
    ZIP_EM_AES_192
    ZIP_EM_AES_256
    */

    zip_file_set_encryption(z,/* Index of file */ st.index, /* encryption method */ ZIP_EM_AES_256, /* password */"myPassword");

    zip_close(z);
};
</code>```

I'm creating an wrapper for libzip (not complete yet), an easy way to interact with zip files, the GitHub URL is there: https://github.com/Romulo-Moraes/zipCrafter

Caution, if you set an password to a file, you should set the same password for the whole zip file, cause it can generate an error when you try open with 7-zip, it will try open the first file with your password then will try the same password for the whole zip.

Some unzip program versions will skip your file that was set with password by libzip, i recommend 7-zip

ContentLicense: CC BY-SA 3.0

Body:
I'm using libZip in my project,
I success to create zip file output, but I'm having difficulty to set a password to a zip file.

I'm calling the zip_set_default_password fucntion and I'm getting the OK response, but when I'm trying to extract it didn't ask for a password.

Code sample:

int CompressWithPassword(const char * psFileContent, int iFileSize, const char * pcPassword)
{
    zip_source *psZipSource = NULL;
    zip_int64_t iIndex = 0;
    int iError = EOK;
    const char * pcZipOutputPath = "/home/user/Documents/myzip.zip";

    // Open zip file.
    m_psZip =
            zip_open(pcZipOutputPath,
                    ZIP_CREATE /*Create the archive if it does not exist*/,
                    &iError);

    // Zip opend ?
    if(iError != ZIP_ER_OK)
    {
        Close();
        return iError;
    }

    // Generate zip source content.
    psZipSource =
            zip_source_buffer(m_psZip,
                              psFileContent,
                              iFileSize,
                              0);

    // Valid zip source ?
    if(psZipSource == NULL)
    {
        Close();
        iError = -1;
        return iError;
    }

    iIndex =
            zip_file_add(m_psZip,
                         pcZipOutputPath,
                         psZipSource, ZIP_FL_OVERWRITE);
    if(iIndex < 0)
    {
        Close();
        return iIndex;
    }

    // Create password
    int iRetPassword =
                zip_set_default_password(m_psZip, pcPassword);

    // password set ?
    if (iRetPassword == -1)
    {
        Close();
        return iRetPassword;
    }

    // Close zip file.
    Close();

    return iError;
}

When I'm calling this function, I'm getting OK and the zip file is created, What I'm missing here?

LibZip version 1.1.3-1, OS: fedora 25

Thanks.

Body:
I saw that has a lot of people searching by this question, then i'll make an example of zip_file_set_encryption, the method basically ask for zip archive, file index,encryption method and the password:

int main(){
    int errCode = 0;
    zip *z = zip_open("package.zip",ZIP_CREATE,&errCode);

    zip_source_t *source;

    char buffer[] = "Hello world!";
    source = zip_source_buffer(z,buffer,strlen(buffer),0);
    zip_file_add(z,"example.txt",source,0);

    /* Available encryption methods:
    ZIP_EM_AES_128
    ZIP_EM_AES_192
    ZIP_EM_AES_256
    */

    zip_file_set_encryption(z,/* Index of the file */ 0,/* Encryption method */ ZIP_EM_AES_256,/* Password to encrypt file */ "myPassword");

    zip_close(z);
};

then when i use 7-zip to open the zip file created by my program:

7z e package.zip

It just prompt the password to me, if you type the correct then the files  in your workspace will be filled with the content:

Enter password (will not be echoed):

with the libzip is possible set file password by name, but with a little process before:

int main(){
    int errCode = 0;
    zip *z = zip_open("package.zip",ZIP_CREATE,&errCode);

    zip_source_t *source;

    char buffer[] = "Hello world!";
    source = zip_source_buffer(z,buffer,strlen(buffer),0);
    zip_file_add(z,"example.txt",source,0);

    source = zip_source_buffer(z,buffer,strlen(buffer),0);
    zip_file_add(z,"example2.txt",source,0);

    // Create struct of file stat
    struct zip_stat st;

    // Fill the struct with the file name that you want
    zip_stat(z,"example2.txt",0,&st);

    // Set the password to the file using index that had got by name

    /* Available encryption methods:
    ZIP_EM_AES_128
    ZIP_EM_AES_192
    ZIP_EM_AES_256
    */

    zip_file_set_encryption(z,/* Index of file */ st.index, /* encryption method */ ZIP_EM_AES_256, /* password */"myPassword");

    zip_close(z);
};

I'm creating an wrapper for libzip (not complete yet), an easy way to interact with zip files, the GitHub URL is there: https://github.com/Romulo-Moraes/zipCrafter

Caution, if you set an password to a file, you should set the same password for the whole zip file, cause it can generate an error when you try open with 7-zip, it will try open the first file with your password then will try the same password for the whole zip.

Some unzip program versions will skip your file that was set with password by libzip, i recommend 7-zip


问:
How do I get cypher graph algorithm result nodes and their neighbors in one query?
I have a graph loaded into neo4j v3.4.6 and I would like to compute the centrality of the nodes, grabbing the top N entries along with their neighbors and the relationships between them. I would like to do this as a single cypher query. Sounds simple enough but I'm quite new to the Cypher query language and not adapting quickly to its non-SQL-ness. I am working with a system I cannot modify, so I am suck with neo4j v3.4.6. The system also has an older version of apoc library that is lacking the apoc.neighbors procedure (not sure if that would be useful if I had it, but it sounds useful).

Here are the two best examples of what I have tried thus far. Both require multiple queries. I will use N=10:

Effectively what I want but might get extra "most central" nodes (and their neighbors) if there are ties for the Nth highest centrality score.

```<code>// Compute the centrality scores and write them back to the graph:
CALL algo.betweenness(
  null, // nodeLabel; null for all nodes
  null, // edgeLabel; null for all edges
  {
    direction: 'both',
    write: true,
    writeProperty: "centrality"
  }
)
</code>```
```<code>// Get the top N=10 centrality scores, take note of the
// smallest value in this list:
MATCH (n)
RETURN n.centrality
ORDER BY n.centrality DESC
LIMIT 10
</code>```
```<code>// Match the paths where the centrality of the first node
// is `>=` the threshold from the previous query.
// Let's assume that threshold was `100`
MATCH (n)-[r]-(m)
WHERE n.centrality >= 100
RETURN n, r, m
</code>```

Not what I want. It stops after N relationships/edges -- which might not exhaust the neighborhood of even the 1st most central node in my graph, let alone the top N central nodes -- rather than "all relationships starting with the top N central nodes".

```<code>// Compute the centrality scores and write them back to the graph:
// Same as above
CALL algo.betweenness(
  null, // nodeLabel; null for all nodes
  null, // edgeLabel; null for all edges
  {
    direction: 'both',
    write: true,
    writeProperty: "centrality"
  }
)
</code>```
```<code>// Grab the first `N` single-hop paths `(n)-[r]-(m)` sorted by `n.centratlity`
MATCH (n)-[r]-(m)
RETURN n, r, m
ORDER BY n.centrality DESC
LIMIT 10
</code>```

答:
With some more research I found a solution. Uses .stream instead of writing centrality score back to the graph, and a WITH ... ORDER BY ... LIMIT clause to do the in-place ordering and filtering. Here is my query:

```<code>CALL algo.betweenness.stream(
  null, // nodeLabel; null for all nodes
  null, // edgeLabel; null for all edges
  {
    direction: "both"
  }
)
YIELD nodeId, centrality
// Grab the top N=10 results
WITH nodeId, centrality
  ORDER BY centrality DESC
  LIMIT 10
// Extend results to include neighborhood
MATCH (n)
  WHERE id(n) = nodeId
OPTIONAL MATCH (n)-[r]-(m)
  WHERE id(n) = nodeId
RETURN n, r, m
</code>```

Body:
I have a graph loaded into neo4j v3.4.6 and I would like to compute the centrality of the nodes, grabbing the top N entries along with their neighbors and the relationships between them. I would like to do this as a single cypher query. Sounds simple enough but I'm quite new to the Cypher query language and not adapting quickly to its non-SQL-ness. I am working with a system I cannot modify, so I am suck with neo4j v3.4.6. The system also has an older version of apoc library that is lacking the apoc.neighbors procedure (not sure if that would be useful if I had it, but it sounds useful).

Here are the two best examples of what I have tried thus far. Both require multiple queries. I will use N=10:

Effectively what I want but might get extra "most central" nodes (and their neighbors) if there are ties for the Nth highest centrality score.

// Compute the centrality scores and write them back to the graph:
CALL algo.betweenness(
  null, // nodeLabel; null for all nodes
  null, // edgeLabel; null for all edges
  {
    direction: 'both',
    write: true,
    writeProperty: "centrality"
  }
)

// Get the top N=10 centrality scores, take note of the
// smallest value in this list:
MATCH (n)
RETURN n.centrality
ORDER BY n.centrality DESC
LIMIT 10

// Match the paths where the centrality of the first node
// is `>=` the threshold from the previous query.
// Let's assume that threshold was `100`
MATCH (n)-[r]-(m)
WHERE n.centrality >= 100
RETURN n, r, m

Not what I want. It stops after N relationships/edges -- which might not exhaust the neighborhood of even the 1st most central node in my graph, let alone the top N central nodes -- rather than "all relationships starting with the top N central nodes".

// Compute the centrality scores and write them back to the graph:
// Same as above
CALL algo.betweenness(
  null, // nodeLabel; null for all nodes
  null, // edgeLabel; null for all edges
  {
    direction: 'both',
    write: true,
    writeProperty: "centrality"
  }
)

// Grab the first `N` single-hop paths `(n)-[r]-(m)` sorted by `n.centratlity`
MATCH (n)-[r]-(m)
RETURN n, r, m
ORDER BY n.centrality DESC
LIMIT 10

Body:
With some more research I found a solution. Uses .stream instead of writing centrality score back to the graph, and a WITH ... ORDER BY ... LIMIT clause to do the in-place ordering and filtering. Here is my query:

CALL algo.betweenness.stream(
  null, // nodeLabel; null for all nodes
  null, // edgeLabel; null for all edges
  {
    direction: "both"
  }
)
YIELD nodeId, centrality
// Grab the top N=10 results
WITH nodeId, centrality
  ORDER BY centrality DESC
  LIMIT 10
// Extend results to include neighborhood
MATCH (n)
  WHERE id(n) = nodeId
OPTIONAL MATCH (n)-[r]-(m)
  WHERE id(n) = nodeId
RETURN n, r, m