问:
Extract all the child nodes for a parent node from turtle file using SPARQL
I have following concepts in turtle file. I would like to extract preferred label and ids for parent node (DOID_4159) and all its child from below concepts. I have written following SPARQL query to fetch the information, but it will not give all the child nodes.

```<code>qres = g.query(
    """
    SELECT *
    WHERE {
    {?s skos:prefLabel ?prefLabel .
    ?s skos:broader  <http://purl.obolibrary.org/obo/DOID_4159>  .
    }
    UNION
    {?s skos:prefLabel "skin cancer"@en .
    ?s skos:prefLabel ?prefLabel .
    }
    }
    """)
</code>```
```<code><http://purl.obolibrary.org/obo/DOID_8923>
      a       skos:Concept ;
      skos:altLabel "malignant scalp melanoma"@en , "malignant lip melanoma"@en , "malignant melanoma of skin of upper limb"@en , "cutaneous melanoma"@en , "malignant melanoma of ear and/or external auricular canal"@en , "malignant trunk melanoma"@en , "malignant melanoma of skin of trunk except scrotum"@en , "malignant lower limb melanoma"@en , "malignant melanoma of skin of lower limb"@en , "malignant upper limb melanoma"@en , "malignant ear melanoma"@en , "malignant neck melanoma"@en ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_4159> ;
      skos:definition "A skin cancer that has_material_basis_in melanocytes." ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> ;

<http://purl.obolibrary.org/obo/DOID_3451>
      a       skos:Concept ;
      skos:altLabel "carcinoma of skin"@en ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_4159> ;
      skos:definition "A skin cancer that is located_in tissues of the skin and develops from epithelial cells." ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> ;
      skos:prefLabel "skin carcinoma"@en .
<http://purl.obolibrary.org/obo/DOID_6944>
      a       skos:Concept ;
      skos:altLabel "Seborrheic Keratosis of Vulva"@en ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_6498> , <http://purl.obolibrary.org/obo/DOID_4159> ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> ;
      skos:prefLabel "vulvar seborrheic keratosis"@en .
<http://purl.obolibrary.org/obo/DOID_4159>
      a       skos:Concept ;
      skos:altLabel "malignant neoplasm of skin"@en , "CA - skin cancer"@en , "melanoma and Non-melanoma skin cancer"@en ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_37> ;
      skos:definition "An integumentary system cancer located_in the skin that is the uncontrolled growth of abnormal skin cells." ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> ;
      skos:prefLabel "skin cancer"@en .
<http://purl.obolibrary.org/obo/DOID_11684>
      a       skos:Concept ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_6498> ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> ;
      skos:prefLabel "melanoacanthoma"@en .
</code>```
```<code>Following is the desired output:
id        label
DOID_8923 skin melanoma
DOID_3451 skin carcinoma
DOID_6944 vulvar seborrheic keratosis
DOID_4159 skin cancer
DOID_6498 seborrheic keratosis
DOID_11684 melanoacanthoma
</code>```

If I would like to fetch this information for parent (DOID_4159) and all its associated nodes, how can I achieve this? I am new to SPARQL, any help is highly appreciated.

答:
here we have some issues

The .ttl file you posted is not correct. There is an error on the definition of the 1st entity which is missing of the . at the end. So you have to update the definition from:

```<code><http://purl.obolibrary.org/obo/DOID_8923>
      a       skos:Concept ;
      skos:altLabel "malignant scalp melanoma"@en , "malignant lip melanoma"@en , "malignant melanoma of skin of upper limb"@en , "cutaneous melanoma"@en , "malignant melanoma of ear and/or external auricular canal"@en , "malignant trunk melanoma"@en , "malignant melanoma of skin of trunk except scrotum"@en , "malignant lower limb melanoma"@en , "malignant melanoma of skin of lower limb"@en , "malignant upper limb melanoma"@en , "malignant ear melanoma"@en , "malignant neck melanoma"@en ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_4159> ;
      skos:definition "A skin cancer that has_material_basis_in melanocytes." ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> ;
</code>```

To:

```<code><http://purl.obolibrary.org/obo/DOID_8923>
      a       skos:Concept ;
      skos:altLabel "malignant scalp melanoma"@en , "malignant lip melanoma"@en , "malignant melanoma of skin of upper limb"@en , "cutaneous melanoma"@en , "malignant melanoma of ear and/or external auricular canal"@en , "malignant trunk melanoma"@en , "malignant melanoma of skin of trunk except scrotum"@en , "malignant lower limb melanoma"@en , "malignant melanoma of skin of lower limb"@en , "malignant upper limb melanoma"@en , "malignant ear melanoma"@en , "malignant neck melanoma"@en ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_4159> ;
      skos:definition "A skin cancer that has_material_basis_in melanocytes." ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> .
</code>```

The . at the end, it means that the definition of your entity is complete. While the ; is used when you need to add other relationships.

The record DOID_8923 has no skos:prefLabel so, you are not able to retrieve the prefLabel from DOID_8923. You need to add the skos:prefLabel also to this entity

As already pointed out by UninformedUser
you have to specify the relation between DOID_11684 and DOID_4159 also in your schema

Here you can find your .ttl file updated and the transitive SPARQL query

```<code>@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix skos: <http://www.w3.org/2004/02/skos/core#> .

<http://purl.obolibrary.org/obo/DOID_8923>
      a       skos:Concept ;
      skos:altLabel "malignant scalp melanoma"@en , "malignant lip melanoma"@en , "malignant melanoma of skin of upper limb"@en , "cutaneous melanoma"@en , "malignant melanoma of ear and/or external auricular canal"@en , "malignant trunk melanoma"@en , "malignant melanoma of skin of trunk except scrotum"@en , "malignant lower limb melanoma"@en , "malignant melanoma of skin of lower limb"@en , "malignant upper limb melanoma"@en , "malignant ear melanoma"@en , "malignant neck melanoma"@en ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_4159> ;
      skos:definition "A skin cancer that has_material_basis_in melanocytes." ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> .

<http://purl.obolibrary.org/obo/DOID_3451>
      a       skos:Concept ;
      skos:altLabel "carcinoma of skin"@en ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_4159> ;
      skos:definition "A skin cancer that is located_in tissues of the skin and develops from epithelial cells." ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> ;
      skos:prefLabel "skin carcinoma"@en .
<http://purl.obolibrary.org/obo/DOID_6944>
      a       skos:Concept ;
      skos:altLabel "Seborrheic Keratosis of Vulva"@en ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_6498> , <http://purl.obolibrary.org/obo/DOID_4159> ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> ;
      skos:prefLabel "vulvar seborrheic keratosis"@en .
<http://purl.obolibrary.org/obo/DOID_4159>
      a       skos:Concept ;
      skos:altLabel "malignant neoplasm of skin"@en , "CA - skin cancer"@en , "melanoma and Non-melanoma skin cancer"@en ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_37> ;
      skos:definition "An integumentary system cancer located_in the skin that is the uncontrolled growth of abnormal skin cells." ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> ;
      skos:prefLabel "skin cancer"@en .
<http://purl.obolibrary.org/obo/DOID_11684>
      a       skos:Concept ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_6498> ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> ;
      skos:prefLabel "melanoacanthoma"@en .
</code>```

SPARQL

```<code>prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
prefix skos: <http://www.w3.org/2004/02/skos/core#>

SELECT *

WHERE {?s skos:broader*  <http://purl.obolibrary.org/obo/DOID_4159>;

          skos:prefLabel ?prefLabel
         }

</code>```
```<code>s                                           prefLabel
<http://purl.obolibrary.org/obo/DOID_4159>  skin cancer
<http://purl.obolibrary.org/obo/DOID_3451>  skin carcinoma
<http://purl.obolibrary.org/obo/DOID_6944>  vulvar seborrheic keratosis

</code>```

Body:
I have following concepts in turtle file. I would like to extract preferred label and ids for parent node (DOID_4159) and all its child from below concepts. I have written following SPARQL query to fetch the information, but it will not give all the child nodes.

qres = g.query(
    """
    SELECT *
    WHERE {
    {?s skos:prefLabel ?prefLabel .
    ?s skos:broader  <http://purl.obolibrary.org/obo/DOID_4159>  .
    }
    UNION
    {?s skos:prefLabel "skin cancer"@en .
    ?s skos:prefLabel ?prefLabel .
    }
    }
    """)

<http://purl.obolibrary.org/obo/DOID_8923>
      a       skos:Concept ;
      skos:altLabel "malignant scalp melanoma"@en , "malignant lip melanoma"@en , "malignant melanoma of skin of upper limb"@en , "cutaneous melanoma"@en , "malignant melanoma of ear and/or external auricular canal"@en , "malignant trunk melanoma"@en , "malignant melanoma of skin of trunk except scrotum"@en , "malignant lower limb melanoma"@en , "malignant melanoma of skin of lower limb"@en , "malignant upper limb melanoma"@en , "malignant ear melanoma"@en , "malignant neck melanoma"@en ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_4159> ;
      skos:definition "A skin cancer that has_material_basis_in melanocytes." ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> ;

<http://purl.obolibrary.org/obo/DOID_3451>
      a       skos:Concept ;
      skos:altLabel "carcinoma of skin"@en ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_4159> ;
      skos:definition "A skin cancer that is located_in tissues of the skin and develops from epithelial cells." ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> ;
      skos:prefLabel "skin carcinoma"@en .
<http://purl.obolibrary.org/obo/DOID_6944>
      a       skos:Concept ;
      skos:altLabel "Seborrheic Keratosis of Vulva"@en ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_6498> , <http://purl.obolibrary.org/obo/DOID_4159> ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> ;
      skos:prefLabel "vulvar seborrheic keratosis"@en .
<http://purl.obolibrary.org/obo/DOID_4159>
      a       skos:Concept ;
      skos:altLabel "malignant neoplasm of skin"@en , "CA - skin cancer"@en , "melanoma and Non-melanoma skin cancer"@en ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_37> ;
      skos:definition "An integumentary system cancer located_in the skin that is the uncontrolled growth of abnormal skin cells." ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> ;
      skos:prefLabel "skin cancer"@en .
<http://purl.obolibrary.org/obo/DOID_11684>
      a       skos:Concept ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_6498> ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> ;
      skos:prefLabel "melanoacanthoma"@en .

Following is the desired output:
id        label
DOID_8923 skin melanoma
DOID_3451 skin carcinoma
DOID_6944 vulvar seborrheic keratosis
DOID_4159 skin cancer
DOID_6498 seborrheic keratosis
DOID_11684 melanoacanthoma

If I would like to fetch this information for parent (DOID_4159) and all its associated nodes, how can I achieve this? I am new to SPARQL, any help is highly appreciated.

Body:
here we have some issues

The .ttl file you posted is not correct. There is an error on the definition of the 1st entity which is missing of the . at the end. So you have to update the definition from:

