问:
Parse JSON data from file using C#
I'm trying to parse a json file, but it's being kinda hard to do. I'm using Visual Studio 2019.

I need to take some data from the file.

Here's the Json file's data I need to extract:

```<code>{
    "Id": "92cb6271-005e-48e9-a319-a606b8b6e1ef",
    "DefaultPosition": {
        "PositionId": "35ed169a-1208-4d8a-8faa-d2627d5790ed",
        "EntityDetails": {
            "DateCreated": "2019-09-17T15:25:52.4942161-03:00",
            "DateModified": "2019-09-17T15:45:28.896274-03:00",
            "CreatedBy": {
                "Id": "1abb5047-8580-4be1-909d-41138035e4c9",
                "ItemDisplayText": "Laurete Araujo",
                "ItemType": "Users"
            },
            "ModifiedBy": {
                "Id": "1abb5047-8580-4be1-909d-41138035e4c9",
                "ItemDisplayText": "Laurete Araujo",
                "ItemType": "Users"
            },
            "Owner": {
                "Id": "1abb5047-8580-4be1-909d-41138035e4c9",
                "ItemDisplayText": "Laurete Araujo",
                "ItemType": "Users"
            }
        },
        "NameComponents": {
        "FullName": "ABRAHÃO DOS SANTOS",
        "FamilyName": "SANTOS",
        "FirstName": "ABRAHÃO DOS"
        },
        "MaritalStatus": {
        "Id": "97d7a9dd-a7c4-4076-829c-7ec63b0e3fe7",
        "DisplayTitle": "Marital Status",
        "ItemDisplayText": "Married",
        "ItemType": "LookupListEntries"
        }
}
</code>```

This is the C# code I'm trying to use, but it's giving me issues:

```<code>public void JsonParser(string file)
{
    string fullname;
    string gender;
    string nationality;
    string maritalstatus;

    var json = System.IO.File.ReadAllText(file);

    var objects = Newtonsoft.Json.Linq.JArray.Parse(json); // parse as array

    foreach (JObject root in objects)
    {
        foreach (KeyValuePair<String, JToken> app in root)
        {
            var appName = app.Key;
            fullname = (String)app.Value["FullName"];

            if (app.Key == "Gender")
            {
                gender = (String)app.Value["ItemDisplayText"];
                Console.WriteLine(gender);
            }

            Console.WriteLine(fullname);
            Console.WriteLine("\n");
        }
    }
}
</code>```

When I run the code and I try to import the file from where I want to extract the data, this error appears:

Newtonsoft.Json.JsonReaderException: 'Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1.'

Thank you!

答:
Your json has an issue its not an array and you are trying to parse it as an jarray,

this is how your json should look like

```<code>[
    {
      "Id": "92cb6271-005e-48e9-a319-a606b8b6e1ef",
      "DefaultPosition": {
        "PositionId": "35ed169a-1208-4d8a-8faa-d2627d5790ed",
        "EntityDetails": {
          "DateCreated": "2019-09-17T15:25:52.4942161-03:00",
          "DateModified": "2019-09-17T15:45:28.896274-03:00",
          "CreatedBy": {
            "Id": "1abb5047-8580-4be1-909d-41138035e4c9",
            "ItemDisplayText": "Laurete Araujo",
            "ItemType": "Users"
          },
          "ModifiedBy": {
            "Id": "1abb5047-8580-4be1-909d-41138035e4c9",
            "ItemDisplayText": "Laurete Araujo",
            "ItemType": "Users"
          },
          "Owner": {
            "Id": "1abb5047-8580-4be1-909d-41138035e4c9",
            "ItemDisplayText": "Laurete Araujo",
            "ItemType": "Users"
          }
        },
        "NameComponents": {
          "FullName": "ABRAHÃO DOS SANTOS",
          "FamilyName": "SANTOS",
          "FirstName": "ABRAHÃO DOS"
        },
        "MaritalStatus": {
          "Id": "97d7a9dd-a7c4-4076-829c-7ec63b0e3fe7",
          "DisplayTitle": "Marital Status",
          "ItemDisplayText": "Married",
          "ItemType": "LookupListEntries"
        }
      }
    }
  ]
</code>```

or if you want to get the exact values without treating it as array then you can use this

```<code>public static void JsonParser(string file)
{
    string fullname;
    string gender;
    string nationality;
    string maritalstatus;

    var json = System.IO.File.ReadAllText(file);

    var objects = JObject.Parse(json);

    fullname = (string)objects["DefaultPosition"]["NameComponents"]["FullName"];
    Console.WriteLine(fullname);
    Console.WriteLine("\n");
}
</code>```

but the ideal approach should be creating a model that has the same structure and deserializing to that particular object.

Title: Parse JSON data from file using C#

Body:
I'm trying to parse a json file, but it's being kinda hard to do. I'm using Visual Studio 2019.

I need to take some data from the file.

Here's the Json file's data I need to extract:

{
    "Id": "92cb6271-005e-48e9-a319-a606b8b6e1ef",
    "DefaultPosition": {
        "PositionId": "35ed169a-1208-4d8a-8faa-d2627d5790ed",
        "EntityDetails": {
            "DateCreated": "2019-09-17T15:25:52.4942161-03:00",
            "DateModified": "2019-09-17T15:45:28.896274-03:00",
            "CreatedBy": {
                "Id": "1abb5047-8580-4be1-909d-41138035e4c9",
                "ItemDisplayText": "Laurete Araujo",
                "ItemType": "Users"
            },
            "ModifiedBy": {
                "Id": "1abb5047-8580-4be1-909d-41138035e4c9",
                "ItemDisplayText": "Laurete Araujo",
                "ItemType": "Users"
            },
            "Owner": {
                "Id": "1abb5047-8580-4be1-909d-41138035e4c9",
                "ItemDisplayText": "Laurete Araujo",
                "ItemType": "Users"
            }
        },
        "NameComponents": {
        "FullName": "ABRAHÃO DOS SANTOS",
        "FamilyName": "SANTOS",
        "FirstName": "ABRAHÃO DOS"
        },
        "MaritalStatus": {
        "Id": "97d7a9dd-a7c4-4076-829c-7ec63b0e3fe7",
        "DisplayTitle": "Marital Status",
        "ItemDisplayText": "Married",
        "ItemType": "LookupListEntries"
        }
}

This is the C# code I'm trying to use, but it's giving me issues:

public void JsonParser(string file)
{
    string fullname;
    string gender;
    string nationality;
    string maritalstatus;

    var json = System.IO.File.ReadAllText(file);

    var objects = Newtonsoft.Json.Linq.JArray.Parse(json); // parse as array

    foreach (JObject root in objects)
    {
        foreach (KeyValuePair<String, JToken> app in root)
        {
            var appName = app.Key;
            fullname = (String)app.Value["FullName"];

            if (app.Key == "Gender")
            {
                gender = (String)app.Value["ItemDisplayText"];
                Console.WriteLine(gender);
            }

            Console.WriteLine(fullname);
            Console.WriteLine("\n");
        }
    }
}

When I run the code and I try to import the file from where I want to extract the data, this error appears:

Newtonsoft.Json.JsonReaderException: 'Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1.'

Thank you!

Body:
Your json has an issue its not an array and you are trying to parse it as an jarray,

this is how your json should look like

[
    {
      "Id": "92cb6271-005e-48e9-a319-a606b8b6e1ef",
      "DefaultPosition": {
        "PositionId": "35ed169a-1208-4d8a-8faa-d2627d5790ed",
        "EntityDetails": {
          "DateCreated": "2019-09-17T15:25:52.4942161-03:00",
          "DateModified": "2019-09-17T15:45:28.896274-03:00",
          "CreatedBy": {
            "Id": "1abb5047-8580-4be1-909d-41138035e4c9",
            "ItemDisplayText": "Laurete Araujo",
            "ItemType": "Users"
          },
          "ModifiedBy": {
            "Id": "1abb5047-8580-4be1-909d-41138035e4c9",
            "ItemDisplayText": "Laurete Araujo",
            "ItemType": "Users"
          },
          "Owner": {
            "Id": "1abb5047-8580-4be1-909d-41138035e4c9",
            "ItemDisplayText": "Laurete Araujo",
            "ItemType": "Users"
          }
        },
        "NameComponents": {
          "FullName": "ABRAHÃO DOS SANTOS",
          "FamilyName": "SANTOS",
          "FirstName": "ABRAHÃO DOS"
        },
        "MaritalStatus": {
          "Id": "97d7a9dd-a7c4-4076-829c-7ec63b0e3fe7",
          "DisplayTitle": "Marital Status",
          "ItemDisplayText": "Married",
          "ItemType": "LookupListEntries"
        }
      }
    }
  ]

or if you want to get the exact values without treating it as array then you can use this

public static void JsonParser(string file)
{
    string fullname;
    string gender;
    string nationality;
    string maritalstatus;

    var json = System.IO.File.ReadAllText(file);

    var objects = JObject.Parse(json);

    fullname = (string)objects["DefaultPosition"]["NameComponents"]["FullName"];
    Console.WriteLine(fullname);
    Console.WriteLine("\n");
}

but the ideal approach should be creating a model that has the same structure and deserializing to that particular object.


来源: stackexchange

问:
Assersion error using f_printf of fatfs, but f_write works fine
I have a small piece of code that opens a file, reads a single number, adds one and writes it back to the file.
It works fine when I use f_write, but f_open returns FR_INT_ERR.
I'm using version R0.12c.
The code that generates error:

```<code>FIL indexFile;
char chars[10] = {0};
uint16_t indexNumber = 0;
FRESULT fr;
fr = f_open(&indexFile, INDEX_NAME, FA_READ | FA_WRITE | FA_OPEN_EXISTING);
fr = f_read(&indexFile, &chars, 10, &br);
indexNumber = atoi(chars);
fr = f_lseek(&indexFile, 0);
fr = f_printf(&indexFile, "%d", indexNumber+1);  // produces assertion error
if (fr != FR_OK) printf("Something went wrong");
</code>```

But if I change fr = f_printf(&indexFile, "%d", indexNumber+1); to the following, it does not complain:

```<code>char stringBuffer[5];
sprintf(stringBuffer, "%d", indexNumber+1);
UINT bw;
fr = f_write(&indexFile, stringBuffer, strlen(stringBuffer), &bw);
if (fr != FR_OK || strlen(stringBuffer) != bw) printf("something went wrong");
</code>```

Although I can keep using the second approach but I'm the type of person who needs to understand what is wrong.

BTW: I'm using STM32

答:
I believe that f_write does indeed return an FRESULT but that f_printf will return an int indicating the number of characters written. Therefore, checking for F_OK as a return does not make sense. You need to instead assert based on the input format string,

Edit: as per @KamilCuk comment, EOF (-1) will be returned on failure, so test for that.

ContentLicense: CC BY-SA 4.0

Body:
I have a small piece of code that opens a file, reads a single number, adds one and writes it back to the file.
It works fine when I use f_write, but f_open returns FR_INT_ERR.
I'm using version R0.12c.
The code that generates error:

FIL indexFile;
char chars[10] = {0};
uint16_t indexNumber = 0;
FRESULT fr;
fr = f_open(&indexFile, INDEX_NAME, FA_READ | FA_WRITE | FA_OPEN_EXISTING);
fr = f_read(&indexFile, &chars, 10, &br);
indexNumber = atoi(chars);
fr = f_lseek(&indexFile, 0);
fr = f_printf(&indexFile, "%d", indexNumber+1);  // produces assertion error
if (fr != FR_OK) printf("Something went wrong");

But if I change fr = f_printf(&indexFile, "%d", indexNumber+1); to the following, it does not complain:

char stringBuffer[5];
sprintf(stringBuffer, "%d", indexNumber+1);
UINT bw;
fr = f_write(&indexFile, stringBuffer, strlen(stringBuffer), &bw);
if (fr != FR_OK || strlen(stringBuffer) != bw) printf("something went wrong");

Although I can keep using the second approach but I'm the type of person who needs to understand what is wrong.

BTW: I'm using STM32


问:
(Laravel Eloquent) Get posts of category and all nested subcategories
I would like to retrieve all posts of chosen category and all nested subcategories. I mean sth like this:

```<code>[id= 1]-Category 1
[id= 7]--Category 1.1
[id=12]---Category 1.1.1
[id=13]---Category 1.1.2
[id= 9]--Category 1.2
[id= 3]-Category 2
</code>```

At first I tried to get recursively all IDs of chosen category and all nested subcategories and then retrieve posts with those categories IDs.

I wrote method getSubcategoriesIds($category) in controller which actually give me what I want but it returns array with duplicated ids. For instans, category 1 I get:

```<code>array:10 [
    0 => 1
    1 => 7
    2 => 1
    3 => 7
    4 => 12
    5 => 1
    6 => 7
    7 => 12
    8 => 13
    9 => 9
]
</code>```

How can I improve the method to return IDs without duplicates?
Or maybe there is better way to revive those posts?

Here are my files:

Model Category.php:

```<code>class Category extends Model {

    public function parent() {
        return $this->belongsTo('App\Category', 'parent_id');
    }

    public function children() {
        return $this->hasMany('App\Category', 'parent_id');
    }

    public function subcategories() {
        return $this->children()->with('subcategories');
    }

    public function parents() {
        return $this->parent()->with('parents');
    }

    public function posts(){
        return $this->hasMany('App\Post');
    }
}
</code>```

PostController.php:

```<code>public function show($id)
{
    $ids =$this->getSubcategoriesIds(Category::with('subcategories')->where('id', $id)->first()));
    $posts = Post::whereIn('category_id', $ids)->get();
    return view('post.index', compact('posts'));
}

public function getSubcategoriesIds($category) {
    $array = [$category->id];
    if(count($category->subcategories) == 0) {
        return $array;
    }
    else  {
        foreach ($category->subcategories as $subcategory) {
            array_push($array, $subcategory->id);
            if(count($subcategory->subcategories)){
                $array = array_merge($array, $this->getChildren($subcategory->subcategories, $array));
            }
        }
        return $array;
    }
}

public function getChildren($subcategories, $array) {
    foreach ($subcategories as $subcategory)  {
        array_push($array, $subcategory->id);
        if(count($subcategory->subcategories)){
            return $array = array_merge($array, $this->getChildren($subcategory->subcategories, $array));
        }
        return $array;
    }
}
</code>```

答:
I found problem in my recursive method. I shouldn't have passed $array to the recursive method getChildrenIds().

Here is my solution (with some refactoring):

```<code>public function getCategoriesIds($category)
{
    if(!empty($category))
    {
        $array = array($category->id);
        if(count($category->subcategories) == 0) return $array;
        else return array_merge($array, $this->getChildrenIds($category->subcategories));
    }
    else return null;
}

public function getChildrenIds($subcategories)
{
    $array = array();
    foreach ($subcategories as $subcategory)
    {
        array_push($array, $subcategory->id);
        if(count($subcategory->subcategories))
            $array = array_merge($array, $this->getChildrenIds($subcategory->subcategories));
    }
    return $array;
}
</code>```

and now $this->getCategoriesIds(Category::with('subcategories')->where('id', 1)->first()); returns:

```<code>array:10 [
0 => 1
1 => 7
2 => 12
3 => 13
4 => 9
]
</code>```

Body:
I would like to retrieve all posts of chosen category and all nested subcategories. I mean sth like this:

[id= 1]-Category 1
[id= 7]--Category 1.1
[id=12]---Category 1.1.1
[id=13]---Category 1.1.2
[id= 9]--Category 1.2
[id= 3]-Category 2

At first I tried to get recursively all IDs of chosen category and all nested subcategories and then retrieve posts with those categories IDs.

I wrote method getSubcategoriesIds($category) in controller which actually give me what I want but it returns array with duplicated ids. For instans, category 1 I get:

array:10 [
    0 => 1
    1 => 7
    2 => 1
    3 => 7
    4 => 12
    5 => 1
    6 => 7
    7 => 12
    8 => 13
    9 => 9
]

How can I improve the method to return IDs without duplicates?
Or maybe there is better way to revive those posts?

Here are my files:

Model Category.php:

class Category extends Model {

    public function parent() {
        return $this->belongsTo('App\Category', 'parent_id');
    }

    public function children() {
        return $this->hasMany('App\Category', 'parent_id');
    }

    public function subcategories() {
        return $this->children()->with('subcategories');
    }

    public function parents() {
        return $this->parent()->with('parents');
    }

    public function posts(){
        return $this->hasMany('App\Post');
    }
}

PostController.php:

public function show($id)
{
    $ids =$this->getSubcategoriesIds(Category::with('subcategories')->where('id', $id)->first()));
    $posts = Post::whereIn('category_id', $ids)->get();
    return view('post.index', compact('posts'));
}

public function getSubcategoriesIds($category) {
    $array = [$category->id];
    if(count($category->subcategories) == 0) {
        return $array;
    }
    else  {
        foreach ($category->subcategories as $subcategory) {
            array_push($array, $subcategory->id);
            if(count($subcategory->subcategories)){
                $array = array_merge($array, $this->getChildren($subcategory->subcategories, $array));
            }
        }
        return $array;
    }
}

public function getChildren($subcategories, $array) {
    foreach ($subcategories as $subcategory)  {
        array_push($array, $subcategory->id);
        if(count($subcategory->subcategories)){
            return $array = array_merge($array, $this->getChildren($subcategory->subcategories, $array));
        }
        return $array;
    }
}

Body:
I found problem in my recursive method. I shouldn't have passed $array to the recursive method getChildrenIds().

Here is my solution (with some refactoring):

public function getCategoriesIds($category)
{
    if(!empty($category))
    {
        $array = array($category->id);
        if(count($category->subcategories) == 0) return $array;
        else return array_merge($array, $this->getChildrenIds($category->subcategories));
    }
    else return null;
}

public function getChildrenIds($subcategories)
{
    $array = array();
    foreach ($subcategories as $subcategory)
    {
        array_push($array, $subcategory->id);
        if(count($subcategory->subcategories))
            $array = array_merge($array, $this->getChildrenIds($subcategory->subcategories));
    }
    return $array;
}

and now $this->getCategoriesIds(Category::with('subcategories')->where('id', 1)->first()); returns:

array:10 [
0 => 1
1 => 7
2 => 12
3 => 13
4 => 9
]


问:
Java regex question
I have a text something like

```<code>ab1ab2ab3ab4cd
</code>```

Can one create a java regular expression to obtain all subtrings that start with "ab" and end with "cd"? e.g:

```<code>ab1ab2ab3ab4cd
ab2ab3ab4cd
ab3ab4cd
ab4cd
</code>```

Thanks

答:
The regex (?=(ab.*cd)) will group such matches in group 1 as you can see:

```<code>import java.util.regex.*;

public class Main {
  public static void main(String[] args) throws Exception {

    Matcher m = Pattern.compile("(?=(ab.*cd))").matcher("ab1ab2ab3ab4cd");

    while (m.find()) {
      System.out.println(m.group(1));
    }
  }
}
</code>```

which produces:

```<code>ab1ab2ab3ab4cd
ab2ab3ab4cd
ab3ab4cd
ab4cd
</code>```

You need the look ahead, (?= ... ), otherwise you'll just get one match. Note that regex will fail to produce the desired results if there are more than 2 cd's in your string. In that case, you'll have to resort to some manual string algorithm.

ContentLicense: CC BY-SA 3.0

Title: Java regex question

Body:
I have a text something like

ab1ab2ab3ab4cd

Can one create a java regular expression to obtain all subtrings that start with "ab" and end with "cd"? e.g:

ab1ab2ab3ab4cd
ab2ab3ab4cd
ab3ab4cd
ab4cd

Thanks

Body:
The regex (?=(ab.*cd)) will group such matches in group 1 as you can see:

import java.util.regex.*;

public class Main {
  public static void main(String[] args) throws Exception {

    Matcher m = Pattern.compile("(?=(ab.*cd))").matcher("ab1ab2ab3ab4cd");

    while (m.find()) {
      System.out.println(m.group(1));
    }
  }
}

which produces:

ab1ab2ab3ab4cd
ab2ab3ab4cd
ab3ab4cd
ab4cd

You need the look ahead, (?= ... ), otherwise you'll just get one match. Note that regex will fail to produce the desired results if there are more than 2 cd's in your string. In that case, you'll have to resort to some manual string algorithm.