<http://purl.obolibrary.org/obo/DOID_8923>
      a       skos:Concept ;
      skos:altLabel "malignant scalp melanoma"@en , "malignant lip melanoma"@en , "malignant melanoma of skin of upper limb"@en , "cutaneous melanoma"@en , "malignant melanoma of ear and/or external auricular canal"@en , "malignant trunk melanoma"@en , "malignant melanoma of skin of trunk except scrotum"@en , "malignant lower limb melanoma"@en , "malignant melanoma of skin of lower limb"@en , "malignant upper limb melanoma"@en , "malignant ear melanoma"@en , "malignant neck melanoma"@en ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_4159> ;
      skos:definition "A skin cancer that has_material_basis_in melanocytes." ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> ;

To:

<http://purl.obolibrary.org/obo/DOID_8923>
      a       skos:Concept ;
      skos:altLabel "malignant scalp melanoma"@en , "malignant lip melanoma"@en , "malignant melanoma of skin of upper limb"@en , "cutaneous melanoma"@en , "malignant melanoma of ear and/or external auricular canal"@en , "malignant trunk melanoma"@en , "malignant melanoma of skin of trunk except scrotum"@en , "malignant lower limb melanoma"@en , "malignant melanoma of skin of lower limb"@en , "malignant upper limb melanoma"@en , "malignant ear melanoma"@en , "malignant neck melanoma"@en ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_4159> ;
      skos:definition "A skin cancer that has_material_basis_in melanocytes." ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> .

The . at the end, it means that the definition of your entity is complete. While the ; is used when you need to add other relationships.

The record DOID_8923 has no skos:prefLabel so, you are not able to retrieve the prefLabel from DOID_8923. You need to add the skos:prefLabel also to this entity

As already pointed out by UninformedUser
you have to specify the relation between DOID_11684 and DOID_4159 also in your schema

Here you can find your .ttl file updated and the transitive SPARQL query

@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix skos: <http://www.w3.org/2004/02/skos/core#> .

<http://purl.obolibrary.org/obo/DOID_8923>
      a       skos:Concept ;
      skos:altLabel "malignant scalp melanoma"@en , "malignant lip melanoma"@en , "malignant melanoma of skin of upper limb"@en , "cutaneous melanoma"@en , "malignant melanoma of ear and/or external auricular canal"@en , "malignant trunk melanoma"@en , "malignant melanoma of skin of trunk except scrotum"@en , "malignant lower limb melanoma"@en , "malignant melanoma of skin of lower limb"@en , "malignant upper limb melanoma"@en , "malignant ear melanoma"@en , "malignant neck melanoma"@en ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_4159> ;
      skos:definition "A skin cancer that has_material_basis_in melanocytes." ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> .

<http://purl.obolibrary.org/obo/DOID_3451>
      a       skos:Concept ;
      skos:altLabel "carcinoma of skin"@en ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_4159> ;
      skos:definition "A skin cancer that is located_in tissues of the skin and develops from epithelial cells." ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> ;
      skos:prefLabel "skin carcinoma"@en .
<http://purl.obolibrary.org/obo/DOID_6944>
      a       skos:Concept ;
      skos:altLabel "Seborrheic Keratosis of Vulva"@en ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_6498> , <http://purl.obolibrary.org/obo/DOID_4159> ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> ;
      skos:prefLabel "vulvar seborrheic keratosis"@en .
<http://purl.obolibrary.org/obo/DOID_4159>
      a       skos:Concept ;
      skos:altLabel "malignant neoplasm of skin"@en , "CA - skin cancer"@en , "melanoma and Non-melanoma skin cancer"@en ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_37> ;
      skos:definition "An integumentary system cancer located_in the skin that is the uncontrolled growth of abnormal skin cells." ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> ;
      skos:prefLabel "skin cancer"@en .
<http://purl.obolibrary.org/obo/DOID_11684>
      a       skos:Concept ;
      skos:broader <http://purl.obolibrary.org/obo/DOID_6498> ;
      skos:inScheme <https://localhost:8443/ontology/Applicanttest/APPLICANTTEST> ;
      skos:prefLabel "melanoacanthoma"@en .

SPARQL

prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
prefix skos: <http://www.w3.org/2004/02/skos/core#>

SELECT *

WHERE {?s skos:broader*  <http://purl.obolibrary.org/obo/DOID_4159>;

          skos:prefLabel ?prefLabel
         }

s                                           prefLabel
<http://purl.obolibrary.org/obo/DOID_4159>  skin cancer
<http://purl.obolibrary.org/obo/DOID_3451>  skin carcinoma
<http://purl.obolibrary.org/obo/DOID_6944>  vulvar seborrheic keratosis


来源: stackexchange

问:
Creating a library that contains instance members
In regards to my a little to late discovery that static libraries (obviously) can't have instance members, How to reference property of static library, is there a way to create a shared library that contains both instance and static members?

On way that probably works is to create a class file, save it to some shared directory and reference it from multiple projects.  Is there a better way?

答:
I just read an excellent blog post this morning with a nice writeup about sharing code:

http://www.mobileorchard.com/code-sharing-via-static-libraries-and-cross-project-references

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Adam Alexander


问:
Controlling tabbing in form inputs
is it possible to skip the url field when tab button is pressed in a form?
like after it goes to the last input element i wanted it to go back to the first input element instead of going to the url field!

thanks a alot.

答: You can add an onkeyup on your last input and check if the tab-key was pressed and then run something like your_first_input.focus(), so that it jumps to the first input.

ContentLicense: CC BY-SA 3.0

Title: Controlling tabbing in form inputs


问:
Nginx redirect to 404 page if there is a trailing slash at the end of the URL
I got a ask of doing a redirect to 404 page if there is a trailing slash at the end of the URL.

Eg:

```<code>https://www.example.com/test/
</code>```

If the user enters a trailing slash at the end means we need to redirect it to 404 page. Previously I have redirected the same URL by removing the trailing slash, Now the requirement has changed to redirect to the 404 page.

Here is the nginx conf file for it. Please let me know what change I have to make here to achieve the scenario.

nginx.conf

```<code>server {

  listen 80;
  rewrite ^/(.*)/$ /$1 permanent;

  location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
    try_files $uri $uri.html $uri/index.html $uri/index =404;
    error_page 404 /404.html;
  }

  error_page   500 502 503 504  /50x.html;

  location = /50x.html {
    root   /usr/share/nginx/html;
  }
}

</code>```

Updated Conf:

Default Nginx 404 error page is displayed after this config. What's the update required here to display the custom 404 page?.

```<code>server {

  listen 80;

  location ~ ^/(.*)/$ {
    return 404;
  }

  location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
    try_files $uri $uri.html $uri/index.html $uri/index =404;
    error_page 404 404 /404.html;
  }

  error_page   500 502 503 504  /50x.html;

  location = /50x.html {
    root   /usr/share/nginx/html;
  }
}

</code>```

答:
Remove the rewrite ^/(.*)/$ /$1 permanent; statement and replace it with:

```<code>location ~ ^/(.*)/$ { return 404; }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I got a ask of doing a redirect to 404 page if there is a trailing slash at the end of the URL.

Eg:

https://www.example.com/test/

If the user enters a trailing slash at the end means we need to redirect it to 404 page. Previously I have redirected the same URL by removing the trailing slash, Now the requirement has changed to redirect to the 404 page.

Here is the nginx conf file for it. Please let me know what change I have to make here to achieve the scenario.

nginx.conf

server {

  listen 80;
  rewrite ^/(.*)/$ /$1 permanent;

  location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
    try_files $uri $uri.html $uri/index.html $uri/index =404;
    error_page 404 /404.html;
  }

  error_page   500 502 503 504  /50x.html;

  location = /50x.html {
    root   /usr/share/nginx/html;
  }
}

Updated Conf:

Default Nginx 404 error page is displayed after this config. What's the update required here to display the custom 404 page?.

server {

  listen 80;

  location ~ ^/(.*)/$ {
    return 404;
  }

  location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
    try_files $uri $uri.html $uri/index.html $uri/index =404;
    error_page 404 404 /404.html;
  }

  error_page   500 502 503 504  /50x.html;

  location = /50x.html {
    root   /usr/share/nginx/html;
  }
}

Body:
Remove the rewrite ^/(.*)/$ /$1 permanent; statement and replace it with:

location ~ ^/(.*)/$ { return 404; }


问:
How can ı remove ant design's space between dropdown and menu?
enter image description here

Hello, I want to delete the space between the menu and the button, so the button and the drop-down menu will be combined. I don't know how to do this can you help me?
I can not find how can ı remove it .

答:
You can do it by wrapping the Button inside a span element. like this:

```<code> <Dropdown placement="bottomLeft" ...>
  <span>
    <Button>bottomLeft</Button>
  </span>
</Dropdown>
</code>```

it works because Dropdown will calculate it's popup position based on the top of the element which placed directly inside the <Dropdown>, and since in the above solution, span has y-overflow, so the the popup will be shown without any space between Button and popup. You can controll the space between popup and Button by styling the span element like this:

```<code> <Dropdown placement="bottomCenter" ...>
   <span style={{ display: 'inline-block', height: 27 }}>
     <Button>bottomCenter</Button>
  </span>
 </Dropdown>
</code>```

I've implemented an example Here on stackblitz you can check it out.

Body:
You can do it by wrapping the Button inside a span element. like this:

 <Dropdown placement="bottomLeft" ...>
  <span>
    <Button>bottomLeft</Button>
  </span>
</Dropdown>

it works because Dropdown will calculate it's popup position based on the top of the element which placed directly inside the <Dropdown>, and since in the above solution, span has y-overflow, so the the popup will be shown without any space between Button and popup. You can controll the space between popup and Button by styling the span element like this:

 <Dropdown placement="bottomCenter" ...>
   <span style={{ display: 'inline-block', height: 27 }}>
     <Button>bottomCenter</Button>
  </span>
 </Dropdown>

I've implemented an example Here on stackblitz you can check it out.


问:
Python to Powerpoint: Export svg to a pptx file
I was experimenting with the python-pptx library to automate the process of adding images to my presentations. I used code such as:

```<code>from pptx import Presentation
import os

prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[8])
placeholder = slide.placeholders[1]
picture = placeholder.insert_picture('pie.png')
prs.save("ESEMPIO.pptx")
</code>```

This works just fine, but it was noted that when zooming in the pie chart contained in pie.png becomes quite pixelated. Someone suggested to use SVG format, so I saved the image as an SVG (unfortunately, I can't seem to add the SVG file here). Now, if I try to do:

```<code>from pptx import Presentation
import os

prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[8])
placeholder = slide.placeholders[1]
picture = placeholder.insert_picture('pie.svg')
prs.save("ESEMPIO.pptx")
</code>```

I get the following error: UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f38da87c350>, which I guess is because it does not like the SVG format. Is there any workaround to get an SVG into a PowerPoint presentation?

PNG pie chart

答: According to this issue on the repository, svg support doesn't seem to be a priority for the devs, and they suggest manually converting to png and inserting that into your presentation. My best suggestion is converting to a relatively high resolution png so the pixelation is less noticeable.</p>

Body:
I was experimenting with the python-pptx library to automate the process of adding images to my presentations. I used code such as:

from pptx import Presentation
import os

prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[8])
placeholder = slide.placeholders[1]
picture = placeholder.insert_picture('pie.png')
prs.save("ESEMPIO.pptx")

This works just fine, but it was noted that when zooming in the pie chart contained in pie.png becomes quite pixelated. Someone suggested to use SVG format, so I saved the image as an SVG (unfortunately, I can't seem to add the SVG file here). Now, if I try to do:

from pptx import Presentation
import os

prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[8])
placeholder = slide.placeholders[1]
picture = placeholder.insert_picture('pie.svg')
prs.save("ESEMPIO.pptx")

I get the following error: UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f38da87c350>, which I guess is because it does not like the SVG format. Is there any workaround to get an SVG into a PowerPoint presentation?

PNG pie chart


问:
wpf how to get program focus form windows
i made program it work in background, i want this program only work on program i select it
example : i created Auto clicker and i want to use this program just in games if the user go to any other program it doesn't work

this way i hope it is there

```<code>if(Windows.Focus.NameProgram.ToString() == "Call of Duty Cold War")
{
   // here all commands i will put it later.
}
</code>```

here i mean what windows focus it now if it is Call of Duty Cold War then work, if not dont work (of course still running in the background)

答:
Use a function called GetForegroundWindow from Windows API.

The implementation further down gets the current focused window.

Documentation: GetForegroundWindow | MS Docs

```<code>   public class GetFocusedWindow
    {

        [DllImport("user32.dll")]
        static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

        private static string GetActiveWindowTitle()
        {
            const int nChars = 256;
            StringBuilder Buff = new StringBuilder(nChars);
            IntPtr handle = GetForegroundWindow();

            if (GetWindowText(handle, Buff, nChars) > 0)
            {
                return Buff.ToString();
            }
            return null;
        }

        static void Main(string[] args)
        {
            while (true)
            {
                Thread.Sleep(2000);
                Console.WriteLine(GetActiveWindowTitle());
            }
        }
    }
</code>```

Body:
i made program it work in background, i want this program only work on program i select it
example : i created Auto clicker and i want to use this program just in games if the user go to any other program it doesn't work

this way i hope it is there

if(Windows.Focus.NameProgram.ToString() == "Call of Duty Cold War")
{
   // here all commands i will put it later.
}

here i mean what windows focus it now if it is Call of Duty Cold War then work, if not dont work (of course still running in the background)

Body:
Use a function called GetForegroundWindow from Windows API.

The implementation further down gets the current focused window.

Documentation: GetForegroundWindow | MS Docs

   public class GetFocusedWindow
    {

        [DllImport("user32.dll")]
        static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

        private static string GetActiveWindowTitle()
        {
            const int nChars = 256;
            StringBuilder Buff = new StringBuilder(nChars);
            IntPtr handle = GetForegroundWindow();

            if (GetWindowText(handle, Buff, nChars) > 0)
            {
                return Buff.ToString();
            }
            return null;
        }

        static void Main(string[] args)
        {
            while (true)
            {
                Thread.Sleep(2000);
                Console.WriteLine(GetActiveWindowTitle());
            }
        }
    }


问:
iOS Apple Push Notifications not arriving on real device
I've been trying to setup Apple Push Notifications (Alerts) on my Swift (iOS >= 15.0) application. For authentication I'm using the new(ish) token based authentication and have added the push notification entitlement. Unfortunately when trying to send a push notification to my real test iPhone device, the notification never arrives.

I'm using the following URL and Payload:

https://api.sandbox.push.apple.com:443/3/device/<device_id>

```<code>POST /3/device/c<REDACTED DEVICE ID>6 HTTP/2
Host: api.sandbox.push.apple.com
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
User-Agent: python-httpx/0.21.1
Apns-Expiration: 0
Apns-Priority: 10
Apns-Topic: <REDACTED BUNDLE_ID e.g. com.my.app>
Apns-Push-Type: alert
Authorization: bearer ey<REDACTED>w
Content-Type: application/json
Content-Length: 78

{"some": "thing", "aps": {"alert": {"title": "test", "subtitle": "subtitle"}}}
</code>```

Sending this to Apple's sandbox environment returns a HTTP Status Code 200 without any content. This means that at least the device ID and bundle ID are correct. unfortunately the notifications never arrive on my device (even not the following day or after repeated attempts).

I've successfully registered my application with the appropriate permissions as can be seen here:

When using the simctl command line tool, I'm able to send and see the notification to my xcode simulator and can see the didReceiveRemoteNotification function is being called.

```<code># cat test.apn
{
  "some": "thing",
  "aps": {
    "alert": {
      "title": "test",
      "subtitle": "subtitle"
    }
  }
}
# xcrun simctl push booted com.my.app test.apn
Notification sent to 'com.my.app'
</code>```

The following code is what I have in place currently for handling registration for push notifications and catching incoming notifications:

@main
struct MyApp: App {

    @UIApplicationDelegateAdaptor private var appDelegate: AppDelegate

    var body: some Scene {
        WindowGroup {
            Text("Hello")
    }
}

class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    func forwardTokenToServer(token: Data) async throws {

        let tokenComponents = token.map { data in String(format: "%02.2hhx", data) }
        let deviceTokenString = tokenComponents.joined()

        let device = NotificationDevice(deviceToken: deviceTokenString)
        print("Sending device \(device.name) \(device.type) \(device.id) to backend service...")

        guard let url = URL(string: "https://my.app/api/iosdevices") else {
            throw URLError(.badServerResponse)  // Todo proper errors
         }

        var request = URLRequest(url: url)
        request.httpMethod = "POST"

        let encoder = JSONEncoder()
        guard let deviceData = try? encoder.encode(device) else {
            throw URLError(.badServerResponse) // TODO proper errors
        }

        let (_, response) = try await URLSession.shared.upload(
            for: request,
            from: deviceData
        )
        print("Response from backend: \(response)")
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {

        // Request Alert push notification authorization
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (allowed, error) in
            //This callback does not trigger on main loop be careful
            if allowed {
                print("PushNotification Allowed")
            } else {
                print("Error no auth for push notifications")
            }
        }

        UIApplication.shared.registerForRemoteNotifications()
        UNUserNotificationCenter.current().delegate = self
        return true
    }

    // Note there is no callback in simulator, must use device to get valid push token
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Task {
             do {
                 try await self.forwardTokenToServer(token: deviceToken)
             } catch {
               print("Failed to forward token to backend.")
             }
        }
    }

    // Called when we could not register for push notifications
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register for remote notifications \(error.localizedDescription)")
    }

    // Called when we receive a new notificationn
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
            print("Got a notification")
    }
}
```

Any tips or ideas are much appreciated!

答:
Finally figured out that the DeviceID in development got changed. When sending a notification with the old DeviceID to apple's APNS server api.sandbox.push.apple.com, it still regarded the old DeviceID as valid so I didn't pick up on it.

Apparently it will take a while before old DeviceIDs become invalid on the apple backend.

Body:
I've been trying to setup Apple Push Notifications (Alerts) on my Swift (iOS >= 15.0) application. For authentication I'm using the new(ish) token based authentication and have added the push notification entitlement. Unfortunately when trying to send a push notification to my real test iPhone device, the notification never arrives.

I'm using the following URL and Payload:

https://api.sandbox.push.apple.com:443/3/device/<device_id>

POST /3/device/c<REDACTED DEVICE ID>6 HTTP/2
Host: api.sandbox.push.apple.com
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
User-Agent: python-httpx/0.21.1
Apns-Expiration: 0
Apns-Priority: 10
Apns-Topic: <REDACTED BUNDLE_ID e.g. com.my.app>
Apns-Push-Type: alert
Authorization: bearer ey<REDACTED>w
Content-Type: application/json
Content-Length: 78

{"some": "thing", "aps": {"alert": {"title": "test", "subtitle": "subtitle"}}}

Sending this to Apple's sandbox environment returns a HTTP Status Code 200 without any content. This means that at least the device ID and bundle ID are correct. unfortunately the notifications never arrive on my device (even not the following day or after repeated attempts).

I've successfully registered my application with the appropriate permissions as can be seen here:

When using the simctl command line tool, I'm able to send and see the notification to my xcode simulator and can see the didReceiveRemoteNotification function is being called.

# cat test.apn
{
  "some": "thing",
  "aps": {
    "alert": {
      "title": "test",
      "subtitle": "subtitle"
    }
  }
}
# xcrun simctl push booted com.my.app test.apn
Notification sent to 'com.my.app'

The following code is what I have in place currently for handling registration for push notifications and catching incoming notifications:

@main
struct MyApp: App {

    @UIApplicationDelegateAdaptor private var appDelegate: AppDelegate

    var body: some Scene {
        WindowGroup {
            Text("Hello")
    }
}

class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    func forwardTokenToServer(token: Data) async throws {

        let tokenComponents = token.map { data in String(format: "%02.2hhx", data) }
        let deviceTokenString = tokenComponents.joined()

        let device = NotificationDevice(deviceToken: deviceTokenString)
        print("Sending device \(device.name) \(device.type) \(device.id) to backend service...")

        guard let url = URL(string: "https://my.app/api/iosdevices") else {
            throw URLError(.badServerResponse)  // Todo proper errors
         }

        var request = URLRequest(url: url)
        request.httpMethod = "POST"

        let encoder = JSONEncoder()
        guard let deviceData = try? encoder.encode(device) else {
            throw URLError(.badServerResponse) // TODO proper errors
        }

        let (_, response) = try await URLSession.shared.upload(
            for: request,
            from: deviceData
        )
        print("Response from backend: \(response)")
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {

        // Request Alert push notification authorization
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (allowed, error) in
            //This callback does not trigger on main loop be careful
            if allowed {
                print("PushNotification Allowed")
            } else {
                print("Error no auth for push notifications")
            }
        }

        UIApplication.shared.registerForRemoteNotifications()
        UNUserNotificationCenter.current().delegate = self
        return true
    }

    // Note there is no callback in simulator, must use device to get valid push token
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Task {
             do {
                 try await self.forwardTokenToServer(token: deviceToken)
             } catch {
               print("Failed to forward token to backend.")
             }
        }
    }

    // Called when we could not register for push notifications
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register for remote notifications \(error.localizedDescription)")
    }

    // Called when we receive a new notificationn
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
            print("Got a notification")
    }
}

Any tips or ideas are much appreciated!


问:
JavaScript object related question that what will be the output of below code?

var x = 3;
var one = {
  x:2,
  two: {
    x:1,
    three:function(){
        return this.x;

    }
  }
}