问:
Detect / Avoid "Premature end of JPEG" in cv2 - python
I have a stream of images saved to a file (like every 2 seconds) from outside program (can't control it). When I try to read that image, sometimes, it is read while it is being written, so I get the message from OpenCV about the end of the JPEG. Is there a way to test if the file is bad, and if so to wait a while and then try to re-read it?

Thanks...

答:
I found the below solution to be much more elegant and less verbose. Albeit, it requires the skimage package.

```<code>from skimage import io
try:
    _ = io.imread(path)
    img = cv2.imread(path)
    # Do stuff with img
except Exception as e:
    print(e)
    return False
</code>```

Turns out skimage catches the exception while opencv doesn't. So, reading in the image with skimage.io before opencv should solve the problem.

Source: This medium post.

Body:
I found the below solution to be much more elegant and less verbose. Albeit, it requires the skimage package.

from skimage import io
try:
    _ = io.imread(path)
    img = cv2.imread(path)
    # Do stuff with img
except Exception as e:
    print(e)
    return False

Turns out skimage catches the exception while opencv doesn't. So, reading in the image with skimage.io before opencv should solve the problem.

Source: This medium post.


问:
GKE cluster - can I direct traffic from global http load balancer to nginx ingress controller
I'm using GKE and I installed nginx ingress controller on the cluster. GCP created automatically a TCP load balancer to redirect the request from the external ephemeral IP to my cluster nodes (nginx).

I have another a web application deployed on a VM, and I'd like to balance the incoming requests by subdomain between VM and gke cluster. In order to do that I created a global load balancer with 2 backends and the host and path rules.

I configured DNS record A to point the Global load balancer.

I can reach the VM from my domain but I cannot reach the ingresses installed on GKE.

I tried to configure the gke-backend as instance group (node pool) and as Internet network endpoint group pointing to TCP load balancer. But without success :-(

How can I balance between a VM and GKE cluster in GCP?

答:
I solved my problems by using 2 static IPs and 2 DNS A records, the first one (*.mydomain) targets the k8s cluster and second one (service.mydomain) targets my VM.

It was the fast solution I just came up


问:
Add ACF admin column to custom post type
I'm trying to add a new admin column to my custom post type using the content of a custom field (ACF). The field I want to add is a 'post object' field, but it just displays the post title instead of the linked post from the ACF. I added a screenshot.

This is what I have so far:

```<code>function add_new_realisaties_column($columns) {
    $columns['realisatie_line'] = 'Line';
    return $columns;
}
add_filter('manage_realisaties_posts_columns', 'add_new_realisaties_column');

function add_new_realisaties_admin_column_show_value( $column, $post_id ) {
if ($column == 'realisatie_line') {
    $post_object = get_field('realisatie_line');

    if( $post_object ):
        // override $post
        $post = $post_object;
        setup_postdata( $post );

        $evdate = the_title();

        wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
    <?php endif;

    echo $evdate;
    }
}
add_filter('manage_realisaties_posts_custom_column', 'add_new_realisaties_admin_column_show_value', 10, 2);

/* Make the column sortable */
function set_custom_realisaties_sortable_columns( $columns ) {
    $columns['realisatie_line'] = 'realisatie_line';
    return $columns;
}
add_filter( 'manage_edit-realisaties_sortable_columns', 'set_custom_realisaties_sortable_columns' );

function realisaties_custom_orderby( $query ) {
    if ( ! is_admin() )
        return;
        $orderby = $query->get('orderby');

        if ( 'realisatie_line' == $orderby ) {
            $query->set( 'meta_key', 'realisatie_line' );
            $query->set( 'orderby', 'meta_value' );
        }
    }
add_action( 'pre_get_posts', 'realisaties_custom_orderby' );
</code>```

答:
There's a couple things I notice. One is that you shouldn't actually need to use the setup_postdata() function, because the ACF Post Object field uses get_post() which returns a full object already. You'd only do this if you're intended to override the global $post object, say on a single-{post_type}.php template, for instance.

Another thing is that it's generally more common to use a switch statement instead of an if/else for post columns. A bit pedantic, but something to note.

Lastly, the_title() will echo the title by default, so assigning it, and then echoing it later, can cause issues (namely leaving variables littered around the document). Consider using get_the_title() if you plan on assigning it to a variable. Also, I won't go into excruciating detail, but just using setup_postdata may not be enough to get the post helper functions to pull the data from where you want.

Now, with all that said, you should be able to just echo the post_title field of the $post_object from get_field(), since it returns a full formed WP_Post object. I put this on a test site of mine and it worked just as intended:

```<code>add_filter('manage_realisaties_posts_custom_column', 'add_new_realisaties_admin_column_show_value', 10, 2);
function add_new_realisaties_admin_column_show_value( $column, $post_id ){
    switch( $column ){
        case 'realisatie_line':
            if( $post_object = get_field('realisatie_line') ){
                echo $post_object->post_title;
            }
            break;
    }
}
</code>```

And here's what it looks like in the admin, note I just grabbed a random post for the Post Object relational field:

Body:
I'm trying to add a new admin column to my custom post type using the content of a custom field (ACF). The field I want to add is a 'post object' field, but it just displays the post title instead of the linked post from the ACF. I added a screenshot.

This is what I have so far:

function add_new_realisaties_column($columns) {
    $columns['realisatie_line'] = 'Line';
    return $columns;
}
add_filter('manage_realisaties_posts_columns', 'add_new_realisaties_column');

function add_new_realisaties_admin_column_show_value( $column, $post_id ) {
if ($column == 'realisatie_line') {
    $post_object = get_field('realisatie_line');

    if( $post_object ):
        // override $post
        $post = $post_object;
        setup_postdata( $post );

        $evdate = the_title();

        wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
    <?php endif;

    echo $evdate;
    }
}
add_filter('manage_realisaties_posts_custom_column', 'add_new_realisaties_admin_column_show_value', 10, 2);

/* Make the column sortable */
function set_custom_realisaties_sortable_columns( $columns ) {
    $columns['realisatie_line'] = 'realisatie_line';
    return $columns;
}
add_filter( 'manage_edit-realisaties_sortable_columns', 'set_custom_realisaties_sortable_columns' );

function realisaties_custom_orderby( $query ) {
    if ( ! is_admin() )
        return;
        $orderby = $query->get('orderby');

        if ( 'realisatie_line' == $orderby ) {
            $query->set( 'meta_key', 'realisatie_line' );
            $query->set( 'orderby', 'meta_value' );
        }
    }
add_action( 'pre_get_posts', 'realisaties_custom_orderby' );

Body:
There's a couple things I notice. One is that you shouldn't actually need to use the setup_postdata() function, because the ACF Post Object field uses get_post() which returns a full object already. You'd only do this if you're intended to override the global $post object, say on a single-{post_type}.php template, for instance.

Another thing is that it's generally more common to use a switch statement instead of an if/else for post columns. A bit pedantic, but something to note.

Lastly, the_title() will echo the title by default, so assigning it, and then echoing it later, can cause issues (namely leaving variables littered around the document). Consider using get_the_title() if you plan on assigning it to a variable. Also, I won't go into excruciating detail, but just using setup_postdata may not be enough to get the post helper functions to pull the data from where you want.

Now, with all that said, you should be able to just echo the post_title field of the $post_object from get_field(), since it returns a full formed WP_Post object. I put this on a test site of mine and it worked just as intended:

add_filter('manage_realisaties_posts_custom_column', 'add_new_realisaties_admin_column_show_value', 10, 2);
function add_new_realisaties_admin_column_show_value( $column, $post_id ){
    switch( $column ){
        case 'realisatie_line':
            if( $post_object = get_field('realisatie_line') ){
                echo $post_object->post_title;
            }
            break;
    }
}

And here's what it looks like in the admin, note I just grabbed a random post for the Post Object relational field:


问:
Translate R for loop into apply function
I have written a for loop in my code

```<code>for(i in 2:nrow(ProductionWellYear2)) {

  if (ProductionWellYear2[i,ncol(ProductionWellYear2)] == 0) {
    ProductionWellYear2[i, ncol(ProductionWellYear2)] = ProductionWellYear2[i-1,ncol(ProductionWellYear2)] +1}

  else {ProductionWellYear2[i,ncol(ProductionWellYear2)] = ProductionWellYear2[i,ncol(ProductionWellYear2)]}

  }

</code>```

However, this is very time intensive as this dataframe has over 800k rows.  How can I make this quicker and avoid the for loop?

Body:
I have written a for loop in my code

for(i in 2:nrow(ProductionWellYear2)) {

  if (ProductionWellYear2[i,ncol(ProductionWellYear2)] == 0) {
    ProductionWellYear2[i, ncol(ProductionWellYear2)] = ProductionWellYear2[i-1,ncol(ProductionWellYear2)] +1}

  else {ProductionWellYear2[i,ncol(ProductionWellYear2)] = ProductionWellYear2[i,ncol(ProductionWellYear2)]}

  }

However, this is very time intensive as this dataframe has over 800k rows.  How can I make this quicker and avoid the for loop?

Body:
You could use conditional assignment, using R's potential as a vectorized language.

Consider this initial data frame:

          X1          X2         X3 year
1  1.3709584 -0.09465904 -0.1333213 2014
2 -0.5646982  2.01842371  0.6359504    0
3  0.3631284 -0.06271410 -0.2842529 2016
4  0.6328626  1.30486965 -2.6564554    0
5  0.4042683  2.28664539 -2.4404669 2018
6 -0.1061245 -1.38886070  1.3201133    0
7  1.5115220 -0.27878877 -0.3066386 2020

Then do:

num.col <- ncol(ProductionWellYear2)  # to keep code short

ProductionWellYear2[ProductionWellYear2[num.col] == 0, num.col] <-
  ProductionWellYear2[which(ProductionWellYear2[num.col] == 0) - 1, num.col] + 1

Resulting data frame:

           X1         X2          X3 year
1 -0.16137564 -1.0344340 -2.18025447 2014
2  0.60828818  1.8149734  1.11955225 2015
3  0.02006922  1.1641742  2.08033131 2016
4 -0.70472925  0.4136222  0.95275587 2017
5  0.43061575  1.0180987 -0.26629157 2018
6 -2.49764918  0.5957401 -2.06162220 2019
7 -1.00775410  1.1497179 -0.03193637 2020

Data:

ProductionWellYear2 <- structure(list(X1 = c(1.37095844714667, -0.564698171396089, 0.363128411337339,
0.63286260496104, 0.404268323140999, -0.106124516091484, 1.51152199743894
), X2 = c(-0.0946590384130976, 2.01842371387704, -0.062714099052421,
1.30486965422349, 2.28664539270111, -1.38886070111234, -0.278788766817371
), X3 = c(-0.133321336393658, 0.635950398070074, -0.284252921416072,
-2.65645542090478, -2.44046692857552, 1.32011334573019, -0.306638594078475
), year = c(2014, 0, 2016, 0, 2018, 0, 2020)), row.names = c(NA,
-7L), class = "data.frame")


问:
How to Copy twitter account image to server?
I am using the twitter api to access some account details. It's been made clear that you can easily get the twitter account image:

http://a0.twimg.com/profile_images/1260994338/P3030586-2_bigger.jpg

However, when i try to copy() this image in PHP to my local server it doesn't work. It seems you can't even ping the address as 'could not find host'.

How can I copy the twitter account image to my local server?

答:
The problem you are having is that the php ini-file variable allow_url_fopen is turned off, as it should be. You need to be using cURL to get the file. cURL is usually installed on web servers by default. This example works on my site:

```<code><?php
function save_image($img,$path){
    $ch = curl_init($img);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    $data=curl_exec($ch);
    curl_close ($ch);
    if(file_exists($path)){
        unlink($path);
    }
    $fp = fopen($path,'x');
    fwrite($fp, $data);
    fclose($fp);
}

save_image("http://a0.twimg.com/profile_images/1260994338/P3030586-2_bigger.jpg","up/file2.jpg");
?>
</code>```

Also make sure you have the right CHMOD (775) set on your destination folder.

Body:
The problem you are having is that the php ini-file variable allow_url_fopen is turned off, as it should be. You need to be using cURL to get the file. cURL is usually installed on web servers by default. This example works on my site:

<?php
function save_image($img,$path){
    $ch = curl_init($img);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    $data=curl_exec($ch);
    curl_close ($ch);
    if(file_exists($path)){
        unlink($path);
    }
    $fp = fopen($path,'x');
    fwrite($fp, $data);
    fclose($fp);
}

save_image("http://a0.twimg.com/profile_images/1260994338/P3030586-2_bigger.jpg","up/file2.jpg");
?>

Also make sure you have the right CHMOD (775) set on your destination folder.


问:
Javascript async/await callback function
I'm wondering if async/await behave the same in the following two 'super-basic' examples:

```<code>async function blah1() {
  return await foo.bar().then('Done');
}
</code>```

as this

```<code>async function blah2() {
  return blah3(foo.bar());
}

async function blah3(fn) {
  return await fn.then('Done');
}
</code>```

or is there some important difference?

Yes I know 'return await' is redundant but I left it in for this example :)

答:
async function blah1() {
  return await foo.bar().then('Done');
}

blah1()
```

<p>Calls <code>foo.bar</code>, which returns a promise, to which a <code>then</code> is added.</p>

<p>The resultant promise is returned.</p>

<pre class="lang-js prettyprint-override"><code>async function blah2() {
  return blah3(foo.bar());
}

async function blah3(fn) {
  return await fn.then('Done');
}

blah2()
</code>```

Calls foo.bar, which returns a promise, which is passed to blah3, which adds a then.

The resultant promise is returned from blah3 to blah2 and thence to the caller.

I'd say no meaningful behavioral difference.

Body:
I'm wondering if async/await behave the same in the following two 'super-basic' examples:

async function blah1() {
  return await foo.bar().then('Done');
}

as this

async function blah2() {
  return blah3(foo.bar());
}

async function blah3(fn) {
  return await fn.then('Done');
}

or is there some important difference?

Yes I know 'return await' is redundant but I left it in for this example :)