var go = one.two.three;

 console.log(one.two.three() + "" + go());
 ```

Anyone can explain to me why output coming 13 why not 1-undefined?

答:
To assign an object method to a variable, it needs to be bandaged using the bind() function, and if the global variable window is passed to the context, the answer will be 13

```<code>*var go = one.two.three.bind(window);*
</code>```

if the object is one the answer will be 12

```<code>*var go = one.two.three.bind(one);*
</code>```

if the object is two the answer will be 11

```<code>*var go = one.two.three.bind(two);*
</code>```

Body:
var x = 3;
var one = {
  x:2,
  two: {
    x:1,
    three:function(){
        return this.x;

    }
  }
}

var go = one.two.three;

 console.log(one.two.three() + "" + go());

Anyone can explain to me why output coming 13 why not 1-undefined?

Body:
To assign an object method to a variable, it needs to be bandaged using the bind() function, and if the global variable window is passed to the context, the answer will be 13

*var go = one.two.three.bind(window);*

if the object is one the answer will be 12

*var go = one.two.three.bind(one);*

if the object is two the answer will be 11

*var go = one.two.three.bind(two);*


问:
localhost refused to connect for Forge Autodesk Online Viewer
i am following the tutorial from this link: https://forge.autodesk.com/developer/learn/viewer-app/overview

after i click the Authorize me! button, chrome shows localhost refused to connect.

there is also this message error in my cmd after runnning npm start:

```<code>node:internal/errors:464
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (C:\Users\Jessilyn\walkthrough\node_modules\express\lib\response.js:776:10)
    at ServerResponse.send (C:\Users\Jessilyn\walkthrough\node_modules\express\lib\response.js:170:12)
    at C:\Users\Jessilyn\walkthrough\start.js:137:17
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
</code>```

it loaded for the first attempt. when i tried again, this error happened. i deleted the git clone and restart the process and have been receiving the same results over and over again.

i don't understand what's going on, would appreciate if you could provide guidance.

答:
At which step in code you're getting the error?
Looks like the server start is not correct, do you have the proper nodejs version and all the packages installed?

Alternately you can try this similar tutorial: https://learnforge.autodesk.io/#/tutorials/viewmodels

Body:
i am following the tutorial from this link: https://forge.autodesk.com/developer/learn/viewer-app/overview

after i click the Authorize me! button, chrome shows localhost refused to connect.

there is also this message error in my cmd after runnning npm start:

node:internal/errors:464
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (C:\Users\Jessilyn\walkthrough\node_modules\express\lib\response.js:776:10)
    at ServerResponse.send (C:\Users\Jessilyn\walkthrough\node_modules\express\lib\response.js:170:12)
    at C:\Users\Jessilyn\walkthrough\start.js:137:17
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ERR_HTTP_HEADERS_SENT'

it loaded for the first attempt. when i tried again, this error happened. i deleted the git clone and restart the process and have been receiving the same results over and over again.

i don't understand what's going on, would appreciate if you could provide guidance.


问:
Kohana AND PhpUnit in Netbeans
I do some PHP with Kohana 3 (IDE:Netbeans), and got excited about idea of writing tests for code. It sounds pretty cool thing to do, but i have few complications and worries.

Why using Kohana unittest module in browser is like 5 times faster then running tests in Netbeans or command Line ?

How could i exclude all kohana internal tests? In the PHPUnit .xml configuration file ?

Why when run any test  i've got in Netbeans panel two entries for it - one with yellow triangle (it says 'file x skipped'), and entry with normal test result. I do get that double entries for every test, also those native from Kohana. I don't mind but it's strange.

All over the Web i see examples, tutorials and screencasts of PHPUnit with sample classes and methods that add two numbers or displays name or do some other trivial things. I've learnt to do those kind of assertions, but how could i test my code in Kohana? My Models are 90% ORM stuff. Controllers? How? Any 'How-tos' and examples are welcome.

I've seen in Ruby tutorial about Rspec a way to test DB by using testing enviroment Databse and rollbacks after finisning tests. Also user actions like clicking links were simulated. Is it possible with PHPUnit ?

答:
It's probably better to split such a rambling question into multiple SO questions.

No idea. Perhaps there's an invocation overhead for NetBeans to invoke phpunit, compared to apache passing the request to PHP.

That might be possible, or you could find a way to set the following option: --exclude-group kohana

No idea sorry.

AFAIK PHPUnit can't do client-interaction tests. How to do system behaviour testing could be a question on its own.

Title: Kohana AND PhpUnit in Netbeans


问:
Creating Signature for Text
I'm creating a program where I need to read all the lines and words in a txt file, count the number of times the words show up and do this for multiple txt files. Then I need to create a "signature" which is the 25 most common words and compare each txt file's signature to the other files. I worked all day today to get the program that counts the words in each text but I was stuck on the part on how to get the signature. Essentially when the program runs, this is what is shown:

The program creates a column called word, which shows all the words that are in the text and the number of times they show up for each text file. I have 2 for now, but I'll have more later on. I need to sort this list of words out, so the top 25 words that show up the most will be part of the "signature" and stored in a list, one list for each text. I am not sure how to sort out this many words. I have been thinking about how I could do this, and I thought of creating a list of lists, but I don't think that will work. Could anyone suggest something and show some code with it? I could also show you the program in private and show the change in code that way. Any help would really be great considering how long this has taken me today. Thanks in advance!

答:
You could try this</p>
```<code>import pandas as pd

df = pd.DataFrame([['word1',1,222], ['word2',10,20],['word3',111,1],['word4',11,62]], columns =['word', 'file1','file2'])

#Convert the columns containing word count to numeric
df['file1'] = pd.to_numeric(df['file1'])
df['file2'] = pd.to_numeric(df['file2'])

wordlist =[]
for column in df.columns:
    if column != 'word':
        #sort datatable columnwise and pick the top words from word column. Replace the value 3 by the required number.
        #append it to a list of lists
        wordlist.append([df.sort_values(column, ascending=False)['word'].head(3)])

print(wordlist)
</code>```

Title: Creating Signature for Text

Body:
You could try this

import pandas as pd

df = pd.DataFrame([['word1',1,222], ['word2',10,20],['word3',111,1],['word4',11,62]], columns =['word', 'file1','file2'])

#Convert the columns containing word count to numeric
df['file1'] = pd.to_numeric(df['file1'])
df['file2'] = pd.to_numeric(df['file2'])

wordlist =[]
for column in df.columns:
    if column != 'word':
        #sort datatable columnwise and pick the top words from word column. Replace the value 3 by the required number.
        #append it to a list of lists
        wordlist.append([df.sort_values(column, ascending=False)['word'].head(3)])

print(wordlist)


问:
Assigning values from data frame to vector in R
I have a data frame as below:

```<code>data <- data.frame(name = c("a", "b"),
                   value = c("apple", "ball"))
</code>```

Now from this data I want to create a vector as follows:

```<code>transformed_data <- c( a = "apple", b = "ball")
</code>```

How this is possible to do in R?

答:
Since you're tagging tidyverse in the question, you can use deframe from the tibble package:

tibble::deframe(data)

      a       b
"apple"  "ball"
```

Body:
I have a data frame as below:

data <- data.frame(name = c("a", "b"),
                   value = c("apple", "ball"))

Now from this data I want to create a vector as follows:

transformed_data <- c( a = "apple", b = "ball")

How this is possible to do in R?


问:
How to fill nan values with rolling mean in pandas
I have a dataframe which contains nan values at few places. I am trying to perform data cleaning in which I fill the nan values with mean of it's previous five instances. To do so, I have come up with the following.

```<code>input_data_frame[var_list].fillna(input_data_frame[var_list].rolling(5).mean(), inplace=True)
</code>```

But, this is not working. It isn't filling the nan values. There is no change in the dataframe's null count before and after the above operation. Assuming I have a dataframe with just integer column, How can I fill NaN values with mean of the previous five instances? Thanks in advance.

答:
you can simply use interpolate()</p>
```<code>df = {'a': [1,5, np.nan, np.nan, np.nan, 2, 5, np.nan] }
df = pd.DataFrame(data=df)
print(df)

df['a'].interpolate()
</code>```

Body:
I have a dataframe which contains nan values at few places. I am trying to perform data cleaning in which I fill the nan values with mean of it's previous five instances. To do so, I have come up with the following.

input_data_frame[var_list].fillna(input_data_frame[var_list].rolling(5).mean(), inplace=True)

But, this is not working. It isn't filling the nan values. There is no change in the dataframe's null count before and after the above operation. Assuming I have a dataframe with just integer column, How can I fill NaN values with mean of the previous five instances? Thanks in advance.

Body:
you can simply use interpolate()

df = {'a': [1,5, np.nan, np.nan, np.nan, 2, 5, np.nan] }
df = pd.DataFrame(data=df)
print(df)

df['a'].interpolate()


问:
Symfony2 Doctrine2 mapping from existing database (exception)
I've already got a MySQL database therefore I wish to create mapping meta data from the existing database.

```<code>php app/console doctrine:mapping:convert xml ./src/MainBundle/Resources/config/doctrine/metadata/orm --from-database --force
</code>```

However I got the following exception

```<code>[Doctrine\ORM\Mapping\MappingException]
Property "customerid" in "Accountcustomer" was already declared, but it must be declared only once
</code>```

I haven't used customerId in any primary / composite key anywhere else in the database however I've used it as a foreign key several times.

However I do not know how having customerId in a composite key or another primary key could affect this.

答:
Unfortunately Doctrine 2.0 does not support primary keys as foreign keys...
Check the link: http://www.doctrine-project.org/docs/orm/2.0/en/reference/limitations-and-known-issues.html</p>

Body:
I've already got a MySQL database therefore I wish to create mapping meta data from the existing database.

php app/console doctrine:mapping:convert xml ./src/MainBundle/Resources/config/doctrine/metadata/orm --from-database --force

However I got the following exception

[Doctrine\ORM\Mapping\MappingException]
Property "customerid" in "Accountcustomer" was already declared, but it must be declared only once

I haven't used customerId in any primary / composite key anywhere else in the database however I've used it as a foreign key several times.

However I do not know how having customerId in a composite key or another primary key could affect this.


问:
How to print a X with two letters inside a square
I am trying to make the this shape but stuck at here. I tried with counters more than one but failed again.

P p p p p p Q
p P p p p Q q
p p P p Q q q
p p p Q q q q
p p Q q Q q q
p Q q q q Q q
Q q q q q q Q
```
```int main()
{
    int loopLimit = 7;
    int upperCharacter = 0;

    do {
        int loopCounter = 0;

        do {
            if (loopCounter == upperCharacter) std::cout << "P ";
            else std::cout << "p ";
            loopCounter = loopCounter + 1;
        } while (loopCounter < loopLimit);

        upperCharacter = upperCharacter + 1;
        loopLimit = loopLimit - 1;
        std::cout << "\n";
    } while (loopLimit > 0);
}
```
<p>My code currently outputs:</p>
<pre class="lang-none prettyprint-override"><code>P p p p p p p
p P p p p p
p p P p p
p p p P
p p p
p p
p
</code>```

答:
With How do I ask and answer homework questions? in mind,

I propose to try the following, in order to avoid that you program yourself into a corner.