Body:
async function blah1() {
  return await foo.bar().then('Done');
}

blah1()

Calls foo.bar, which returns a promise, to which a then is added.

The resultant promise is returned.

async function blah2() {
  return blah3(foo.bar());
}

async function blah3(fn) {
  return await fn.then('Done');
}

blah2()

Calls foo.bar, which returns a promise, which is passed to blah3, which adds a then.

The resultant promise is returned from blah3 to blah2 and thence to the caller.

I'd say no meaningful behavioral difference.


问:
What's a good way to save all data related to a training run in Keras?
I know how to do a few things already:

Summarise a model with model.summary(). But this actually doesn't print everything about the model, just the coarse details.

Save model with model.save() and load model with keras.models.load_model()

Get weights with model.get_weights()

Get the training history from model.fit()

But none of these seem to give me a catch all solution for saving everything from end to end so that I can 100% reproduce a model architecture, training setup, and results.

Any help filling in the gaps would be appreciated.

答:
model.to_json() can be used to convert model config into json format and save it as a json.
You can recreate the model from json using model_from_json found in keras.models

Weights can be saved separately using model.save_weights.
Useful in checkpointing your model. Note that model.save saves both of these together. Saving only the weights and loading them back useful when you need to work with the variables used in defining the model. In that case create the model using the code and do model.load_weights.


问:
PowerBi List of all workspaces and users within - Newbie Question
My job entails me rotating through different parts of our IT Team. I recently moved to our Analytics department and found myself utilizing Powershell to retrieve data for Power BI. Bear with me here as I am new to this...

My goal is to generate a list of all the workspaces in our organization and the users correlated with each workspace. In general we want to try to get a wider-view on what is taking place within our tenant.

I've tried each of these methods with no success.

https://powershell.org/forums/topic/powerbi-query-trying-to-list-workspaces-and-users/

How to extract all PowerBI users and workspace access using the PowerBI API or Azure Portal?

Ive also tried to run the command below but get the error of "System.Linq.Enumerable+WhereSelectListIterator`2" when it should be the user info.

```<code>Get-PowerBIWorkspace -Scope Organization -Include All -All |select-object | export-csv c:\temp\powerbiworkspaces.csv -NoTypeInformation
</code>```

Any help would be greatly appreciated..

Thank you in advance,

答:
After struggling a bit I ended up re-purposing the code from the one link. This worked for me therefore ill leave this up.</p>

```<code>#Gets User, workspace, workspaceId
Get-PowerBIWorkspace -Scope Organization -Include All -All  |
ForEach-Object {
$Workspace = $_.name
$WorkspaceId = $_.Id
foreach ($User in $_.Users) {
[PSCustomObject]@{
Workspace = $Workspace
WorkspaceId = $WorkspaceId
User = $User.accessright
Identifier   =$user.Identifier}}} | Export-CSV "C:\Temp\WorkspaceDetails.csv" -NoTypeInformation
</code>```

Body:
My job entails me rotating through different parts of our IT Team. I recently moved to our Analytics department and found myself utilizing Powershell to retrieve data for Power BI. Bear with me here as I am new to this...

My goal is to generate a list of all the workspaces in our organization and the users correlated with each workspace. In general we want to try to get a wider-view on what is taking place within our tenant.

I've tried each of these methods with no success.

https://powershell.org/forums/topic/powerbi-query-trying-to-list-workspaces-and-users/

How to extract all PowerBI users and workspace access using the PowerBI API or Azure Portal?

Ive also tried to run the command below but get the error of "System.Linq.Enumerable+WhereSelectListIterator`2" when it should be the user info.

Get-PowerBIWorkspace -Scope Organization -Include All -All |select-object | export-csv c:\temp\powerbiworkspaces.csv -NoTypeInformation

Any help would be greatly appreciated..

Thank you in advance,

Body:
After struggling a bit I ended up re-purposing the code from the one link. This worked for me therefore ill leave this up.

#Gets User, workspace, workspaceId
Get-PowerBIWorkspace -Scope Organization -Include All -All  |
ForEach-Object {
$Workspace = $_.name
$WorkspaceId = $_.Id
foreach ($User in $_.Users) {
[PSCustomObject]@{
Workspace = $Workspace
WorkspaceId = $WorkspaceId
User = $User.accessright
Identifier   =$user.Identifier}}} | Export-CSV "C:\Temp\WorkspaceDetails.csv" -NoTypeInformation


问:
Change default RUNPY directory in UniVerse
I have UniVerse 11.3.1, and have been taking advantage of Rocket's u2py module to run python code. Overall, this has been great. When calling python code from PICK I usually do PyCallFunction. However I have a number of scripts I run directly from the RUNPY command in TCL.

In refactoring some of my directories I am moving away from having the PP directory house my python code. I can call my scripts from a new directory, say PYSCRIPTS, but it means if I have a bash or TCL script that calls RUNPY I now have to explicitly call out which directory I call it from:

RUNPY PYSCRIPTS test.py instead of RUNPY test.py.

Is there a way to change the default directory that RUNPY looks in? Is this related to PYTHONPATH configuration, or is this hard-coded in the UniVerse binary? A minor inconvenience, but I would rather handle the parent directory of these scripts via configuration vs hard-coding them.

答:
The crusty old UniVerse guy in me says use a VOC entry, but that will only work in the Account you put it in.

```<code>>ED VOC RUNPY2
New record.

----: I
0001= S
0002= RUNPY PYSCRIPTS
0003=
Bottom at line 2.
----: FI
"RUNPY2" filed in file "VOC".
</code>```

However that doesn't solve your BASH requirement. For that I think there is some pathing info in a .pth file in each account.

You probably want to get a hold of the document titled "U2Python User Guide" for your version and look for the section on .pth files. These hold some path related variables. There are warnings there about some of the variables being overwritten on upgrade, and I have no first hand experience which is why I am being unreasonably vague about what you should do.

Good Luck

Body:
The crusty old UniVerse guy in me says use a VOC entry, but that will only work in the Account you put it in.

>ED VOC RUNPY2
New record.

----: I
0001= S
0002= RUNPY PYSCRIPTS
0003=
Bottom at line 2.
----: FI
"RUNPY2" filed in file "VOC".

However that doesn't solve your BASH requirement. For that I think there is some pathing info in a .pth file in each account.

You probably want to get a hold of the document titled "U2Python User Guide" for your version and look for the section on .pth files. These hold some path related variables. There are warnings there about some of the variables being overwritten on upgrade, and I have no first hand experience which is why I am being unreasonably vague about what you should do.

Good Luck


问:
Installing Switch.pm in Active perl on windows 10
I'm trying to get a Perl script running on Windows 10 with Active Perl 5.28.1. It currently runs on windows 7 with Active Perl 5.8.8.  When I try to run it I get:

```<code>Can't locate Switch.pm in @INC (you may need to install the Switch module) (@INC contains: C:\Perl\lib C:/Perl64/site/lib C:/Perl64/lib) at fds_propagator_with_collision_ephem.pl line 108.
</code>```

So I tried to install Switch.pm.  I started cpan and then did install Switch.pm

I got:

```<code>C:\Users\rdirosar>cpan
Loading internal logger. Log::Log4perl recommended for better logging

cpan shell -- CPAN exploration and modules installation (v2.20)
Enter 'h' for help.

cpan> install Switch.pm

Reading 'C:\Perl64\cpan\sources\authors\01mailrc.txt.gz'
Use of uninitialized value $command in concatenation (.) or string at C:\Perl64\lib/CPAN/Tarzip.pm line 163, <IN> line 1.

'-qdt' is not recognized as an internal or external command,
operable program or batch file.
............................................................................DONE

Reading 'C:\Perl64\cpan\sources\modules\02packages.details.txt.gz'
Use of uninitialized value $command in concatenation (.) or string at C:\Perl64\lib/CPAN/Tarzip.pm line 163.
'-qdt' is not recognized as an internal or external command,
operable program or batch file.

Warning: Your C:\Perl64\cpan\sources\modules\02packages.details.txt.gz does not contain a Line-Count header.
Please check the validity of the index file by comparing it to more
than one CPAN mirror. I'll continue but problems seem likely to
happen.
Warning: Your C:\Perl64\cpan\sources\modules\02packages.details.txt.gz does not contain a Last-Updated header.
Please check the validity of the index file by comparing it to more
than one CPAN mirror. I'll continue but problems seem likely to
happen.
.Could not split line["┬0\cL²\cU\c?└'≈\cCé"]

Could not split line["c▐X'Γπ"├█\cP\cE?▀&δ┌╠5α%â╛mτl∞Bô⌠ñg▒R\cI¥\cT\cP╘≈\cX."]

Could not split line["V╟\c]\$≈»1"]

Could not split line["a\cVk\cQ0y│ôδNj+╒1<c;¼òPb╪Zà⌠∞\cBl≥┤h\cRU\cPFÄ┴▄4û\cIƒ\@⌐╜─b*QZ\$lEX╞╔■î>∩îÅ=\cF┬N;│¼-\cZu¿fÆh\eD"]

Giving up parsing your C:\Perl64\cpan\sources\modules\02packages.details.txt.gz, too many errorsReading 'C:\Perl64\cpan\sources\authors\01mailrc.txt.gz'

Use of uninitialized value $command in concatenation (.) or string at C:\Perl64\lib/CPAN/Tarzip.pm line 163.

'-qdt' is not recognized as an internal or external command,
operable program or batch file.
............................................................................DONE

Reading 'C:\Perl64\cpan\sources\modules\02packages.details.txt.gz'

Use of uninitialized value $command in concatenation (.) or string at C:\Perl64\lib/CPAN/Tarzip.pm line 163.

'-qdt' is not recognized as an internal or external command,
operable program or batch file.

Warning: Your C:\Perl64\cpan\sources\modules\02packages.details.txt.gz does not contain a Line-Count header.

Please check the validity of the index file by comparing it to more
than one CPAN mirror. I'll continue but problems seem likely to happen.

Warning: Your C:\Perl64\cpan\sources\modules\02packages.details.txt.gz does not contain a Last-Updated header.

Please check the validity of the index file by comparing it to more
than one CPAN mirror. I'll continue but problems seem likely to
happen.

.Could not split line["┬0\cL²\cU\c?└'≈\cCé"]

Could not split line["c▐X'Γπ"├█\cP\cE?▀&δ┌╠5α%â╛mτl∞Bô⌠ñg▒R\cI¥\cT\cP╘≈\cX."]

Could not split line["V╟\c]\$≈»1"]

Could not split line["a\cVk\cQ0y│ôδNj+╒1<c;¼òPb╪Zà⌠∞\cBl≥┤h\cRU\cPFÄ┴▄4û\cIƒ\@⌐╜─b*QZ\$lEX╞╔■î>∩îÅ=\cF┬N;│¼-\cZu¿fÆh\eD"]

Giving up parsing your C:\Perl64\cpan\sources\modules\02packages.details.txt.gz, too many errorsLockfile removed.

C:\Users\rdirosar>
</code>```

I tried deleting the files in:
C:\Perl64\cpan\sources\authors and C:\Perl64\cpan\sources\modules\
That had no effect, if there are files in the directories they are updated
as needed.

What am I doing wrong?
Robert

note: I found I needed to add some cr/lf to the text, otherwise I would get a error message about code not being formated correctly.

答:
According to https://www.activestate.com/blog/goodbye-ppm-hello-state-tool/ ActivePerl 5.28 has removed the old PPM interactive GUI module installation tool in favor of the new https://platform.activestate.com/ website where you log in, pick modules, builds, waits and finally downloads your own custom runtime as one big .exe or .msi file (on windows anyways).

This installation file includes ActivePerl 5.28 and the modules you picked.

In my test on Windows 10 the Switch module was installed without trouble like this.

Other alternatives might be:

Perl 5.26 where PPM a is still available I think, find it at activestate.com

use the CPAN command from 5.28, but for many if not most modules you need make or dmake. The latter is perhaps easiest available through http://www.mingw.org/

Use WSL - windows subsystem for linux. There apt or yum or similar command for your flavour of linux are available. Easy and dependable way to install Perl modules. In my experience. But this isn't ActivePerl, it's barely Windows, it's mostly Gnu/Linux

Strawberry-Perl for Windows

Switch seems to be (judging by a very quick glance now) just a pure perl module that does not depend on other non-core modules. So you can just download the file from https://fastapi.metacpan.org/source/CHORNY/Switch-2.17/Switch.pm and place it in one of the folders output from perl -le'print for @INC' and make sure the file is readable by the system user.

Body:
I'm trying to get a Perl script running on Windows 10 with Active Perl 5.28.1. It currently runs on windows 7 with Active Perl 5.8.8.  When I try to run it I get:

Can't locate Switch.pm in @INC (you may need to install the Switch module) (@INC contains: C:\Perl\lib C:/Perl64/site/lib C:/Perl64/lib) at fds_propagator_with_collision_ephem.pl line 108.

So I tried to install Switch.pm.  I started cpan and then did install Switch.pm

I got:

C:\Users\rdirosar>cpan
Loading internal logger. Log::Log4perl recommended for better logging

cpan shell -- CPAN exploration and modules installation (v2.20)
Enter 'h' for help.

cpan> install Switch.pm

Reading 'C:\Perl64\cpan\sources\authors\01mailrc.txt.gz'
Use of uninitialized value $command in concatenation (.) or string at C:\Perl64\lib/CPAN/Tarzip.pm line 163, <IN> line 1.

'-qdt' is not recognized as an internal or external command,
operable program or batch file.
............................................................................DONE

Reading 'C:\Perl64\cpan\sources\modules\02packages.details.txt.gz'
Use of uninitialized value $command in concatenation (.) or string at C:\Perl64\lib/CPAN/Tarzip.pm line 163.
'-qdt' is not recognized as an internal or external command,
operable program or batch file.

Warning: Your C:\Perl64\cpan\sources\modules\02packages.details.txt.gz does not contain a Line-Count header.
Please check the validity of the index file by comparing it to more
than one CPAN mirror. I'll continue but problems seem likely to
happen.
Warning: Your C:\Perl64\cpan\sources\modules\02packages.details.txt.gz does not contain a Last-Updated header.
Please check the validity of the index file by comparing it to more
than one CPAN mirror. I'll continue but problems seem likely to
happen.
.Could not split line["┬0\cL²\cU\c?└'≈\cCé"]