Use two nested loops (I'd prefer for but if you are more confident with do while stay with that) to output a square of all the same letters. Do not change those loops afterwards.

Then use an if-else to select between two letters.

Then use an if-elseif-else to select between three.

Then four.

I believe the trick you are supposed to learn here is making conditions. Complex structures of interdependent loops is an alternative, but my guess is that it would make things harder for you.

I think a suitable sequence of letters to get right here would be:

p

Q on full first diagonal

q

P on full other diagonal, but check first diagonal afterwards

Q on the other half of the second diagonal

Note that getting the order of the conditions right is important, e.g. for the point of diagonal crossing.

Body:
I am trying to make the this shape but stuck at here. I tried with counters more than one but failed again.

P p p p p p Q
p P p p p Q q
p p P p Q q q
p p p Q q q q
p p Q q Q q q
p Q q q q Q q
Q q q q q q Q

int main()
{
    int loopLimit = 7;
    int upperCharacter = 0;

    do {
        int loopCounter = 0;

        do {
            if (loopCounter == upperCharacter) std::cout << "P ";
            else std::cout << "p ";
            loopCounter = loopCounter + 1;
        } while (loopCounter < loopLimit);

        upperCharacter = upperCharacter + 1;
        loopLimit = loopLimit - 1;
        std::cout << "\n";
    } while (loopLimit > 0);
}

My code currently outputs:

P p p p p p p
p P p p p p
p p P p p
p p p P
p p p
p p
p


问:
Highcharts area-spline fill gradient possibly undefined error
So I'm working with highcharts on angular 12 and trying to fill the area spline color with a gradient and I'm getting this error any idea how to solve this or what I could possibly be doing wrong ?

Any help would be appreciated ,Thanks in advance

答: I tried to reproduce your issue and it seems fine: https://stackblitz.com/edit/highcharts-angular-basic-line-vauauu</p>


问:
FAIL - Deployed application at context path / but context failed to start
Im working in 2 separate webapplications a back and front app.
The funny thing is when I run the back-end I don't have any issues. But in the front-end  I get the following error:

```<code>I have the following error in Netbeans

NetBeans: Deploying on Apache Tomcat or TomEE
    profile mode: false
    debug mode: false
    force redeploy: true
Undeploying ...
undeploy?path=/
OK - Undeployed application at context path /
In-place deployment at D:\WebDevel\WebStore\WebFrontE\target\Web-1.0-SNAPSHOT
Deployment is in progress...
deploy?config=file%3A%2FC%3A%2FUsers%7E1%2FAppData%2FLocal%2FTemp%2Fcontext7815575477480252472.xml&path=/
FAIL - Deployed application at context path / but context failed to start
</code>```

Both are running on the same Tomcat. my colleague has the same code and it works fine :-s

答: I had the same issue with even newly added projects tried a lot of stuff mentioned above. what works for me is to manually Stop tomcat service in the Installation directory  \Tomcat 9.0\bin Tomcat9w.exe. Then deployed the project it works this way in Netbeans IDE.</p>

Body:
Im working in 2 separate webapplications a back and front app.
The funny thing is when I run the back-end I don't have any issues. But in the front-end  I get the following error:

I have the following error in Netbeans

NetBeans: Deploying on Apache Tomcat or TomEE
    profile mode: false
    debug mode: false
    force redeploy: true
Undeploying ...
undeploy?path=/
OK - Undeployed application at context path /
In-place deployment at D:\WebDevel\WebStore\WebFrontE\target\Web-1.0-SNAPSHOT
Deployment is in progress...
deploy?config=file%3A%2FC%3A%2FUsers%7E1%2FAppData%2FLocal%2FTemp%2Fcontext7815575477480252472.xml&path=/
FAIL - Deployed application at context path / but context failed to start

Both are running on the same Tomcat. my colleague has the same code and it works fine :-s


问:
How to set a One To Many relationship in ONE model between different types
I have a table named categories and here is it's structure:

```<code>id              bigint(20)      AUTO_INCREMENT
name            varchar(255)
description     varchar(255)
short_name      varchar(255)
picture         varchar(255)
parent_category int(11)
category_type   tinyint(4)
</code>```

So each category has a category_type which can be one of these values:

1: Main Category

2: Superior Category

3: Secondary Category

4: Secondary Sub Category

Now I wanted to set a One To Many relationship between these categories.

For example: a main category has many superior categories and a superior category is related to one main category.

And this will apply to the rest of them as well.

But because I have only one Model which is Category, I don't know how to apply this relationship, so if you know, plz help me out...

Model Category.php:

```<code>class Category extends Model
{
    use HasFactory;
    protected $fillable = ['name','short_name','description','picture','category_type','parent_category'];

}
</code>```

答:
You can write the following relations in the Category model:

```<code>public function parentCategory()
{
    return $this->belongsTo(Category::class, 'parent_category', 'id');
}

public function childCategories()
{
    return $this->hasMany(Category::class, 'parent_category', 'id');
}
</code>```

You can later fetch the relations for example like this:

```<code>$cat = Category::where('category_type', 'main')->first();
$cat->childCategories; //all the categories where the main category has been set as parent category
</code>```

Or

```<code>  $cat2 = Category::where('category_type', 'secondary')->first();
  $cat2->parentCategory; //the category object which has been marked as parent for that specific secondary category
</code>```

If you want to filter per category type on the relations, you can do this as well:

```<code>public function superiorChildCategories()
{
    return $this->hasMany(Category::class,'parent_category','id')->where('category_type','superior');
}
</code>```

To use:

```<code>$cat3 = Category::where('category_type', 'main')->first();
$cat3->superiorChildCategories; //all the superior type categories where the main category has been set as parent category, will return null if there is no superior type child categories
</code>```

Don't forget to set the actual parent type relation on the database as well, so parent_category column should be the id of the parent category.

It is also tested, and works as expected.

Body:
I have a table named categories and here is it's structure:

id              bigint(20)      AUTO_INCREMENT
name            varchar(255)
description     varchar(255)
short_name      varchar(255)
picture         varchar(255)
parent_category int(11)
category_type   tinyint(4)

So each category has a category_type which can be one of these values:

1: Main Category

2: Superior Category

3: Secondary Category

4: Secondary Sub Category

Now I wanted to set a One To Many relationship between these categories.

For example: a main category has many superior categories and a superior category is related to one main category.

And this will apply to the rest of them as well.

But because I have only one Model which is Category, I don't know how to apply this relationship, so if you know, plz help me out...

Model Category.php:

class Category extends Model
{
    use HasFactory;
    protected $fillable = ['name','short_name','description','picture','category_type','parent_category'];

}

Body:
You can write the following relations in the Category model:

public function parentCategory()
{
    return $this->belongsTo(Category::class, 'parent_category', 'id');
}

public function childCategories()
{
    return $this->hasMany(Category::class, 'parent_category', 'id');
}

You can later fetch the relations for example like this:

$cat = Category::where('category_type', 'main')->first();
$cat->childCategories; //all the categories where the main category has been set as parent category

Or

  $cat2 = Category::where('category_type', 'secondary')->first();
  $cat2->parentCategory; //the category object which has been marked as parent for that specific secondary category

If you want to filter per category type on the relations, you can do this as well:

public function superiorChildCategories()
{
    return $this->hasMany(Category::class,'parent_category','id')->where('category_type','superior');
}

To use:

$cat3 = Category::where('category_type', 'main')->first();
$cat3->superiorChildCategories; //all the superior type categories where the main category has been set as parent category, will return null if there is no superior type child categories

Don't forget to set the actual parent type relation on the database as well, so parent_category column should be the id of the parent category.

It is also tested, and works as expected.


问:
retrieving FormData as its original form
Today, while working on a project which uses
below flow for creating new post in website

[Client] ---> FormData --> [FrontEnd Server] ---> FormData -->[Backend Server] --> save post

I have some form-data sent from client using fetch to frontend server

ex..

Client.js

let form_data = new FormData();
form_data.append('title', 'How to resolve Issue');
form_data.append('descr', '
The tips are mentioned in Home page!
');
form_data.append('image', uploaded_image);
fetch(`${FRONTEND_SERVER_URL}`, {method: 'POST', body: form_data})
```
<p>Where form_data is an instance of FormData object</p>
<p>but on my server when i try to retrieve same form_data, i can't</p>
<p>ex..
<strong>NextServer.js</strong></p>
<pre class="lang-js prettyprint-override"><code>export default async function handler(req, res){
    ...
    console.log(req.body);
    ...
}
</code>```

I Got Something like,

```<code>------WebKitFormBoundaryJzNYHjUhaXw7Qpnx
Content-Disposition: form-data; name="title"

How to resolve Issue
------WebKitFormBoundaryJzNYHjUhaXw7Qpnx
Content-Disposition: form-data; name="descr"

<p>The tips are mentioned in Home page!</p>

</code>```

So can you help me to get actual FormData sent from the client instead of raw data(string)

答: FormData uses multipart/form-data format. That is not a simple POST request with a body. It is generally used for uploading files, that's why it needs special handling. As an alternative, you could use JSON</p>

Body:
Today, while working on a project which uses
below flow for creating new post in website

[Client] ---> FormData --> [FrontEnd Server] ---> FormData -->[Backend Server] --> save post

I have some form-data sent from client using fetch to frontend server

ex..

Client.js

let form_data = new FormData();
form_data.append('title', 'How to resolve Issue');
form_data.append('descr', '
The tips are mentioned in Home page!
');
form_data.append('image', uploaded_image);
fetch(`${FRONTEND_SERVER_URL}`, {method: 'POST', body: form_data})

Where form_data is an instance of FormData object

but on my server when i try to retrieve same form_data, i can't

ex..
NextServer.js

export default async function handler(req, res){
    ...
    console.log(req.body);
    ...
}

I Got Something like,

------WebKitFormBoundaryJzNYHjUhaXw7Qpnx
Content-Disposition: form-data; name="title"

How to resolve Issue
------WebKitFormBoundaryJzNYHjUhaXw7Qpnx
Content-Disposition: form-data; name="descr"

The tips are mentioned in Home page!

So can you help me to get actual FormData sent from the client instead of raw data(string)


问:
Where are default arguement of function stored in memory, Is it put along with function address in code segment?
void display(char = '*', int = 3);  where is '*' and 3 stored.
Code taken from https://www.programiz.com/cpp-programming/default-argument

答:
The way default arguments work is rather primitive. Whenever you call the function:

```<code>display('x',42);
display('x');
display();
</code>```

Then the default arguments are replaced at the call site, ie the three calls are equivalent to:

```<code>display('x',42);
display('x',3);
display('*',3);
</code>```

Default arguments aren't first class citizens. They are not stored along with the function. They are no different from "normal" parameters you pass to a function.

Body:
The way default arguments work is rather primitive. Whenever you call the function:

display('x',42);
display('x');
display();

Then the default arguments are replaced at the call site, ie the three calls are equivalent to:

display('x',42);
display('x',3);
display('*',3);

Default arguments aren't first class citizens. They are not stored along with the function. They are no different from "normal" parameters you pass to a function.


问:
Incosistent rows updated between MySQL and go-sql-driver/mysql
I'm trying to update a record in the database, and based on the rowsAffected() count I can decided whether the record exists or not. In which case if it doesn't (rowsAffected() == 0) I will run a insert query.

func (u *UserService) NewAddress(l *models.Address) error {
    var err error
    db, err := database.GetConnection()
    if err != nil {
        return err
    }
    defer db.Close()
    sql := `UPDATE Locations SET Address = ?, StateId = ? WHERE Id = ?`
    query := `INSERT INTO Locations (UserId, StateId, Address, City, StreetName, StreetNumber, Code, Latitude, Longitude) VALUES(?,?,?,?,?,?,?,?,?)`

    stmt, err := db.Prepare(sql)
    if err != nil {
        return err
    }
    results, err := stmt.Exec("Port St Johns, South Africa", l.StateId, l.Id)
    if err != nil {
        return err
    }
    fmt.Println(results.RowsAffected())
    if affected, err := results.RowsAffected(); err == nil {
        if affected == 0 {
            insert, err := db.Query(query, l.UserId, l.StateId, l.Address, l.City, l.StreetName, l.StreetNumber, l.Code, l.Latitude, l.Longitude)
            defer insert.Close()
            if err != nil {
                return err
            }
        }
    }
    return nil
}

```
<p>However, the <code>RowsAffected()</code> func always returns 0 if the value of the column I'm updating e.i <code>Address</code> is the same as the one already stored in the database. It also returns 0 if it can't find the record I'm trying to update.</p>
<p>If I run the same query directly on MySQL console however, even if the update (address) is exactly the same, it always returns <code>Update Rows</code> >= 1 as long as the <code>WHERE</code> clause condition is met.</p>
<pre class="lang-sql prettyprint-override"><code>UPDATE Locations
SET Address = "Port St Johns", StateId = 2
WHERE Id = 102;
</code>```

Can I do this update any different? I'm trying to avoid a select query to check if the record exists before updating/inserting.

答: I added a updated timestamp as @mkopriva suggested. That way there's always an updated count even when all the data is the same, the timestamp will change/update

Body:
I'm trying to update a record in the database, and based on the rowsAffected() count I can decided whether the record exists or not. In which case if it doesn't (rowsAffected() == 0) I will run a insert query.

func (u *UserService) NewAddress(l *models.Address) error {
    var err error
    db, err := database.GetConnection()
    if err != nil {
        return err
    }
    defer db.Close()
    sql := `UPDATE Locations SET Address = ?, StateId = ? WHERE Id = ?`
    query := `INSERT INTO Locations (UserId, StateId, Address, City, StreetName, StreetNumber, Code, Latitude, Longitude) VALUES(?,?,?,?,?,?,?,?,?)`

    stmt, err := db.Prepare(sql)
    if err != nil {
        return err
    }
    results, err := stmt.Exec("Port St Johns, South Africa", l.StateId, l.Id)
    if err != nil {
        return err
    }
    fmt.Println(results.RowsAffected())
    if affected, err := results.RowsAffected(); err == nil {
        if affected == 0 {
            insert, err := db.Query(query, l.UserId, l.StateId, l.Address, l.City, l.StreetName, l.StreetNumber, l.Code, l.Latitude, l.Longitude)
            defer insert.Close()
            if err != nil {
                return err
            }
        }
    }
    return nil
}

However, the RowsAffected() func always returns 0 if the value of the column I'm updating e.i Address is the same as the one already stored in the database. It also returns 0 if it can't find the record I'm trying to update.

If I run the same query directly on MySQL console however, even if the update (address) is exactly the same, it always returns Update Rows >= 1 as long as the WHERE clause condition is met.

UPDATE Locations
SET Address = "Port St Johns", StateId = 2
WHERE Id = 102;

Can I do this update any different? I'm trying to avoid a select query to check if the record exists before updating/inserting.


问:
Mifare DESFire EV1 4K AES authentication issue
Please, can someone tell me what I'm doing wrong. I have to AES authenticate my card. The card is Mifare DESFire EV1 4K and the reader is Omnikey 5121. I followed some examples here on Stack but I always fail in the last step where card's rotated RndA is not equal to my rotated RndA. Is something wrong with the AES configuration?

```<code>public static byte[] Authenticate_AES(this SCardReader reader, byte[] key)
    {
        using (var aes = Aes.Create())
        {
            aes.Key = key;
            aes.Padding = PaddingMode.None;
            aes.Mode = CipherMode.CBC;
            aes.BlockSize = 128;
            aes.IV = SCardUtils.StringToByteArray("00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00");

            var decryptor = aes.CreateDecryptor();
            var encryptor = aes.CreateEncryptor();
            var rnd = new Random();

            //Get encrypted RandB from the card
            var rAPDU = reader.Transmit(0x90, 0xAA, 0, 0, SCardUtils.StringToByteArray("00"));

            if (!rAPDU.HasData)
                throw new Exception("RandB_enc is null");

            //Encrypted RndB
            var RndB_enc = new byte[16];
            rAPDU.Data.CopyTo(RndB_enc, 0);
            SCardUtils.ShowBytes(RndB_enc, "RndB_enc");

            //Decrypt encrypted RndB
            var RndB = decryptor.TransformFinalBlock(RndB_enc, 0, RndB_enc.Length);
            SCardUtils.ShowBytes(RndB, "RndB");

            //Rotate RndB 1 byte to the left
            var RndB_rot = SCardUtils.RotateLeft(RndB);
            SCardUtils.ShowBytes(RndB_rot, "RndB_rot");

            //Generate random RndA
            var RndA = new byte[16];
            rnd.NextBytes(RndA);
            SCardUtils.ShowBytes(RndA, "RndA");

            //Concatenate RndA and RndB_rot
            var RndAB_rot = RndA.Concat(RndB_rot).ToArray();
            SCardUtils.ShowBytes(RndAB_rot, "RndAB_rot");

            //Encypt RndAB_rot
            var dataToSend = encryptor.TransformFinalBlock(RndAB_rot, 0, RndAB_rot.Length);
            SCardUtils.ShowBytes(dataToSend, "Encrypted data");

            rAPDU = reader.Transmit(0x90, 0xAF, 0, 0, dataToSend);

            if (!rAPDU.HasData)
                throw new Exception("rAPDU data is null");

            //Encrypted RndA_rot
            var RndA_rot_enc = new byte[16];
            rAPDU.Data.CopyTo(RndA_rot_enc, 0);
            SCardUtils.ShowBytes(RndA_rot_enc, "RndA_rot_enc");

            //Decrypt encrypted RndA_rot
            var RndA_rot_dec = decryptor.TransformFinalBlock(RndA_rot_enc, 0, RndA_rot_enc.Length);
            SCardUtils.ShowBytes(RndA_rot_dec, "RndA_rot_dec");

            var RndA_rot = SCardUtils.RotateLeft(RndA);
            SCardUtils.ShowBytes(RndA_rot, "RndA_rot");

            //Compare RndA_rot with RndA rotated to the left
            if (!SCardUtils.IsEqualTo(RndA_rot_dec, RndA_rot))
                throw new Exception($"Error authenticating card. The values are not equal.");

            var sessionKey = new byte[16];
            Array.Copy(RndA, 0, sessionKey, 0, 4);
            Array.Copy(RndB, 0, sessionKey, 4, 4);
            Array.Copy(RndA, 12, sessionKey, 8, 4);
            Array.Copy(RndB, 12, sessionKey, 12, 4);

            return sessionKey;
        }
    }
</code>```

Here is the output:

```<code>Reader name:  OMNIKEY CardMan 5x21-CL 0
RndB_enc:     08 DD A2 12 57 43 6C F7 75 98 78 9E 6C 0A A7 06
RndB:         16 C8 35 7A 4A 36 29 D2 F0 86 26 AD FA CA 81 9F
RndB_rot:     C8 35 7A 4A 36 29 D2 F0 86 26 AD FA CA 81 9F 16
RndA:         77 93 A5 8D 0E 0D 88 88 22 C3 40 9C 26 67 95 35
RndAB_rot:    77 93 A5 8D 0E 0D 88 88 22 C3 40 9C 26 67 95 35 C8 35 7A 4A 36 29 D2 F0 86 26 AD FA CA 81 9F 16
Data:         4D BD 7A E8 B8 6C 00 5F E4 B5 B5 42 7B AE 51 39 25 77 CB 60 83 6A E8 15 B9 9D FD A9 FD A7 75 9F
RndA_rot_enc: D6 CB CF 08 5F 8A E8 6C 30 95 34 6F DD CF 4F FA
RndA_rot_dec: 6B 70 54 39 CD 8E 97 42 E2 A5 FF E3 90 95 46 E0
RndA_rot:     93 A5 8D 0E 0D 88 88 22 C3 40 9C 26 67 95 35 77
</code>```

So you can see RndA_rot_dec and RndA_rot are not equal and I can't figure it out why.

Thank you all in advance.

答:
I finally got the solution. I also modified the code a bit so it can be more understandable for everyone who will have a problem as I did. For several weeks.

```<code>public static byte[] Authenticate_AES(this SCardReader reader, byte[] key, byte[] IV)
    {
        //Get encrypted RndB from the tag
        var rAPDU = reader.Transmit(0x90, 0xAA, 0, 0, SCardUtils.StringToByteArray("00"));

        if (!rAPDU.HasData)
            throw new Exception("RandB_enc is null");

        var aes = Aes.Create();
        aes.Mode = CipherMode.CBC;
        aes.KeySize = 128;
        aes.BlockSize = 128;
        aes.Padding = PaddingMode.None;
        aes.Key = key;
        aes.IV = IV; //16 bytes of zeros

        //Encrypted RndB from the tag
        var RndB_enc = rAPDU.Data.ToArray();
        SCardUtils.ShowBytes(RndB_enc, "RndB_enc");

        var decryptor = aes.CreateDecryptor();

        //Decrypt encrypted RndB
        var RndB = decryptor.TransformFinalBlock(RndB_enc, 0, RndB_enc.Length);
        SCardUtils.ShowBytes(RndB, "RndB");

        //Rotate RndB 1 byte to the left
        var RndB_rot = SCardUtils.RotateLeft(RndB);
        SCardUtils.ShowBytes(RndB_rot, "RndB_rot");

        var rnd = new Random();

        //Generate random RndA
        var RndA = new byte[16];
        rnd.NextBytes(RndA);
        SCardUtils.ShowBytes(RndA, "RndA");

        //Concatenate RndA and RndB_rot
        var RndAB_rot = RndA.Concat(RndB_rot).ToArray();
        SCardUtils.ShowBytes(RndAB_rot, "RndAB_rot");

        //IV is now encrypted RndB received from the tag
        aes.IV = RndB_enc;

        var encryptor = aes.CreateEncryptor();

        //Encypt RndAB_rot
        var RndAB_rot_enc = encryptor.TransformFinalBlock(RndAB_rot, 0, RndAB_rot.Length);
        SCardUtils.ShowBytes(RndAB_rot_enc, "RndAB_rot_enc");

        rAPDU = reader.Transmit(0x90, 0xAF, 0, 0, RndAB_rot_enc);

        if (!rAPDU.HasData)
            throw new Exception("rAPDU data is null");

        //Encrypted RndA_rot from the tag
        var RndA_rot_enc = rAPDU.Data.ToArray();
        SCardUtils.ShowBytes(RndA_rot_enc, "RndA_rot_enc");

        //IV is now the last 16 bytes of RndAB_rot_enc
        aes.IV = RndAB_rot_enc.Skip(16).Take(16).ToArray();

        decryptor = aes.CreateDecryptor();

        //Decrypt encrypted RndA_rot
        var RndA_rot = decryptor.TransformFinalBlock(rAPDU.Data, 0, rAPDU.Data.Length);
        SCardUtils.ShowBytes(RndA_rot, "RndA_rot");

        //Compare RndA_rot_dec with RndA_rot
        if (!SCardUtils.IsEqualTo(RndA_rot, SCardUtils.RotateLeft(RndA)))
            throw new Exception($"Error authenticating card. The values are not equal.");

        var sessionKey = new byte[16];
        Array.Copy(RndA, 0, sessionKey, 0, 4);
        Array.Copy(RndB, 0, sessionKey, 4, 4);
        Array.Copy(RndA, 12, sessionKey, 8, 4);
        Array.Copy(RndB, 12, sessionKey, 12, 4);

        aes.Clear();
        return sessionKey;
    }
</code>```

The problem was with Init Vector. It is changing through the three-pass authentication.

Here is the final output:

```<code>   Reader name: OMNIKEY CardMan 5x21-CL 0
      RndB_enc: 6F 40 6D 9D 51 7A 2C 9E 88 C9 2C 84 80 94 E3 F7
          RndB: FB FB A7 5F 54 97 D7 CA 4B 15 07 F1 A0 D1 A2 68
      RndB_rot: FB A7 5F 54 97 D7 CA 4B 15 07 F1 A0 D1 A2 68 FB
          RndA: 87 7B BA 48 4D 01 14 CE 4D 8E 33 A5 1B 0F 00 E9
     RndAB_rot: 87 7B BA 48 4D 01 14 CE 4D 8E 33 A5 1B 0F 00 E9 FB A7 5F 54 97 D7 CA 4B 15 07 F1 A0 D1 A2 68 FB
 RndAB_rot_enc: 0B 8B 4E D9 BF 40 51 F0 83 FC 44 E8 B7 A7 21 26 DE A9 B9 CE E5 05 F7 A5 46 FE 91 0F 59 2B 90 E7
  RndA_rot_enc: 9F 3D E8 90 37 2E 7B F6 1E BA AC 29 6E 94 1C 9E
      RndA_rot: 7B BA 48 4D 01 14 CE 4D 8E 33 A5 1B 0F 00 E9 87
</code>```

As you can see RndA (line 5) rotated 1 byte to the left is equal to RndA_rot (last line). With this authentication is completed.

Body:
Please, can someone tell me what I'm doing wrong. I have to AES authenticate my card. The card is Mifare DESFire EV1 4K and the reader is Omnikey 5121. I followed some examples here on Stack but I always fail in the last step where card's rotated RndA is not equal to my rotated RndA. Is something wrong with the AES configuration?

public static byte[] Authenticate_AES(this SCardReader reader, byte[] key)
    {
        using (var aes = Aes.Create())
        {
            aes.Key = key;
            aes.Padding = PaddingMode.None;
            aes.Mode = CipherMode.CBC;
            aes.BlockSize = 128;
            aes.IV = SCardUtils.StringToByteArray("00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00");

            var decryptor = aes.CreateDecryptor();
            var encryptor = aes.CreateEncryptor();
            var rnd = new Random();

            //Get encrypted RandB from the card
            var rAPDU = reader.Transmit(0x90, 0xAA, 0, 0, SCardUtils.StringToByteArray("00"));

            if (!rAPDU.HasData)
                throw new Exception("RandB_enc is null");

            //Encrypted RndB
            var RndB_enc = new byte[16];
            rAPDU.Data.CopyTo(RndB_enc, 0);
            SCardUtils.ShowBytes(RndB_enc, "RndB_enc");

            //Decrypt encrypted RndB
            var RndB = decryptor.TransformFinalBlock(RndB_enc, 0, RndB_enc.Length);
            SCardUtils.ShowBytes(RndB, "RndB");

            //Rotate RndB 1 byte to the left
            var RndB_rot = SCardUtils.RotateLeft(RndB);
            SCardUtils.ShowBytes(RndB_rot, "RndB_rot");

            //Generate random RndA
            var RndA = new byte[16];
            rnd.NextBytes(RndA);
            SCardUtils.ShowBytes(RndA, "RndA");

            //Concatenate RndA and RndB_rot
            var RndAB_rot = RndA.Concat(RndB_rot).ToArray();
            SCardUtils.ShowBytes(RndAB_rot, "RndAB_rot");

            //Encypt RndAB_rot
            var dataToSend = encryptor.TransformFinalBlock(RndAB_rot, 0, RndAB_rot.Length);
            SCardUtils.ShowBytes(dataToSend, "Encrypted data");

            rAPDU = reader.Transmit(0x90, 0xAF, 0, 0, dataToSend);

            if (!rAPDU.HasData)
                throw new Exception("rAPDU data is null");

            //Encrypted RndA_rot
            var RndA_rot_enc = new byte[16];
            rAPDU.Data.CopyTo(RndA_rot_enc, 0);
            SCardUtils.ShowBytes(RndA_rot_enc, "RndA_rot_enc");

            //Decrypt encrypted RndA_rot
            var RndA_rot_dec = decryptor.TransformFinalBlock(RndA_rot_enc, 0, RndA_rot_enc.Length);
            SCardUtils.ShowBytes(RndA_rot_dec, "RndA_rot_dec");

            var RndA_rot = SCardUtils.RotateLeft(RndA);
            SCardUtils.ShowBytes(RndA_rot, "RndA_rot");

            //Compare RndA_rot with RndA rotated to the left
            if (!SCardUtils.IsEqualTo(RndA_rot_dec, RndA_rot))
                throw new Exception($"Error authenticating card. The values are not equal.");

            var sessionKey = new byte[16];
            Array.Copy(RndA, 0, sessionKey, 0, 4);
            Array.Copy(RndB, 0, sessionKey, 4, 4);
            Array.Copy(RndA, 12, sessionKey, 8, 4);
            Array.Copy(RndB, 12, sessionKey, 12, 4);

            return sessionKey;
        }
    }

Here is the output:

Reader name:  OMNIKEY CardMan 5x21-CL 0
RndB_enc:     08 DD A2 12 57 43 6C F7 75 98 78 9E 6C 0A A7 06
RndB:         16 C8 35 7A 4A 36 29 D2 F0 86 26 AD FA CA 81 9F
RndB_rot:     C8 35 7A 4A 36 29 D2 F0 86 26 AD FA CA 81 9F 16
RndA:         77 93 A5 8D 0E 0D 88 88 22 C3 40 9C 26 67 95 35
RndAB_rot:    77 93 A5 8D 0E 0D 88 88 22 C3 40 9C 26 67 95 35 C8 35 7A 4A 36 29 D2 F0 86 26 AD FA CA 81 9F 16
Data:         4D BD 7A E8 B8 6C 00 5F E4 B5 B5 42 7B AE 51 39 25 77 CB 60 83 6A E8 15 B9 9D FD A9 FD A7 75 9F
RndA_rot_enc: D6 CB CF 08 5F 8A E8 6C 30 95 34 6F DD CF 4F FA
RndA_rot_dec: 6B 70 54 39 CD 8E 97 42 E2 A5 FF E3 90 95 46 E0
RndA_rot:     93 A5 8D 0E 0D 88 88 22 C3 40 9C 26 67 95 35 77

So you can see RndA_rot_dec and RndA_rot are not equal and I can't figure it out why.

Thank you all in advance.

Body:
I finally got the solution. I also modified the code a bit so it can be more understandable for everyone who will have a problem as I did. For several weeks.

public static byte[] Authenticate_AES(this SCardReader reader, byte[] key, byte[] IV)
    {
        //Get encrypted RndB from the tag
        var rAPDU = reader.Transmit(0x90, 0xAA, 0, 0, SCardUtils.StringToByteArray("00"));

        if (!rAPDU.HasData)
            throw new Exception("RandB_enc is null");

        var aes = Aes.Create();
        aes.Mode = CipherMode.CBC;
        aes.KeySize = 128;
        aes.BlockSize = 128;
        aes.Padding = PaddingMode.None;
        aes.Key = key;
        aes.IV = IV; //16 bytes of zeros

        //Encrypted RndB from the tag
        var RndB_enc = rAPDU.Data.ToArray();
        SCardUtils.ShowBytes(RndB_enc, "RndB_enc");

        var decryptor = aes.CreateDecryptor();

        //Decrypt encrypted RndB
        var RndB = decryptor.TransformFinalBlock(RndB_enc, 0, RndB_enc.Length);
        SCardUtils.ShowBytes(RndB, "RndB");

        //Rotate RndB 1 byte to the left
        var RndB_rot = SCardUtils.RotateLeft(RndB);
        SCardUtils.ShowBytes(RndB_rot, "RndB_rot");

        var rnd = new Random();

        //Generate random RndA
        var RndA = new byte[16];
        rnd.NextBytes(RndA);
        SCardUtils.ShowBytes(RndA, "RndA");

        //Concatenate RndA and RndB_rot
        var RndAB_rot = RndA.Concat(RndB_rot).ToArray();
        SCardUtils.ShowBytes(RndAB_rot, "RndAB_rot");

        //IV is now encrypted RndB received from the tag
        aes.IV = RndB_enc;

        var encryptor = aes.CreateEncryptor();

        //Encypt RndAB_rot
        var RndAB_rot_enc = encryptor.TransformFinalBlock(RndAB_rot, 0, RndAB_rot.Length);
        SCardUtils.ShowBytes(RndAB_rot_enc, "RndAB_rot_enc");

        rAPDU = reader.Transmit(0x90, 0xAF, 0, 0, RndAB_rot_enc);

        if (!rAPDU.HasData)
            throw new Exception("rAPDU data is null");

        //Encrypted RndA_rot from the tag
        var RndA_rot_enc = rAPDU.Data.ToArray();
        SCardUtils.ShowBytes(RndA_rot_enc, "RndA_rot_enc");

        //IV is now the last 16 bytes of RndAB_rot_enc
        aes.IV = RndAB_rot_enc.Skip(16).Take(16).ToArray();

        decryptor = aes.CreateDecryptor();

        //Decrypt encrypted RndA_rot
        var RndA_rot = decryptor.TransformFinalBlock(rAPDU.Data, 0, rAPDU.Data.Length);
        SCardUtils.ShowBytes(RndA_rot, "RndA_rot");

        //Compare RndA_rot_dec with RndA_rot
        if (!SCardUtils.IsEqualTo(RndA_rot, SCardUtils.RotateLeft(RndA)))
            throw new Exception($"Error authenticating card. The values are not equal.");

        var sessionKey = new byte[16];
        Array.Copy(RndA, 0, sessionKey, 0, 4);
        Array.Copy(RndB, 0, sessionKey, 4, 4);
        Array.Copy(RndA, 12, sessionKey, 8, 4);
        Array.Copy(RndB, 12, sessionKey, 12, 4);

        aes.Clear();
        return sessionKey;
    }

The problem was with Init Vector. It is changing through the three-pass authentication.

Here is the final output:

   Reader name: OMNIKEY CardMan 5x21-CL 0
      RndB_enc: 6F 40 6D 9D 51 7A 2C 9E 88 C9 2C 84 80 94 E3 F7
          RndB: FB FB A7 5F 54 97 D7 CA 4B 15 07 F1 A0 D1 A2 68
      RndB_rot: FB A7 5F 54 97 D7 CA 4B 15 07 F1 A0 D1 A2 68 FB
          RndA: 87 7B BA 48 4D 01 14 CE 4D 8E 33 A5 1B 0F 00 E9
     RndAB_rot: 87 7B BA 48 4D 01 14 CE 4D 8E 33 A5 1B 0F 00 E9 FB A7 5F 54 97 D7 CA 4B 15 07 F1 A0 D1 A2 68 FB
 RndAB_rot_enc: 0B 8B 4E D9 BF 40 51 F0 83 FC 44 E8 B7 A7 21 26 DE A9 B9 CE E5 05 F7 A5 46 FE 91 0F 59 2B 90 E7
  RndA_rot_enc: 9F 3D E8 90 37 2E 7B F6 1E BA AC 29 6E 94 1C 9E
      RndA_rot: 7B BA 48 4D 01 14 CE 4D 8E 33 A5 1B 0F 00 E9 87

As you can see RndA (line 5) rotated 1 byte to the left is equal to RndA_rot (last line). With this authentication is completed.


问:
Flutter Hive storing box on network drive
I'm working on a project that requires multiple clients to simultaneously work on synchronised data. There will be 4 clients working together connected to the same network. I've been looking at various database solutions for this. Now I'm not looking to go super deep into anything ridiculously advanced so I have mostly considered Hive for a nice lightweight local database, or firebase for a good cloud option. A key thing to consider in this project is it will be deployed in an area with quite spotty internet, so ideally I want everything running over the local network.

Both do come with drawbacks. Firebase requires a steady network connection. Lose that and the whole system is useless.

I'd like to use hive but I need to find a way to make the data sync between the 4 computers in the system. Is it possible to put my hive directory on a network drive and have all 4 computers access the boxes there?

Alternatively, are there any other options anyone can recommend? Can Firebase be run over LAN? I know they have a local emulator suite, but is that suitable for a production app?

Thanks for any help

答:
Your question isn't specific enough to answer directly.

Firebase Firestore provides a non-SQL database running on a Google Cloud server. Hive is only a SQL-like database. According to Hive's documentation, Hive can sync data with a server. Although to my knowledge this isn't really common.

You're asking for a way to sync data from multiple clients. As you've mentioned, the easiest solution would be to use Firebase Firestore.
Since these clients are on the same network, you can set up a local server. It might also be possible for the app itself to create a local server (like a LAN). But keep in mind, every other solution will be more error-prone and difficult to set up than Firestore.


问:
Why does "Ctrl + R", which is the key bound to "Reload Window" in vscode, doesn't Reload Window?
I'm a new user of vscode.

I ran into a problem that I was told would be resolved by "Reload Window".  So I first went through the "Command Palette" to find it, and it did fix my problem.  However, I noticed that it says it is bound to "Ctrl + R".  So if that's the key sequence it's bound to, why does holding down Ctrl and pressing r not execute that function?  It actually brings up the "Select to open" prompt, with the list of recent files as selection choices.

答:
Step

1.VIEW->COMMAND PALETTE->RELOAD WINDOW or cntrl+Shift+p

Click the setting icon

Right Button -> change when expression->clear all the text or command and press enter

Now Test the code cntrl+R

Total Result Live(Gif):

Warning.

Sometimes ctrl+R already has many bindings.
Consider changing the key binding of "Reload Window".
Or change the key bindings of those other commands.


问:
How do I initialize a variable size array in a C++ class?
I have a class that needs to store an array with a variable size. Ideally, this size would be defined as a parameter given to the constructor of the class.

I can define a constant and then work with that, as seen below:

```<code>#include <iostream>
#define ARRSIZE 5

class Classy{
    private:
        int myarray[ARRSIZE];

    public:
        Classy();
        void printarray();
};

Classy::Classy(){
    for(int i = 0; i < ARRSIZE; i++){
        myarray[i] = i * i * 2;
    }
}

void Classy::printarray(){
    for(int i = 0; i < ARRSIZE; i++){
        std::cout << myarray[i] << std::endl;
    }
}
</code>```

However, I'd like to do it like this:

```<code>#include <iostream>
class Classy{
    private:
        int arraysize;
        int myarray[arraysize];

    public:
        Classy(int parraysize);
        void printarray();
};

Classy::Classy(int parraysize){
    arraysize = parraysize;
    for(int i = 0; i < arraysize; i++){
        myarray[i] = i * i * 2;
    }
}

void Classy::printarray(){
    for(int i = 0; i < arraysize; i++){
        std::cout << myarray[i] << std::endl;
    }
}
</code>```

The compiler really doesn't like my approach though, so I am looking for an alternative way of doing things.

I did some googling on the subject, but my searches did not come up fruitful. I found this approach which does it using dynamic memory allocation. This is something I'd like to avoid, so I am looking for a solution that does not rely on that. It might well be (and I'm starting to think) that it is the only elegant solution to my problem (and if this is the case, the question should of course be closed as duplicate).

答:
A bit late. However, this may be another approach.</p>
```<code>#include <iostream>
#include <cstddef>

class Classy
{
public:
    Classy();
    template <size_t ARRSIZE>
    Classy(int (&arr)[ARRSIZE], size_t size = 0);
    void printarray();
private:
    int* myarray;
    size_t max_size;
    size_t arraysize;
};

template <size_t ARRSIZE>
Classy::Classy(int (&arr)[ARRSIZE], size_t size)
{
    myarray = arr;
    max_size = ARRSIZE;
    arraysize = size;
}

void Classy::printarray(){
    for(int i = 0; i < max_size; i++){
        std::cout << i << " " << myarray[i] << std::endl;
    }
}

int main()
{
    int arr[10];
    Classy c(arr);

    c.printarray();

    return 0;
}
</code>```

Body:
I have a class that needs to store an array with a variable size. Ideally, this size would be defined as a parameter given to the constructor of the class.

I can define a constant and then work with that, as seen below:

#include <iostream>
#define ARRSIZE 5

class Classy{
    private:
        int myarray[ARRSIZE];

    public:
        Classy();
        void printarray();
};

Classy::Classy(){
    for(int i = 0; i < ARRSIZE; i++){
        myarray[i] = i * i * 2;
    }
}

void Classy::printarray(){
    for(int i = 0; i < ARRSIZE; i++){
        std::cout << myarray[i] << std::endl;
    }
}

However, I'd like to do it like this:

#include <iostream>
class Classy{
    private:
        int arraysize;
        int myarray[arraysize];

    public:
        Classy(int parraysize);
        void printarray();
};

Classy::Classy(int parraysize){
    arraysize = parraysize;
    for(int i = 0; i < arraysize; i++){
        myarray[i] = i * i * 2;
    }
}

void Classy::printarray(){
    for(int i = 0; i < arraysize; i++){
        std::cout << myarray[i] << std::endl;
    }
}

The compiler really doesn't like my approach though, so I am looking for an alternative way of doing things.

I did some googling on the subject, but my searches did not come up fruitful. I found this approach which does it using dynamic memory allocation. This is something I'd like to avoid, so I am looking for a solution that does not rely on that. It might well be (and I'm starting to think) that it is the only elegant solution to my problem (and if this is the case, the question should of course be closed as duplicate).

Body:
A bit late. However, this may be another approach.

#include <iostream>
#include <cstddef>

class Classy
{
public:
    Classy();
    template <size_t ARRSIZE>
    Classy(int (&arr)[ARRSIZE], size_t size = 0);
    void printarray();
private:
    int* myarray;
    size_t max_size;
    size_t arraysize;
};

template <size_t ARRSIZE>
Classy::Classy(int (&arr)[ARRSIZE], size_t size)
{
    myarray = arr;
    max_size = ARRSIZE;
    arraysize = size;
}

void Classy::printarray(){
    for(int i = 0; i < max_size; i++){
        std::cout << i << " " << myarray[i] << std::endl;
    }
}

int main()
{
    int arr[10];
    Classy c(arr);

    c.printarray();

    return 0;
}


问:
Uncaught Error: Cannot find module './recipes' in React Native
So I'm trying to import files from the ./recipes folder but it keeps showing in the error that it can't find the module './recipes'

This is my App.js:

```<code>import React, { Component } from "react";

import Home from "./Screens/Home";
import { Ampalaya, AdobongSitaw } from "./recipes";

<NavigationContainer>
        <StatusBar style="auto" />
        <Stack.Navigator>
          <Stack.Screen
            name="Home"
            component={Home}
            options={{ headerShown: false }}
          />

          <Stack.Screen
            name="Ampalaya"
            component={Ampalaya}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />

          <Stack.Screen
            name="AdobongSitaw"
            component={AdobongSitaw}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
</Stack.Navigator>
      </NavigationContainer>
</code>```

Also all those files are existing on their perspective folder. Still can't find a solution. Here is my folder structure:

enter image description here

答:
Please try to import it as you are importing your Home Screen.

```<code>import Ampalaya from "./recipes/Ampalaya";
import AdobongSitaw from "./recipes/AdobongSitaw";
</code>```

The only way you could achieve the way you are importing is to make a recipe module.

Create index.js in your recipes folder.

import all your components into the file.

export the module with all components.

```<code>//index.js
import Ampalaya from "./Ampalaya";
import AdobongSitaw from "./AdobongSitaw";

export { Ampalaya, AdobongSitaw };
</code>```

Import the way you were doing it:

```<code>import { Ampalaya, AdobongSitaw } from "./recipes";
</code>```

Body:
So I'm trying to import files from the ./recipes folder but it keeps showing in the error that it can't find the module './recipes'

This is my App.js:

import React, { Component } from "react";

import Home from "./Screens/Home";
import { Ampalaya, AdobongSitaw } from "./recipes";

<NavigationContainer>
        <StatusBar style="auto" />
        <Stack.Navigator>
          <Stack.Screen
            name="Home"
            component={Home}
            options={{ headerShown: false }}
          />

          <Stack.Screen
            name="Ampalaya"
            component={Ampalaya}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />

          <Stack.Screen
            name="AdobongSitaw"
            component={AdobongSitaw}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
</Stack.Navigator>
      </NavigationContainer>

Also all those files are existing on their perspective folder. Still can't find a solution. Here is my folder structure:

enter image description here

Body:
Please try to import it as you are importing your Home Screen.

import Ampalaya from "./recipes/Ampalaya";
import AdobongSitaw from "./recipes/AdobongSitaw";

The only way you could achieve the way you are importing is to make a recipe module.

Create index.js in your recipes folder.

import all your components into the file.

export the module with all components.

//index.js
import Ampalaya from "./Ampalaya";
import AdobongSitaw from "./AdobongSitaw";

export { Ampalaya, AdobongSitaw };

Import the way you were doing it:

import { Ampalaya, AdobongSitaw } from "./recipes";