Could not split line["c▐X'Γπ"├█\cP\cE?▀&δ┌╠5α%â╛mτl∞Bô⌠ñg▒R\cI¥\cT\cP╘≈\cX."]

Could not split line["V╟\c]\$≈»1"]

Could not split line["a\cVk\cQ0y│ôδNj+╒1<c;¼òPb╪Zà⌠∞\cBl≥┤h\cRU\cPFÄ┴▄4û\cIƒ\@⌐╜─b*QZ\$lEX╞╔■î>∩îÅ=\cF┬N;│¼-\cZu¿fÆh\eD"]

Giving up parsing your C:\Perl64\cpan\sources\modules\02packages.details.txt.gz, too many errorsReading 'C:\Perl64\cpan\sources\authors\01mailrc.txt.gz'

Use of uninitialized value $command in concatenation (.) or string at C:\Perl64\lib/CPAN/Tarzip.pm line 163.

'-qdt' is not recognized as an internal or external command,
operable program or batch file.
............................................................................DONE

Reading 'C:\Perl64\cpan\sources\modules\02packages.details.txt.gz'

Use of uninitialized value $command in concatenation (.) or string at C:\Perl64\lib/CPAN/Tarzip.pm line 163.

'-qdt' is not recognized as an internal or external command,
operable program or batch file.

Warning: Your C:\Perl64\cpan\sources\modules\02packages.details.txt.gz does not contain a Line-Count header.

Please check the validity of the index file by comparing it to more
than one CPAN mirror. I'll continue but problems seem likely to happen.

Warning: Your C:\Perl64\cpan\sources\modules\02packages.details.txt.gz does not contain a Last-Updated header.

Please check the validity of the index file by comparing it to more
than one CPAN mirror. I'll continue but problems seem likely to
happen.

.Could not split line["┬0\cL²\cU\c?└'≈\cCé"]

Could not split line["c▐X'Γπ"├█\cP\cE?▀&δ┌╠5α%â╛mτl∞Bô⌠ñg▒R\cI¥\cT\cP╘≈\cX."]

Could not split line["V╟\c]\$≈»1"]

Could not split line["a\cVk\cQ0y│ôδNj+╒1<c;¼òPb╪Zà⌠∞\cBl≥┤h\cRU\cPFÄ┴▄4û\cIƒ\@⌐╜─b*QZ\$lEX╞╔■î>∩îÅ=\cF┬N;│¼-\cZu¿fÆh\eD"]

Giving up parsing your C:\Perl64\cpan\sources\modules\02packages.details.txt.gz, too many errorsLockfile removed.

C:\Users\rdirosar>

I tried deleting the files in:
C:\Perl64\cpan\sources\authors and C:\Perl64\cpan\sources\modules\
That had no effect, if there are files in the directories they are updated
as needed.

What am I doing wrong?
Robert

note: I found I needed to add some cr/lf to the text, otherwise I would get a error message about code not being formated correctly.


问:
Character encoding
For this piece of code:

```<code>String content = String.Empty;
ListenerStateObject state = (ListenerStateObject)ar.AsyncState;
Socket handler = state.workSocket;

int bytesRead = handler.EndReceive(ar);

if (bytesRead > 0)
{
   state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));

   content = state.sb.ToString();
   ...
</code>```

I'm geting 'Ol?' instead of 'Olá'

What's wrong with it?

答: Are you outputting the result into something that understands 'complex' encoding?</p>

Title: Character encoding

Body:
For this piece of code:

String content = String.Empty;
ListenerStateObject state = (ListenerStateObject)ar.AsyncState;
Socket handler = state.workSocket;

int bytesRead = handler.EndReceive(ar);

if (bytesRead > 0)
{
   state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));

   content = state.sb.ToString();
   ...

I'm geting 'Ol?' instead of 'Olá'

What's wrong with it?


问:
Count number of ways to reach a score
I am working on a task where I have a number now I want to know how many ways to reach to this number using 2,3,6 using additions and I can use a number as many number of times as possible.

1st Example:

```<code>Given number is 6
There are 3 ways to reach to this number:
2 +2 + 2 = 2*3
3 + 3 = 3*2
6
</code>```

2nd Example:

```<code>Given number is 5
There are 2 ways to reach to this number:
2+3
3+2 (order matters here)
</code>```

I have come up with below code with help of this link:

```<code>static int count(int n) {
    // table[i] will store count of solutions for
    // value i.
    int table[] = new int[n + 1], i;

    // Base case (If given value is 0)
    table[0] = 1;

    // One by one consider given 3
    // moves and update the table[]
    // values after the index greater
    // than or equal to the value of
    // the picked move
    for (i = 2; i <= n; i++)
        table[i] += table[i - 2];
    for (i = 3; i <= n; i++)
        table[i] += table[i - 3];
    for (i = 6; i <= n; i++)
        table[i] += table[i - 6];

    return table[n];
}
</code>```

This code is working only for 1st example, but not working for 2nd example because the program is returning 1 instead of 2.

How to fix this issue?

答:
You count the number of solutions, without taking into account the order of the elements.

For example, for n = 5, 2 + 3 count for one element only,3 + 2is considered as the same solution.

To get the result that you are looking for, you need two modifications:

Instead of counting the number of solutions, you have to memorize all the corresponding solutions. At this level, you don't need to take the order in consideration, just memorize the number of 2, 3, 6 corresponding to one solution. This allows you to keep the same program structure, basically the same efficient algorithm.

Then, for each particular solution (x, y, z), where x, y, z are the multiplicities associated to 2, 3, 6, you have to evaluate the number of possibilities N(x, y, z) obtained by modifying the order of the elements.

The corresponding number of solutions is :

```<code>N(x, y, z) = C(s, x) * C(s-x, y) * C(s-x-z, z)
</code>```

Where s = x+y+z and the C(n, p) are the binomial coefficients

Note that the last factor is equal to C(z, z) = 1.

Title: Count number of ways to reach a score

Body:
I am working on a task where I have a number now I want to know how many ways to reach to this number using 2,3,6 using additions and I can use a number as many number of times as possible.

1st Example:

Given number is 6
There are 3 ways to reach to this number:
2 +2 + 2 = 2*3
3 + 3 = 3*2
6

2nd Example:

Given number is 5
There are 2 ways to reach to this number:
2+3
3+2 (order matters here)

I have come up with below code with help of this link:

static int count(int n) {
    // table[i] will store count of solutions for
    // value i.
    int table[] = new int[n + 1], i;

    // Base case (If given value is 0)
    table[0] = 1;

    // One by one consider given 3
    // moves and update the table[]
    // values after the index greater
    // than or equal to the value of
    // the picked move
    for (i = 2; i <= n; i++)
        table[i] += table[i - 2];
    for (i = 3; i <= n; i++)
        table[i] += table[i - 3];
    for (i = 6; i <= n; i++)
        table[i] += table[i - 6];

    return table[n];
}

This code is working only for 1st example, but not working for 2nd example because the program is returning 1 instead of 2.

How to fix this issue?

Body:
You count the number of solutions, without taking into account the order of the elements.

For example, for n = 5, 2 + 3 count for one element only,3 + 2is considered as the same solution.

To get the result that you are looking for, you need two modifications:

Instead of counting the number of solutions, you have to memorize all the corresponding solutions. At this level, you don't need to take the order in consideration, just memorize the number of 2, 3, 6 corresponding to one solution. This allows you to keep the same program structure, basically the same efficient algorithm.

Then, for each particular solution (x, y, z), where x, y, z are the multiplicities associated to 2, 3, 6, you have to evaluate the number of possibilities N(x, y, z) obtained by modifying the order of the elements.

The corresponding number of solutions is :

N(x, y, z) = C(s, x) * C(s-x, y) * C(s-x-z, z)

Where s = x+y+z and the C(n, p) are the binomial coefficients

Note that the last factor is equal to C(z, z) = 1.


问:
How skip config.middleware.use for a specific controller action in Rails 5
Is there a way to setup config.middleware.use to exclude / ignore / skip a specific controller action?

For example, if I wanted to exclude the Post#show controller action.

I'm using https://github.com/railslove/rack-tracker to test Google Analytics/Tag Manager.

```<code>  # Rack Tracker config
  config.middleware.use(Rack::Tracker) do
    handler :google_tag_manager, { container: ENV['GTM_CONTAINER_ID'] }
  end
</code>```

I thought I could use a condition like:

```<code>  # Rack Tracker config
  config.middleware.use(Rack::Tracker) do
    handler :google_tag_manager, { container: ENV['GTM_CONTAINER_ID'] } if app.route != ApplicationController::PostController.show
  end
</code>```

Any help is much appreciated.

答:
You can also check the values of env['action_controller.instance'].params['controller'] and env['action_controller.instance'].params['action'], so in your case:

```<code>class ConditionalTracker
  def initialize(app)
    @app = app
  end

  def call(env)
    if env['action_controller.instance'].params['controller'] == 'posts' &&
       env['action_controller.instance'].params['action'] == 'show'
      tracker = Rack::Tracker.new(@app) do
        handler :google_tag_manager, { container: ENV['GTM_CONTAINER_ID'] }
      end
      env = tracker.call(env)
    end

    @app.call(env)
  end
end
</code>```

Body:
Is there a way to setup config.middleware.use to exclude / ignore / skip a specific controller action?

For example, if I wanted to exclude the Post#show controller action.

I'm using https://github.com/railslove/rack-tracker to test Google Analytics/Tag Manager.

  # Rack Tracker config
  config.middleware.use(Rack::Tracker) do
    handler :google_tag_manager, { container: ENV['GTM_CONTAINER_ID'] }
  end

I thought I could use a condition like:

  # Rack Tracker config
  config.middleware.use(Rack::Tracker) do
    handler :google_tag_manager, { container: ENV['GTM_CONTAINER_ID'] } if app.route != ApplicationController::PostController.show
  end

Any help is much appreciated.

Body:
You can also check the values of env['action_controller.instance'].params['controller'] and env['action_controller.instance'].params['action'], so in your case:

class ConditionalTracker
  def initialize(app)
    @app = app
  end

  def call(env)
    if env['action_controller.instance'].params['controller'] == 'posts' &&
       env['action_controller.instance'].params['action'] == 'show'
      tracker = Rack::Tracker.new(@app) do
        handler :google_tag_manager, { container: ENV['GTM_CONTAINER_ID'] }
      end
      env = tracker.call(env)
    end

    @app.call(env)
  end
end


问:
Remove whitespace above div in react app
I have a problem where I have created a header component but there is still whitespace above the header on every page I pull the header component in

this is my entire header component:

```<code>import React from 'react';
import { Link } from 'react-router';
import './index.scss';

export default class Header extends React.Component {

  render() {
    return(
      <div className="container">
        <ul>
          <div className="links">
              <li><Link to="quizzes">Quizzes</Link></li>
            </div>
            <div className="links">
              <li><Link to="categories">Categories</Link></li>
            </div>
            <div className="links">
              <li><Link to="create">Create</Link></li>
          </div>
        </ul>
      </div>
    )
  }
}
</code>```

and this is my entire css

```<code>body {
  margin: 0;
}
.container {
  margin: 0;
  background-color: #bec0c4;
  height: 50px;
  width: 100%;
}
.container ul{
  display: flex;
  flex-direction: row;
  font-size: 20px;
  justify-content: space-between;
  list-style-type: none;
  width: 90%;
}
</code>```

I have seen many answers saying to set the margin to 0 but this is still giving me whitespace at the top. if i set margin-top to -20px, it removes it but i dont like this solution

答:
If you apply a reset.css on your code, ensure your page loads this reset.css. If you are loading it from the homepage for example -index.js-, and then you open your browser directly on, let's said about_us' page -about_us.js-, then if about.us.js fails to load the reset.css you will have a standard page with all the browser's default styles.

So, always ensure you are loading your reset.css on all your routes to avoid default browsers' page overflowing.

Body:
I have a problem where I have created a header component but there is still whitespace above the header on every page I pull the header component in

this is my entire header component:

import React from 'react';
import { Link } from 'react-router';
import './index.scss';

export default class Header extends React.Component {

  render() {
    return(

<Link to="quizzes">Quizzes</Link>

<Link to="categories">Categories</Link>

<Link to="create">Create</Link>

    )
  }
}

and this is my entire css

body {
  margin: 0;
}
.container {
  margin: 0;
  background-color: #bec0c4;
  height: 50px;
  width: 100%;
}
.container ul{
  display: flex;
  flex-direction: row;
  font-size: 20px;
  justify-content: space-between;
  list-style-type: none;
  width: 90%;
}

I have seen many answers saying to set the margin to 0 but this is still giving me whitespace at the top. if i set margin-top to -20px, it removes it but i dont like this solution


问:
Failing to display image from server directory file
I'm failing to display the contents of "uploads" folder.

On the website I've uploaded the image and it goes into the server directory file/ the uploads folder, and then it should fetch and display the image, but it doesn't. Thanks for reading this, I'm happy to hear your suggestions.

```<code>    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

//This is me trying to display the image (all this is in the index.file <main> where my server.php file is included (<?php require_once 'server.php'; ?>)) -
    <td><?php echo '<img src="'.$target_dir.'" width="100" height="100">'; ?></td>

<main>
<?php require_once 'edit-carteri-server.php'; ?>

<?php

if (isset($_SESSION['message'])): ?>

<div class="alert alert-<?=$_SESSION['msg_type']?>">

    <?php
        echo $_SESSION['message'];
        unset($_SESSION['message']);
    ?>
</div>
<?php endif ?>

<div class="container">
<?php
    $mysqli = new mysqli('localhost', 'root', '', 'id12522465_admin') or die(mysqli_error($mysqli));        //Savieno ar datubāzi
    $result = $mysqli->query("SELECT * FROM carteri") or die($mysqli->error);
 ?>

<div class="row justify-content-center">
    <table class="table">
        <thead>
            <tr>
                <th>Bilde</th>
                <th>Valsts</th>
                <th>Teksts</th>
                <th colspan="2">Action</th>
            </tr>
<?php

    while ($row = $result->fetch_assoc()): ?>
        <tr>
            <td><?php echo '<img src="'.$target_file.'" width="100" height="100">'; ?></td>
            <td><?php echo $row['valsts']; ?></td>
            <td><?php echo $row['teksts']; ?></td>
            <td>
                <a href="edit-carteri.php?edit=<?php echo $row['id']; ?>"
                    class="btn btn-info">Edit</a>
                <a href="edit-carteri-server.php?delete=<?php echo $row['id']; ?>"
                    class="btn btn-danger">Delete</a>
            </td>
        </tr>
<?php endwhile; ?>
        </thead>
    </table>
</div>
</code>```

答:
To display an image, src must point to the path of an image.
Try replacing $target_dir by $target_file.

Body:
I'm failing to display the contents of "uploads" folder.

On the website I've uploaded the image and it goes into the server directory file/ the uploads folder, and then it should fetch and display the image, but it doesn't. Thanks for reading this, I'm happy to hear your suggestions.

    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

//This is me trying to display the image (all this is in the index.file  where my server.php file is included (<?php require_once 'server.php'; ?>)) -
    <?php echo ''; ?>

<?php require_once 'edit-carteri-server.php'; ?>

<?php

if (isset($_SESSION['message'])): ?>

<div class="alert alert-<?=$_SESSION['msg_type']?>">

    <?php
        echo $_SESSION['message'];
        unset($_SESSION['message']);
    ?>

<?php endif ?>

<?php
    $mysqli = new mysqli('localhost', 'root', '', 'id12522465_admin') or die(mysqli_error($mysqli));        //Savieno ar datubāzi
    $result = $mysqli->query("SELECT * FROM carteri") or die($mysqli->error);
 ?>

                Bilde
                Valsts
                Teksts
                Action

<?php

    while ($row = $result->fetch_assoc()): ?>

            <?php echo ''; ?>
            <?php echo $row['valsts']; ?>
            <?php echo $row['teksts']; ?>

                <a href="edit-carteri.php?edit=<?php echo $row['id']; ?>"
                    class="btn btn-info">Edit
                <a href="edit-carteri-server.php?delete=<?php echo $row['id']; ?>"
                    class="btn btn-danger">Delete

<?php endwhile; ?>


问:
Getting the starting point of a cumulative Percent of Total using SQL
I need to return records based on what their "Percent of Total" is. So, for example, I might want to know the "Top 10% of Sales by Customer".

Currently, I'm using this:

```<code>SELECT * FROM (SELECT Dim1, SUM(SQ_Fact1) AS Fact1,
(SUM(SUM(SQ_Fact1)) OVER(ORDER BY SUM(SQ_Fact1) DESC))/SUM(SUM(SQ_Fact1)) OVER() AS PctOfTtl
FROM (SELECT Customer AS Dim1, SUM(Sales) AS SQ_Fact1
FROM SalesHistory GROUP BY Customer) AS sq
GROUP BY Dim1) AS mq
WHERE PctOfTtl<=0.10
</code>```

This is a little overly complicated, but it's part of a query-building UI, so it creates a subquery and "main" outer query for all queries (for reasons unrelated to this), then it has to use another outer query around those to check the PctOfTtl. Regardless, the line that gets the cumulative percent of total (and sorts it descending, so I can get the "top" records) is:

```<code>(SUM(SUM(SQ_Fact1)) OVER(ORDER BY SUM(SQ_Fact1) DESC))/SUM(SUM(SQ_Fact1)) OVER() AS PctOfTtl
</code>```

And then in the outer query, I limit what Percents of Total I return by saying "WHERE PctOfTtl<=0.10"

The problem is, the PctOfTtl tells me where their percent of total ends, not where it starts.

So, lets say the top Customer makes up 15% of the Sales. It will have a PctOfTtl of 0.15. The problem is, if the user asks for Customers in the Top 10% of Sales (<=0.1), it will return no records, because the top-most Customer doesn't "end" until 0.15, so their PctOfTtl won't be <=0.1. What I need to know is where their percent of total starts (i.e. the top-most customer will start at 0, and the second will start at 0.15, etc). What I'm really looking for is any customers whose percent of total "range" falls anywhere IN the percent that the user specifies (even if it extends beyond it).

The problem is, like I said, this is for a query-building UI, so I can't completely restructure the query in order to do this. It has to work within the confines of the existing "subquery/main query" format, which using the "OVER" clause does. I can just check if they're employing a "Top %" filter, and if so, tack on the PctOfTtl column and surround the query with an outer query that limits the PctOfTtl. Basically, what I'm hoping to find is a way to use OVER() that will tell me what the PctOfTtl is minus the PctOfTtl "before" it.

答:
Try subtracting out the current value:</p>

```<code>SELECT *
FROM (SELECT Dim1, SUM(SQ_Fact1) AS Fact1,
             SUM(SQ_Fact1) / SUM(SUM(SQ_Fact1)) OVER () as PctOfTtl
             (SUM(SUM(SQ_Fact1)) OVER (ORDER BY SUM(SQ_Fact1) DESC))/SUM(SUM(SQ_Fact1)) OVER () AS Running_PctOfTtl
      FROM (SELECT Customer AS Dim1, SUM(Sales) SQ_Fact1
            FROM SalesHistory
            GROUP BY Customer
           ) sq
      GROUP BY Dim1
     ) mq
WHERE Running_PctOfTtl - PctOfTtl < 0.10;
</code>```

Body:
I need to return records based on what their "Percent of Total" is. So, for example, I might want to know the "Top 10% of Sales by Customer".

Currently, I'm using this:

SELECT * FROM (SELECT Dim1, SUM(SQ_Fact1) AS Fact1,
(SUM(SUM(SQ_Fact1)) OVER(ORDER BY SUM(SQ_Fact1) DESC))/SUM(SUM(SQ_Fact1)) OVER() AS PctOfTtl
FROM (SELECT Customer AS Dim1, SUM(Sales) AS SQ_Fact1
FROM SalesHistory GROUP BY Customer) AS sq
GROUP BY Dim1) AS mq
WHERE PctOfTtl<=0.10

This is a little overly complicated, but it's part of a query-building UI, so it creates a subquery and "main" outer query for all queries (for reasons unrelated to this), then it has to use another outer query around those to check the PctOfTtl. Regardless, the line that gets the cumulative percent of total (and sorts it descending, so I can get the "top" records) is:

(SUM(SUM(SQ_Fact1)) OVER(ORDER BY SUM(SQ_Fact1) DESC))/SUM(SUM(SQ_Fact1)) OVER() AS PctOfTtl

And then in the outer query, I limit what Percents of Total I return by saying "WHERE PctOfTtl<=0.10"

The problem is, the PctOfTtl tells me where their percent of total ends, not where it starts.

So, lets say the top Customer makes up 15% of the Sales. It will have a PctOfTtl of 0.15. The problem is, if the user asks for Customers in the Top 10% of Sales (<=0.1), it will return no records, because the top-most Customer doesn't "end" until 0.15, so their PctOfTtl won't be <=0.1. What I need to know is where their percent of total starts (i.e. the top-most customer will start at 0, and the second will start at 0.15, etc). What I'm really looking for is any customers whose percent of total "range" falls anywhere IN the percent that the user specifies (even if it extends beyond it).

The problem is, like I said, this is for a query-building UI, so I can't completely restructure the query in order to do this. It has to work within the confines of the existing "subquery/main query" format, which using the "OVER" clause does. I can just check if they're employing a "Top %" filter, and if so, tack on the PctOfTtl column and surround the query with an outer query that limits the PctOfTtl. Basically, what I'm hoping to find is a way to use OVER() that will tell me what the PctOfTtl is minus the PctOfTtl "before" it.

Body:
Try subtracting out the current value:

SELECT *
FROM (SELECT Dim1, SUM(SQ_Fact1) AS Fact1,
             SUM(SQ_Fact1) / SUM(SUM(SQ_Fact1)) OVER () as PctOfTtl
             (SUM(SUM(SQ_Fact1)) OVER (ORDER BY SUM(SQ_Fact1) DESC))/SUM(SUM(SQ_Fact1)) OVER () AS Running_PctOfTtl
      FROM (SELECT Customer AS Dim1, SUM(Sales) SQ_Fact1
            FROM SalesHistory
            GROUP BY Customer
           ) sq
      GROUP BY Dim1
     ) mq
WHERE Running_PctOfTtl - PctOfTtl < 0.10;


问:
what does the term `fac` mean in Haskell?
What does the term fac mean in Haskell? I've seen it on many occasions but it appears to not have any definition of being of any type. I know it has something to do with factorials but am not quite sure what people mean when they refer to the term fac.

Here's an example:

```<code>sumFacs n = fac 0 + fac 1 + ... + fac (n-1) + fac n
</code>```

答:
Usually fac refers to the factorial function, which can be defined as:

```<code>fac :: Int -> Int
fac 0 = 1
fac n = n * fac (n - 1)
</code>```

Of course, there are many different ways to define factorial in Haskell.

Body:
What does the term fac mean in Haskell? I've seen it on many occasions but it appears to not have any definition of being of any type. I know it has something to do with factorials but am not quite sure what people mean when they refer to the term fac.

Here's an example:

sumFacs n = fac 0 + fac 1 + ... + fac (n-1) + fac n

Body:
Usually fac refers to the factorial function, which can be defined as:

fac :: Int -> Int
fac 0 = 1
fac n = n * fac (n - 1)

Of course, there are many different ways to define factorial in Haskell.


问:
convert Apk to ios or both with the same codes (cross platforms)
Im an android developer , now i want my apps to be in iphones too, so is there any way to convert apk to ios or to write apps in android and ios with the same code ?</p>

答:
to write apps in android and ios with the same code?

There are a lot of cross-platform frameworks such as

React native(javascript language).

Xamarin Forms(C# language)

Flutter(dart language developed by Google)

to develops an application which could run in both android and iOS platform. All the above framework will have at least more than 70 percent common codebase and the rest of the pieces of code will be written in android and iOS for platform-specific functionality. React Native and Flutter are the trending frameworks

is there any way to convert apk to ios?

I believe it is not possible. Even if you manage to convert, apple has strict rules in installing third-party applications. Thereby you won't be able to install the app in iOS


问:
Typescript Compiler API: Generate the full properties arborescence of a Type Identifier
Given a type Identifier, I'm searching for a way to generate the full arborescence of an object type AST.
By example, if I have:

File1.ts

```<code>type Content = {
    title: string,
    image: string,
    dims: number[]
}
</code>```

File2.ts

```<code>type BlogPost = Pick<Content, 'title'|'image'>

type User {
    name: string,
    email: string,
    news: BlogPost[]
}
</code>```

File3.ts

```<code>const test: User = { ... };
</code>```

My code must be able to deduce, from the user identifier, a list like this one:

```<code>name
email
news.title
news.image
</code>```

I experimented several things by using checker.getTypeAtLocation, iterating across each property one by one, find the right symbol, and try to deduce properties' names.

But I think (hope) this method is too much to accomplish such simple things because I have to handle, in addition to object types, every possibility of types for the properties: Picks, Excludes, Array, Omit, KeyOf, ...

All I want is the list of properties of the final complete form of a type.

So my question is:

Does the Typescript Compiler API provide tools to help me in my quest?
By example, given a type like this one:

```<code>type Content = { title: string, id: number }
type Hello = Pick< Content, 'id' >
</code>```

Generate a final and complete AST like this:

```<code>type Hello = {
    id: number
}
</code>```

Thanks for your help

答:
All I want is the list of properties of the final complete form of a type.

Here's a fully contained example that shows how to do that:

```<code>// setup
import { Project, ts } from "@ts-morph/bootstrap";

const project = new Project();
const file = project.createSourceFile("./main.ts",
    `type Content = { title: string, id: number }; type Hello = Pick< Content, 'id' >`);
const typeChecker = project.createProgram().getTypeChecker();

// get type alias
const helloTypeAliasDec = file.statements.find(s => ts.isTypeAliasDeclaration(s)
    && s.name.getText(file) === "Hello")!;

// get the type alias' type
const type = typeChecker.getTypeAtLocation(helloTypeAliasDec);

// now loop over all its properties
for (const property of type.getProperties()) {
    const propertyType = typeChecker.getTypeOfSymbolAtLocation(property, helloTypeAliasDec);
    console.log("Name:", property.name, "Type:", typeChecker.typeToString(propertyType));
}
</code>```

Outputs: Name: id Type: number

Based on this information you should be able to construct an AST, but there are a few edge cases you might run into.

Body:
Given a type Identifier, I'm searching for a way to generate the full arborescence of an object type AST.
By example, if I have:

File1.ts

type Content = {
    title: string,
    image: string,
    dims: number[]
}

File2.ts

type BlogPost = Pick<Content, 'title'|'image'>

type User {
    name: string,
    email: string,
    news: BlogPost[]
}

File3.ts

const test: User = { ... };

My code must be able to deduce, from the user identifier, a list like this one:

name
email
news.title
news.image

I experimented several things by using checker.getTypeAtLocation, iterating across each property one by one, find the right symbol, and try to deduce properties' names.

But I think (hope) this method is too much to accomplish such simple things because I have to handle, in addition to object types, every possibility of types for the properties: Picks, Excludes, Array, Omit, KeyOf, ...

All I want is the list of properties of the final complete form of a type.

So my question is:

Does the Typescript Compiler API provide tools to help me in my quest?
By example, given a type like this one:

type Content = { title: string, id: number }
type Hello = Pick< Content, 'id' >

Generate a final and complete AST like this:

type Hello = {
    id: number
}

Thanks for your help

Body:
All I want is the list of properties of the final complete form of a type.

Here's a fully contained example that shows how to do that:

// setup
import { Project, ts } from "@ts-morph/bootstrap";

const project = new Project();
const file = project.createSourceFile("./main.ts",
    `type Content = { title: string, id: number }; type Hello = Pick< Content, 'id' >`);
const typeChecker = project.createProgram().getTypeChecker();

// get type alias
const helloTypeAliasDec = file.statements.find(s => ts.isTypeAliasDeclaration(s)
    && s.name.getText(file) === "Hello")!;

// get the type alias' type
const type = typeChecker.getTypeAtLocation(helloTypeAliasDec);

// now loop over all its properties
for (const property of type.getProperties()) {
    const propertyType = typeChecker.getTypeOfSymbolAtLocation(property, helloTypeAliasDec);
    console.log("Name:", property.name, "Type:", typeChecker.typeToString(propertyType));
}

Outputs: Name: id Type: number

Based on this information you should be able to construct an AST, but there are a few edge cases you might run into.


问:
alphabet split instead of word split using lists
so ive predefined a set of names in a list(lst1) and when the user inputs a name,which doesnt matches the ones in the pre defined list prints a message which returns the element which didnt match along with a message "doesnt belong to our family" but when i run this code, the name gets split into a list like for example instead of "Abby:doesnt belong to our family",it prints "a":doesnt belong...."b":doesnt belong and so on...

heres the code:

```<code>lst1=['john','undertaker','kane','randy']
a1=input().strip()
a=a1.split(',')

user_input=[str(i) for i in a]

for _input in user_input:
    for name in [str(i) for i in str(_input)]:
        if name not in lst1:
            print(f"{name}:Not in family")
</code>```

sample input:
1)Rey mysteiro
2)Randy

output:
1)rey mysterio
r:Not in family
e:Not in family
y:Not in family
 :Not in family
m:Not in family
y:Not in family
s:Not in family
t:Not in family
e:Not in family
r:Not in family
i:Not in family
o:Not in family

2)randy
r:Not in family
a:Not in family
n:Not in family
d:Not in family
y:Not in family

for some reason this is not working ,any suggestions to improve this code as well as tackle this problem is appreciated!Thanks for helping me out!

答:
This part:

```<code>user_input=[str(i) for i in a]
</code>```

is unnecessary, items in a are already strings. And so is this:

```<code>for name in [str(i) for i in str(_input)]:
</code>```

(this is the part that turns your word from _input into a list of letters).
Correct way of doing this:

```<code>lst1 = ['john','undertaker','kane','randy']
user_input = input().strip().split(',')
for name in user_input:
    if name not in lst1:
        print(f"{name}:Not in family")
</code>```

Body:
so ive predefined a set of names in a list(lst1) and when the user inputs a name,which doesnt matches the ones in the pre defined list prints a message which returns the element which didnt match along with a message "doesnt belong to our family" but when i run this code, the name gets split into a list like for example instead of "Abby:doesnt belong to our family",it prints "a":doesnt belong...."b":doesnt belong and so on...

heres the code:

lst1=['john','undertaker','kane','randy']
a1=input().strip()
a=a1.split(',')

user_input=[str(i) for i in a]

for _input in user_input:
    for name in [str(i) for i in str(_input)]:
        if name not in lst1:
            print(f"{name}:Not in family")

sample input:
1)Rey mysteiro
2)Randy

output:
1)rey mysterio
r:Not in family
e:Not in family
y:Not in family
 :Not in family
m:Not in family
y:Not in family
s:Not in family
t:Not in family
e:Not in family
r:Not in family
i:Not in family
o:Not in family

2)randy
r:Not in family
a:Not in family
n:Not in family
d:Not in family
y:Not in family

for some reason this is not working ,any suggestions to improve this code as well as tackle this problem is appreciated!Thanks for helping me out!

Body:
This part:

user_input=[str(i) for i in a]

is unnecessary, items in a are already strings. And so is this:

for name in [str(i) for i in str(_input)]:

(this is the part that turns your word from _input into a list of letters).
Correct way of doing this:

lst1 = ['john','undertaker','kane','randy']
user_input = input().strip().split(',')
for name in user_input:
    if name not in lst1:
        print(f"{name}:Not in family")


问:
Javascript object creation best practice
I have the following javascript :

```<code>            var MyObject = (function() {

                function Setup(args) {
                    this.prop1 = args.x;
                    this.prop2 = args.y
                    this.prop3 = this.prop1 + this.prop2;

                    this.Create = function() {
                        return 'a' + helperFunc();
                    }

                    function helperFunc() {
                        return this.prop3;
                    }
                }

                return {
                    init : function(args) {
                        var setup = new Setup(args);

                        setup.Create();
                    }
                }

            })();

            $(function() {

                MyObject.init(someArgs);

            });
</code>```

Is my approach to object construction a good practice?

I am getting undefined in the helperFunc when trying to access this.prop3.

I have also tried to assign this.prop1 + this.prop2 to a local variable and use a function to return this value like so:

```<code>        function Setup(args) {
                var total;

                this.prop1 = args.x;
                this.prop2 = args.y

                total = this.prop1 + this.prop2;
                this.getTotal = function() {
                        return total;
                };

                this.prop3 = this.prop1 + this.prop2;
                ...
</code>```

...and when calling this in the helperFunc like this:

```<code>                       return this.getTotal();
</code>```

.. i get this.getTotal is not a function

I have been reading around object creation and using closures to mimic private members and so on and since there is no one way to define objects I am getting confused.

TBH - I don't really understand the construct:

```<code>                       var myObject = (function() { ... } ();
</code>```

I've seen it used a lot in jQuery plugins but what does the first parenth followed by empty parenth at the end mean and do?

Any knowledge imparted would be much appreciated.

Also, I have on order the Douglas Crockford book on javascript and until it arrives I need to try to solve this problem

答:
You have a good tutorial by Mike Koss on OOP in JS on this page.

I've seen it used a lot in jQuery
  plugins but what does the first
  parenth followed by empty parenth at
  the end mean and do?

The second set of parenth immediatly invokes the function you have declared in the first set of parenth.

You could declare it and execute it separatly (allows to execute multiple times):

```<code>var myFunction = function() { alert("boo"); }; // Declare & instanciate
myFunction(); // Invoke
myFunction(); // Invoke again
</code>```

Or do both in one line:

```<code>(function() { alert("boo"); })(); // Can only invoke now, the function is anonymous and not stored anywhere.
</code>```

Body:
I have the following javascript :

            var MyObject = (function() {

                function Setup(args) {
                    this.prop1 = args.x;
                    this.prop2 = args.y
                    this.prop3 = this.prop1 + this.prop2;

                    this.Create = function() {
                        return 'a' + helperFunc();
                    }

                    function helperFunc() {
                        return this.prop3;
                    }
                }

                return {
                    init : function(args) {
                        var setup = new Setup(args);

                        setup.Create();
                    }
                }

            })();

            $(function() {

                MyObject.init(someArgs);

            });

Is my approach to object construction a good practice?

I am getting undefined in the helperFunc when trying to access this.prop3.

I have also tried to assign this.prop1 + this.prop2 to a local variable and use a function to return this value like so:

        function Setup(args) {
                var total;

                this.prop1 = args.x;
                this.prop2 = args.y

                total = this.prop1 + this.prop2;
                this.getTotal = function() {
                        return total;
                };

                this.prop3 = this.prop1 + this.prop2;
                ...

...and when calling this in the helperFunc like this:

                       return this.getTotal();

.. i get this.getTotal is not a function

I have been reading around object creation and using closures to mimic private members and so on and since there is no one way to define objects I am getting confused.

TBH - I don't really understand the construct:

                       var myObject = (function() { ... } ();

I've seen it used a lot in jQuery plugins but what does the first parenth followed by empty parenth at the end mean and do?

Any knowledge imparted would be much appreciated.

Also, I have on order the Douglas Crockford book on javascript and until it arrives I need to try to solve this problem

Body:
You have a good tutorial by Mike Koss on OOP in JS on this page.

I've seen it used a lot in jQuery
  plugins but what does the first
  parenth followed by empty parenth at
  the end mean and do?

The second set of parenth immediatly invokes the function you have declared in the first set of parenth.

You could declare it and execute it separatly (allows to execute multiple times):

var myFunction = function() { alert("boo"); }; // Declare & instanciate
myFunction(); // Invoke
myFunction(); // Invoke again

Or do both in one line:

(function() { alert("boo"); })(); // Can only invoke now, the function is anonymous and not stored anywhere.


问:
Obtains the name and ID of the dropped element
I am using the cdk drag and drop library to drag and drop objects.

My problem is that I am not able to obtain the data (object information: name and ID) of the dropped object.

I've tried using console.log (event.item.data) but it gives undefined.

Does anyone know how I can get the information about the dropped element?

Thanks

Stackblitz - Demo

.ts

```<code> drop(event: CdkDragDrop<string[]>) {
    console.log(event.item.data)
    if (event.previousContainer === event.container) {
      moveItemInArray(
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    } else {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    }
  }
</code>```

html

```<code><div class="six" style=" height: 75%;">
  <div class="card-deck cardsZone">
    <div class="card myCards">
      <div class="card-body" style="overflow-y: auto;"  #activeList="cdkDropList"
      class="box-list" style="height:100%"
      cdkDropList
      cdkDropListOrientation="vertical"
      [cdkDropListData]="A"
      [cdkDropListConnectedTo]="[inactiveList]"
      (cdkDropListDropped)="drop($event)">
        <div *ngFor="let nw of A" cdkDrag>
        <div class="card mysmallCcards">
          <div class="card-body">
                   <span>{{nw.name}}</span>
          </div>
        </div>
        </div>
      </div>
    </div>
    <div class="card myCards">
      <div class="card-body" style="overflow-y: auto;" #inactiveList="cdkDropList"
      class="box-list" style="height:100%"
      cdkDropList
      cdkDropListOrientation="vertical"
      [cdkDropListData]="B"
      [cdkDropListConnectedTo]="[activeList]"
      (cdkDropListDropped)="drop($event)">
        <div *ngFor="let pr of B" cdkDrag>
        <div class="card mysmallCcards">
          <div class="card-body">
           <span>{{pr.name}}</span>
          </div>
        </div>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

答:
Try with this:

event.previousContainer.data[event.previousIndex]

If you want the id of the item:

event.previousContainer.data[event.previousIndex]['id]

Body:
I am using the cdk drag and drop library to drag and drop objects.

My problem is that I am not able to obtain the data (object information: name and ID) of the dropped object.

I've tried using console.log (event.item.data) but it gives undefined.

Does anyone know how I can get the information about the dropped element?

Thanks

Stackblitz - Demo

.ts

 drop(event: CdkDragDrop<string[]>) {
    console.log(event.item.data)
    if (event.previousContainer === event.container) {
      moveItemInArray(
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    } else {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    }
  }

html

                   {{nw.name}}

           {{pr.name}}


问:
How to access value of child element in a object?
I want to access friends array of every user  (values of the array are user's id's) and return the value of the friend's array of the given user (friend)

```<code>const users = [
{
   "id": 1,
   "firstName": "Paul",
   "surname": "Crowe",
   "friends": [2]
 },
 {
   "id": 2,
   "firstName": "Rob",
   "surname": "Fitz",
   "friends": [1,3]
 },
 {
   "id": 3,
   "firstName": "Ben",
   "surname": "O'Carolan",
   "friends": [2]
 },
</code>```

This is what I have tried:

```<code>const fof = users.filter(user => {
      if (friend == user.id) {
        return true;
      }
    });
</code>```

答:
You can use filter method to find friend and then just map his friends:

```<code>const idPerson = 2;
const idFriends = users.filter(f => f.id == idPerson).flatMap(({friends})=> (friends));
const uniqueUsers = new Map(users.map(u => ([u.id, u])));
const friends = idFriends.map(id => ({...uniqueUsers.get(id)}));
</code>```

An example:

const users = [
    {
        "id": 1,
        "firstName": "Paul",
        "surname": "Crowe",
        "friends": [2]
    },
    {
        "id": 2,
        "firstName": "Rob",
        "surname": "Fitz",
        "friends": [1, 3]
    },
    {
        "id": 3,
        "firstName": "Ben",
        "surname": "O'Carolan",
        "friends": [2]
    }
];

const idPerson = 2;
const idFriends = users.filter(f => f.id == idPerson).flatMap(({friends})=> (friends));
const uniqueUsers = new Map(users.map(u => ([u.id, u])));
const friends = idFriends.map(id => ({...uniqueUsers.get(id)}));
console.log(friends);```

Body:
I want to access friends array of every user  (values of the array are user's id's) and return the value of the friend's array of the given user (friend)

const users = [
{
   "id": 1,
   "firstName": "Paul",
   "surname": "Crowe",
   "friends": [2]
 },
 {
   "id": 2,
   "firstName": "Rob",
   "surname": "Fitz",
   "friends": [1,3]
 },
 {
   "id": 3,
   "firstName": "Ben",
   "surname": "O'Carolan",
   "friends": [2]
 },

This is what I have tried:

const fof = users.filter(user => {
      if (friend == user.id) {
        return true;
      }
    });

Body:
You can use filter method to find friend and then just map his friends:

const idPerson = 2;
const idFriends = users.filter(f => f.id == idPerson).flatMap(({friends})=> (friends));
const uniqueUsers = new Map(users.map(u => ([u.id, u])));
const friends = idFriends.map(id => ({...uniqueUsers.get(id)}));

An example:

const users = [
    {
        "id": 1,
        "firstName": "Paul",
        "surname": "Crowe",
        "friends": [2]
    },
    {
        "id": 2,
        "firstName": "Rob",
        "surname": "Fitz",
        "friends": [1, 3]
    },
    {
        "id": 3,
        "firstName": "Ben",
        "surname": "O'Carolan",
        "friends": [2]
    }
];

const idPerson = 2;
const idFriends = users.filter(f => f.id == idPerson).flatMap(({friends})=> (friends));
const uniqueUsers = new Map(users.map(u => ([u.id, u])));
const friends = idFriends.map(id => ({...uniqueUsers.get(id)}));
console.log(friends);


问:
How do you stop a thead background color from leaking when there are rounded corners?
I have a table with rounded corners. I've specified a different background colour only for the thead.

On all browsers other than Firefox, the background colour leaks through the rounded corner. I've set overflow to hidden but that doesn't seem to help.

How can I stop the background colour from leaking through the rounded corner of the table?

Here's the code:
https://codepen.io/ayushn21/pen/OJVRMgG

Thanks!

答:
You can add cellspacing="0" to
 to remove the space between the table and cells. This will also solve your border radius issue with :

```

Body:
You can add cellspacing="0" to <table> to remove the space between the table and cells. This will also solve your border radius issue with <th>:

<table cellspacing="0"></table>