问:
curl_multi_getcontent returns empty string
This question is very similar to PHP curl_multi_gecontent returns null, but I could not find a solution there. If I try to echo the result of the function, which should contain the request response, I get an empty string ("") instead.

Surely I am missing something wrong in my code but I can't put my finger on it. Can anyone help?

```<code>$id = "stuff";
$password = "mcmuffin";
$data = json_decode(file_get_contents('php://input'), true);
$ch = array();

// build the individual requests, but do not execute them
for($i = 0; $i < sizeof($data); $i++){
    $searchText = $data[$i];
    $type = "ligne3;pdi;voie;commune;cedexa";
    $word = "Contient";
    $option = "AND_OR_RES";
    $format = "json";
    $url = "http://somewebservice/service?chaineRecherche=".urlencode($searchText)."&typeRecherche=".urlencode($type)."&optionMot=".urlencode($word)."&optionRecherche=".urlencode($option)."&typeResultat=".urlencode($format)."&idClient=".urlencode($id)."&passwdClient=".urlencode($mcmuffin);

    $currentCurl = curl_init($url);
    curl_setopt($currentCurl, CURLOPT_HEADER, 0);
    curl_setopt($currentCurl, CURLOPT_RETURNTRANSFER, true);
    array_push($ch, $currentCurl);
}

// build the multi-curl handle, adding all $ch
$mh = curl_multi_init();
for($i = 0; $i < sizeof($ch); $i++){
    curl_multi_add_handle($mh, $ch[$i]);
}

// execute all queries simultaneously, and continue when all are complete
$active = null;
do {
  $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

// all of our requests are done, we can now access the results
for($i = 0; $i < sizeof($ch); $i++){
    echo "bonjour"; //does output
    $response = curl_multi_getcontent($ch[$i]); //empty??
    echo json_encode($response);
}

//close the handles
for($i = 0; $i < sizeof($ch); $i++){
    curl_multi_remove_handle($mh, $ch[$i]);
}
curl_multi_close($mh);
</code>```

Thanks

答:
If target redirects, you'll receive an empty response. Try:

```<code>curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
</code>```

Alternatively, if you already done but have set CURLOPT_MAXREDIRS, it may be more redirecting more times than you have allowed. Try increasing it.

See manual

Body:
This question is very similar to PHP curl_multi_gecontent returns null, but I could not find a solution there. If I try to echo the result of the function, which should contain the request response, I get an empty string ("") instead.

Surely I am missing something wrong in my code but I can't put my finger on it. Can anyone help?

$id = "stuff";
$password = "mcmuffin";
$data = json_decode(file_get_contents('php://input'), true);
$ch = array();

// build the individual requests, but do not execute them
for($i = 0; $i < sizeof($data); $i++){
    $searchText = $data[$i];
    $type = "ligne3;pdi;voie;commune;cedexa";
    $word = "Contient";
    $option = "AND_OR_RES";
    $format = "json";
    $url = "http://somewebservice/service?chaineRecherche=".urlencode($searchText)."&typeRecherche=".urlencode($type)."&optionMot=".urlencode($word)."&optionRecherche=".urlencode($option)."&typeResultat=".urlencode($format)."&idClient=".urlencode($id)."&passwdClient=".urlencode($mcmuffin);

    $currentCurl = curl_init($url);
    curl_setopt($currentCurl, CURLOPT_HEADER, 0);
    curl_setopt($currentCurl, CURLOPT_RETURNTRANSFER, true);
    array_push($ch, $currentCurl);
}

// build the multi-curl handle, adding all $ch
$mh = curl_multi_init();
for($i = 0; $i < sizeof($ch); $i++){
    curl_multi_add_handle($mh, $ch[$i]);
}

// execute all queries simultaneously, and continue when all are complete
$active = null;
do {
  $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

// all of our requests are done, we can now access the results
for($i = 0; $i < sizeof($ch); $i++){
    echo "bonjour"; //does output
    $response = curl_multi_getcontent($ch[$i]); //empty??
    echo json_encode($response);
}

//close the handles
for($i = 0; $i < sizeof($ch); $i++){
    curl_multi_remove_handle($mh, $ch[$i]);
}
curl_multi_close($mh);

Thanks

Body:
If target redirects, you'll receive an empty response. Try:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

Alternatively, if you already done but have set CURLOPT_MAXREDIRS, it may be more redirecting more times than you have allowed. Try increasing it.

See manual


来源: stackexchange

问:
Printing multiple lines of a dictionary
Suppose I define type

```<code>type person = { last_name: string; first_name: string; age: int};;
let person1 = {last_name="Doe"; first_name="John"; age=30};;
</code>```

How can I print

```<code>Last name : Doe
First name : John
Age : 30
</code>```

I thought using

```<code>match person1  with
| {last_name=ln; first_name=fn; age=a} -> print_string ...;;
</code>```

but it seems not the way to go. If person1 and person were defined to be a dictionary with 1000 elements, then that solution doesn't hold.

Is there a better way to challenge that problem? Be aware that I have to use the functional paradigm. So I can't use while or for loop directly

答:
It's hard to answer your question because you seem to have two different ideas of your type simultaneously. You can't have a type that's both a record and a dictionary. It's not possible.

Generally speaking, a dictionary is a collection of things. The convention for collections in OCaml is that they have a function named iter that traverses the collection.

Imagine you have an abstract collection defined by a module C. Conventionally you'll have a type 'a C.t for each collection, where 'a is the type of the elements of the collection. You'll also have (conventionally) a function C.iter of this type:

```<code>C.iter : ('a -> unit) -> 'a C.t -> unit
</code>```

This means you can pass a function (like your printing function) to C.iter, and then also pass a collection. The iter function will traverse the collection and call your function for every element.

In your case the module C would define the dictionary you're imagining, and the type person C.t would be the type of a dictionary of the records you show above. The function C.iter would have the type (person -> unit) -> person C.t -> unit. In other words, it would take a function and apply it to all the persons in the dictionary, one after the other.

We can't really say more unless we know the details of the dictionary that you are planning to create.

ContentLicense: CC BY-SA 4.0

Title: Printing multiple lines of a dictionary

Body:
Suppose I define type

type person = { last_name: string; first_name: string; age: int};;
let person1 = {last_name="Doe"; first_name="John"; age=30};;

How can I print

Last name : Doe
First name : John
Age : 30

I thought using

match person1  with
| {last_name=ln; first_name=fn; age=a} -> print_string ...;;

but it seems not the way to go. If person1 and person were defined to be a dictionary with 1000 elements, then that solution doesn't hold.

Is there a better way to challenge that problem? Be aware that I have to use the functional paradigm. So I can't use while or for loop directly

Body:
It's hard to answer your question because you seem to have two different ideas of your type simultaneously. You can't have a type that's both a record and a dictionary. It's not possible.

Generally speaking, a dictionary is a collection of things. The convention for collections in OCaml is that they have a function named iter that traverses the collection.

Imagine you have an abstract collection defined by a module C. Conventionally you'll have a type 'a C.t for each collection, where 'a is the type of the elements of the collection. You'll also have (conventionally) a function C.iter of this type:

C.iter : ('a -> unit) -> 'a C.t -> unit

This means you can pass a function (like your printing function) to C.iter, and then also pass a collection. The iter function will traverse the collection and call your function for every element.

In your case the module C would define the dictionary you're imagining, and the type person C.t would be the type of a dictionary of the records you show above. The function C.iter would have the type (person -> unit) -> person C.t -> unit. In other words, it would take a function and apply it to all the persons in the dictionary, one after the other.

We can't really say more unless we know the details of the dictionary that you are planning to create.


问:
Docker environmental variables are not accessible in a PHP web application
index.php:

```<code><?php
$host = getenv('HOST');
$port = getenv('PORT');
echo "HOST is : $host";
echo "PORT is : $port";
?>
</code>```

Dockerfile:

```<code>FROM php:7.4-cli
COPY . /var/www/php
EXPOSE 8000
RUN adduser rouser
CMD ["su", "-", "rouser", "-c", "cd /var/www/php && php -S 0.0.0.0:8000"]
</code>```

I build a PHP docker image for my application.

```<code>docker build -t php-web-app:1.0.0 .
</code>```

Running my PHP docker container:

```<code>docker run -e HOST='0.0.0.0' \
-e PORT='8084' \
-p 8000:8000 \
php-web-app:1.0.0
</code>```

I made a curl request to my web application, and here the docker environment variable is not accessible by the PHP web application. It seems to be a security feature and how to do we access the docker environmental variable within a php web application.

```<code>$ curl http://0.0.0.0:8000/
HOST is : PORT is :
</code>```

答:
I'm going to guess that changing user does not preserve the environment variables of your execution.

You can check which variables are available in the environment with the env command.

There are however several things that are non-idiomatic going on with your Dockerfile.

You should not create users in your docker image. You can simply set the userid and groupid of your user in the container by setting the --user uid:gid flag in docker run.

You should not run interactive commands such as adduser in a Dockerfile. Unless you can provide all parameters in a single command so that it can run without user-intervention. Adding users is not one of them; how will you provide a password?

So to see the the environment, change your CMD line to the following:

```<code>CMD ["su", "-", "rouser", "-c", "env"]
</code>```

You will see that it prints the following:

```<code>SHELL=/bin/bash
PWD=/home/rouser
LOGNAME=rouser
HOME=/home/rouser
USER=rouser
SHLVL=0
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
MAIL=/var/mail/rouser
_=/usr/bin/env
</code>```

The environment variables you set are not available. However, if we change the CMD line to just print the env we get another output.

```<code>CMD ["env"]
</code>```

shows us:

```<code>HOSTNAME=be0b41fed51e
PHP_INI_DIR=/usr/local/etc/php
PORT=8084
HOME=/root
PHP_LDFLAGS=-Wl,-O1 -pie
PHP_CFLAGS=-fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
PHP_MD5=
PHP_VERSION=7.4.6
GPG_KEYS=42670A7FE4D0441C8E4632349E4FDC074A4EF02D 5A52880781F755608BF815FC910DEB46F53EA312
PHP_CPPFLAGS=-fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
PHP_ASC_URL=https://www.php.net/distributions/php-7.4.6.tar.xz.asc
PHP_URL=https://www.php.net/distributions/php-7.4.6.tar.xz
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOST=0.0.0.0
PHPIZE_DEPS=autoconf            dpkg-dev           file             g++             gcc             libc-dev            make            pkg-config         re2c
PWD=/
PHP_SHA256=d740322f84f63019622b9f369d64ea5ab676547d2bdcf12be77a5a4cffd06832
</code>```

Notice here that the user is not rouser, but the root user. You can change this by passing, for example, --user 1000:1000 in your docker run command.

So, to fix your problem, I propose you use the following Dockerfile:

```<code>FROM php:7.4-cli
COPY . /var/www/php
EXPOSE 8000
# RUN adduser rouser
# CMD ["su", "-", "rouser", "-c", "cd /var/www/php && php -S 0.0.0.0:8000"]

WORKDIR /var/www/php
CMD ["php", "-S", "0.0.0.0:8000"]
</code>```

Then we get the following output:

```<code>$ curl http://0.0.0.0:8000
HOST is : 0.0.0.0PORT is : 8084
</code>```

Body:
index.php:

<?php
$host = getenv('HOST');
$port = getenv('PORT');
echo "HOST is : $host";
echo "PORT is : $port";
?>

Dockerfile:

FROM php:7.4-cli
COPY . /var/www/php
EXPOSE 8000
RUN adduser rouser
CMD ["su", "-", "rouser", "-c", "cd /var/www/php && php -S 0.0.0.0:8000"]

I build a PHP docker image for my application.

docker build -t php-web-app:1.0.0 .

Running my PHP docker container:

docker run -e HOST='0.0.0.0' \
-e PORT='8084' \
-p 8000:8000 \
php-web-app:1.0.0

I made a curl request to my web application, and here the docker environment variable is not accessible by the PHP web application. It seems to be a security feature and how to do we access the docker environmental variable within a php web application.

$ curl http://0.0.0.0:8000/
HOST is : PORT is :

Body:
I'm going to guess that changing user does not preserve the environment variables of your execution.

You can check which variables are available in the environment with the env command.

There are however several things that are non-idiomatic going on with your Dockerfile.

You should not create users in your docker image. You can simply set the userid and groupid of your user in the container by setting the --user uid:gid flag in docker run.

You should not run interactive commands such as adduser in a Dockerfile. Unless you can provide all parameters in a single command so that it can run without user-intervention. Adding users is not one of them; how will you provide a password?

So to see the the environment, change your CMD line to the following:

CMD ["su", "-", "rouser", "-c", "env"]

You will see that it prints the following:

SHELL=/bin/bash
PWD=/home/rouser
LOGNAME=rouser
HOME=/home/rouser
USER=rouser
SHLVL=0
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
MAIL=/var/mail/rouser
_=/usr/bin/env

The environment variables you set are not available. However, if we change the CMD line to just print the env we get another output.

CMD ["env"]

shows us:

HOSTNAME=be0b41fed51e
PHP_INI_DIR=/usr/local/etc/php
PORT=8084
HOME=/root
PHP_LDFLAGS=-Wl,-O1 -pie
PHP_CFLAGS=-fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
PHP_MD5=
PHP_VERSION=7.4.6
GPG_KEYS=42670A7FE4D0441C8E4632349E4FDC074A4EF02D 5A52880781F755608BF815FC910DEB46F53EA312
PHP_CPPFLAGS=-fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
PHP_ASC_URL=https://www.php.net/distributions/php-7.4.6.tar.xz.asc
PHP_URL=https://www.php.net/distributions/php-7.4.6.tar.xz
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOST=0.0.0.0
PHPIZE_DEPS=autoconf            dpkg-dev           file             g++             gcc             libc-dev            make            pkg-config         re2c
PWD=/
PHP_SHA256=d740322f84f63019622b9f369d64ea5ab676547d2bdcf12be77a5a4cffd06832

Notice here that the user is not rouser, but the root user. You can change this by passing, for example, --user 1000:1000 in your docker run command.

So, to fix your problem, I propose you use the following Dockerfile:

FROM php:7.4-cli
COPY . /var/www/php
EXPOSE 8000
# RUN adduser rouser
# CMD ["su", "-", "rouser", "-c", "cd /var/www/php && php -S 0.0.0.0:8000"]

WORKDIR /var/www/php
CMD ["php", "-S", "0.0.0.0:8000"]

Then we get the following output:

$ curl http://0.0.0.0:8000
HOST is : 0.0.0.0PORT is : 8084


问:
Status on AWS S3 cross region replication delete operations behaviour
I've been surprised to find out that file deletion was not replicated in a S3 bucket Cross Region Replication situation, running this simple test:

simplest configuration of a CRR

upload a new file

check it is replicated

delete the file (not a version of the file)

So I checked the documentation and I find this statement:

If you delete an object from the source bucket, the following occurs:

If you make a DELETE request without specifying an object version ID, Amazon S3 adds a delete marker. Amazon S3 deals with the delete
  marker as follows:

If using latest version of the replication configuration, that is you specify the Filter element in a replication configuration rule,
  Amazon S3 does not replicate the delete marker.

If don't specify the Filter element, Amazon S3 assumes replication configuration is a prior version V1. In the earlier
  version, Amazon S3 handled replication of delete markers differently.
  For more information, see Backward Compatibility .

The later link to backward compat tell me that:

When you delete an object from your source bucket without specifying an object version ID, Amazon S3 adds a delete marker. If you use V1 of the replication configuration XML, Amazon S3 replicates delete markers that resulted from user actions.[...]
  In V2, Amazon S3 doesn't replicate delete markers and therefore you must set the DeleteMarkerReplication element to Disabled.

So if I sum this up:

CRR configuration is considered v1 if there is no Filter

with CRR configuration v1, file deletion is replicated, not with v2

Well, this is my configuration :

```<code>{
    "ReplicationConfiguration": {
        "Role": "arn:aws:iam::271226720751:role/service-role/s3crr_role_for_mybucket_to_myreplica",
        "Rules": [
            {
                "ID": "first replication rule",
                "Status": "Enabled",
                "Destination": {
                    "Bucket": "arn:aws:s3:::myreplica"
                }
            }
        ]
    }
}
</code>```

And deletion is not replicated. So it makes me think that my configuration is still considered V2 (even if I have no filter).

So, can someone confirm this presumption?
And could someone tell me what does:

In V2, Amazon S3 doesn't replicate delete markers and therefore you must set the DeleteMarkerReplication element to Disabled

really mean?

答:
There are two different configuration when replicating delete marker, V1 and V2.

Currently, when you enable S3 Replication (CRR or SRR) from the console, V2 configuration is enabled by default. However, if your use case requires you to delete replicated objects whenever they are deleted from the source bucket, you need the V1 configuration

Here is the difference between V1 and V2:

V1 configuration

The delete marker is replicated (V1 configuration). A subsequent GET request to the deleted object in both the source and the destination bucket does not return the object.

V2 configuration

The delete marker is not replicated (V2 configuration). A subsequent GET request to the deleted object returns the object only in the destination bucket.

To enable V1 configuration (to replicate delete marker), use the policy below. Keep in mind that certain replication features such as tag-based filtering and Replication Time Control (RTC) that are only available in V2 configurations.

{
    "Role": " IAM-role-ARN ",
    "Rules": [
        {
            "ID": "Replication V1 Rule",
            "Prefix": "",
            "Status": "Enabled",
            "Destination": {
                "Bucket": "arn:aws:s3:::<destination-bucket>"
            }
        }
    ]
}```

Here is the blog that describes these behavior in details:
https://aws.amazon.com/blogs/storage/managing-delete-marker-replication-in-amazon-s3/

Body:
I've been surprised to find out that file deletion was not replicated in a S3 bucket Cross Region Replication situation, running this simple test:

simplest configuration of a CRR

upload a new file

check it is replicated

delete the file (not a version of the file)

So I checked the documentation and I find this statement:

If you delete an object from the source bucket, the following occurs:

If you make a DELETE request without specifying an object version ID, Amazon S3 adds a delete marker. Amazon S3 deals with the delete
  marker as follows:

If using latest version of the replication configuration, that is you specify the Filter element in a replication configuration rule,
  Amazon S3 does not replicate the delete marker.

If don't specify the Filter element, Amazon S3 assumes replication configuration is a prior version V1. In the earlier
  version, Amazon S3 handled replication of delete markers differently.
  For more information, see Backward Compatibility .

The later link to backward compat tell me that:

When you delete an object from your source bucket without specifying an object version ID, Amazon S3 adds a delete marker. If you use V1 of the replication configuration XML, Amazon S3 replicates delete markers that resulted from user actions.[...]
  In V2, Amazon S3 doesn't replicate delete markers and therefore you must set the DeleteMarkerReplication element to Disabled.

So if I sum this up:

CRR configuration is considered v1 if there is no Filter

with CRR configuration v1, file deletion is replicated, not with v2

Well, this is my configuration :

{
    "ReplicationConfiguration": {
        "Role": "arn:aws:iam::271226720751:role/service-role/s3crr_role_for_mybucket_to_myreplica",
        "Rules": [
            {
                "ID": "first replication rule",
                "Status": "Enabled",
                "Destination": {
                    "Bucket": "arn:aws:s3:::myreplica"
                }
            }
        ]
    }
}

And deletion is not replicated. So it makes me think that my configuration is still considered V2 (even if I have no filter).

So, can someone confirm this presumption?
And could someone tell me what does:

In V2, Amazon S3 doesn't replicate delete markers and therefore you must set the DeleteMarkerReplication element to Disabled

really mean?

Body:
There are two different configuration when replicating delete marker, V1 and V2.

Currently, when you enable S3 Replication (CRR or SRR) from the console, V2 configuration is enabled by default. However, if your use case requires you to delete replicated objects whenever they are deleted from the source bucket, you need the V1 configuration

Here is the difference between V1 and V2:

V1 configuration

The delete marker is replicated (V1 configuration). A subsequent GET request to the deleted object in both the source and the destination bucket does not return the object.

V2 configuration

The delete marker is not replicated (V2 configuration). A subsequent GET request to the deleted object returns the object only in the destination bucket.

To enable V1 configuration (to replicate delete marker), use the policy below. Keep in mind that certain replication features such as tag-based filtering and Replication Time Control (RTC) that are only available in V2 configurations.

{
    "Role": " IAM-role-ARN ",
    "Rules": [
        {
            "ID": "Replication V1 Rule",
            "Prefix": "",
            "Status": "Enabled",
            "Destination": {
                "Bucket": "arn:aws:s3:::<destination-bucket>"
            }
        }
    ]
}

Here is the blog that describes these behavior in details:
https://aws.amazon.com/blogs/storage/managing-delete-marker-replication-in-amazon-s3/


问:
PyLint W0231 super-init-not-called with __init__ of grandparent
I make a Child class that use methods from Parent class witch not present in GrandParent. But in the Child.__init__() class I don't want to get some effects from Parent.__init__() and instead I call call GrandParent.__init__()

```<code>class GrandParent():
    ...

class Parent(GrandParent):
    def __init__(self):
        GrandParent.__init__(self)
        ...

class Child(Parent):
    def __init__(self):
        GrandParent.__init__(self)
        ...
</code>```

With this code i got next warnings from pylint

```<code> W0233: __init__ method from a non direct base class 'GrandParent' is called (non-parent-init-called)
 W0231: __init__ method from base class 'Parent' is not called (super-init-not-called)
</code>```

What is the correct way to fix this warnings ?

(or disable this warnings for Child is proper solution ?)

```<code>class Child(Parent):
    def __init__(self):  # pylint: disable=W0233
        GrandParent.__init__()   # pylint: disable=W0231
        ...
</code>```

答:
You can try multiple ways such as:

```<code>GrandParent.__init__(self)
super().super().__init__(self)
super(GrandParent, self).__init__()
</code>```

but the error will still be there either as:

super-init-not-called

or bad-super-call (super(GrandParent, self)...)

or even as useless super call to the immediate parent.

I suppose it's meant as a warning for not initializing the immediate class in the class __mro__ by mistake if you work with inheritance and you can to turn off it with a pylint disable:

```<code># pylint: disable=super-init-not-called
</code>```

but you are messing with the __mro__ chain by such calls.

What you can do is allow cascading through the Child.__mro__ items upward i.e. Child -> Parent -> GrandParent (-> object) while skipping by class reference in an __init__:

```<code>class Parent(GrandParent):
    def __init__(self):
        super().__init__()
        if self.__class__ == Child:
            return
</code>```

which does not trigger the PyLint warnings and allows the correct behavior explicitly and without skipping any required items in __mro__.

IMO it's much cleaner preserving the __mro__ which seems what PyLint's intent is as well by super-init-not-called warning. On the other hand, it's kind of tricky and hides the code in a completely different class and that will make the debugging in the future annoying if some properties from Parent will be missing and no comment/disable warning are present in Child class.

If you want to pull the methods out of the GrandParent class only, simply go with the "mixins" classes which is what Django REST Framework is using and don't write any __init__ for those (or if, then don't forget super().__init__() to continue in __mro__ chain!).

```<code>class GrandParent:
    def __init__(self):
        print("> GrandParent __init__()")

class Mixin:
    def mymethod(self):
        print("Hey")

class Parent(Mixin, GrandParent):
    def __init__(self):
        print("> Parent __init__()")
        super().__init__()

class Child(Mixin, GrandParent):
    def __init__(self):
        print("> Child __init__()")
        super().__init__()

Child().mymethod()
# > Child __init__()
# > GrandParent __init__()
# Hey

Parent().mymethod()
# > Parent __init__()
# > GrandParent __init__()
# Hey
</code>```

which will basically be the same situation you have with Child -> Parent -> GrandParent but Mixin itself doesn't have (any useful) __init__ which will cause your code only from GrandParent to execute due to Mixin.__init__() being empty hence doing visually the same thing as with if self.__class__ == Child: return but without any hacks + with increased readability.

Body:
I make a Child class that use methods from Parent class witch not present in GrandParent. But in the Child.__init__() class I don't want to get some effects from Parent.__init__() and instead I call call GrandParent.__init__()

class GrandParent():
    ...

class Parent(GrandParent):
    def __init__(self):
        GrandParent.__init__(self)
        ...

class Child(Parent):
    def __init__(self):
        GrandParent.__init__(self)
        ...

With this code i got next warnings from pylint

 W0233: __init__ method from a non direct base class 'GrandParent' is called (non-parent-init-called)
 W0231: __init__ method from base class 'Parent' is not called (super-init-not-called)

What is the correct way to fix this warnings ?

(or disable this warnings for Child is proper solution ?)

class Child(Parent):
    def __init__(self):  # pylint: disable=W0233
        GrandParent.__init__()   # pylint: disable=W0231
        ...

Body:
You can try multiple ways such as:

GrandParent.__init__(self)
super().super().__init__(self)
super(GrandParent, self).__init__()

but the error will still be there either as:

super-init-not-called

or bad-super-call (super(GrandParent, self)...)

or even as useless super call to the immediate parent.

I suppose it's meant as a warning for not initializing the immediate class in the class __mro__ by mistake if you work with inheritance and you can to turn off it with a pylint disable:

# pylint: disable=super-init-not-called

but you are messing with the __mro__ chain by such calls.

What you can do is allow cascading through the Child.__mro__ items upward i.e. Child -> Parent -> GrandParent (-> object) while skipping by class reference in an __init__:

class Parent(GrandParent):
    def __init__(self):
        super().__init__()
        if self.__class__ == Child:
            return

which does not trigger the PyLint warnings and allows the correct behavior explicitly and without skipping any required items in __mro__.

IMO it's much cleaner preserving the __mro__ which seems what PyLint's intent is as well by super-init-not-called warning. On the other hand, it's kind of tricky and hides the code in a completely different class and that will make the debugging in the future annoying if some properties from Parent will be missing and no comment/disable warning are present in Child class.

If you want to pull the methods out of the GrandParent class only, simply go with the "mixins" classes which is what Django REST Framework is using and don't write any __init__ for those (or if, then don't forget super().__init__() to continue in __mro__ chain!).

class GrandParent:
    def __init__(self):
        print("> GrandParent __init__()")

class Mixin:
    def mymethod(self):
        print("Hey")

class Parent(Mixin, GrandParent):
    def __init__(self):
        print("> Parent __init__()")
        super().__init__()

class Child(Mixin, GrandParent):
    def __init__(self):
        print("> Child __init__()")
        super().__init__()

Child().mymethod()
# > Child __init__()
# > GrandParent __init__()
# Hey

Parent().mymethod()
# > Parent __init__()
# > GrandParent __init__()
# Hey

which will basically be the same situation you have with Child -> Parent -> GrandParent but Mixin itself doesn't have (any useful) __init__ which will cause your code only from GrandParent to execute due to Mixin.__init__() being empty hence doing visually the same thing as with if self.__class__ == Child: return but without any hacks + with increased readability.


问:
Does anyone know the algorithm used for navigating a Pac-Man maze?
I need an algorithm for this pacman maze. Can anyone help?</p>

答:
That's quite a large question.

Anyway, I've yet written a Pac-Man game in both Java and C and I implemented the maze as a matrix filled as follows:
- "-1" if there's a wall;
- "1" if there's a candy;
- else, "0".
To navigate through the maze, you have to use key events. When you'd like to turn left or right, you test if there's a wall ("-1").

I don't know if this answered your question, but feel free to precise if it's not the case.

ContentLicense: CC BY-SA 3.0


问:
Intellij azure-webapp plugin: Encoutering error when deploying to azure: 'No available subscription found in current account.'
I have a valid Azure free trial subscription and I want to deploy a local spring boot app to azure.

I have configured the azure-webapp-maven-plugin in my pom.xml. I am using Intellij.

When i execute mvn azure-webapp:deploy, i get the following error:

Failed to execute goal com.microsoft.azure:azure-webapp-maven-plugin:1.9.1:deploy (default-cli) on project movie-catalog-service: Encoutering error when deploying to azure: 'No available subscription found in current account.'

Edit 1: I installed azure CLI and from my command line it is able to find the subsciption. I followed this url:
https://learn.microsoft.com/en-us/cli/azure/install-azure-cli-macos?view=azure-cli-latest

But still cannot find the same from Intellij.

I tried azure-webapp deploy with Azure CLI. Still same

答:
I had the same issue. And the issue is now opened here.

If Azure CLI is installed and sub is detected correctly.
You can try to use Azure CLI Auth insstead of Maven plug-in.
You can do that by adding config in your azure-webapp-maven-plugin configuration in pom.

```<code><authType>azure_cli</authType>
</code>```

It would be like this:

```<code><plugin>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>azure-webapp-maven-plugin</artifactId>
    <version>1.9.1</version>
    <configuration>
      <schemaVersion>V2</schemaVersion>
      <authType>azure_cli</authType>
      <resourceGroup>someg-group</resourceGroup>
      <appName>some-app-name</appName>
      <pricingTier>P1v2</pricingTier>
      <region>westeurope</region>
      ....
</plugin>
</code>```

Body:
I had the same issue. And the issue is now opened here.

If Azure CLI is installed and sub is detected correctly.
You can try to use Azure CLI Auth insstead of Maven plug-in.
You can do that by adding config in your azure-webapp-maven-plugin configuration in pom.

<authType>azure_cli</authType>

It would be like this:

<plugin>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>azure-webapp-maven-plugin</artifactId>
    <version>1.9.1</version>
    <configuration>
      <schemaVersion>V2</schemaVersion>
      <authType>azure_cli</authType>
      <resourceGroup>someg-group</resourceGroup>
      <appName>some-app-name</appName>
      <pricingTier>P1v2</pricingTier>
      <region>westeurope</region>
      ....
</plugin>


问:
Is there an elegant way to pass multiple functions with different amount of parameters into another function in python?
This block of code looks insanely similar and I'm looking for a way to create one function from the both of them:

```<code>guardians = ["guardianPogchamp", "guardianKappa", "guardianKappaPride", "guardianSmorc", "guardianTrihard"]

with pocofixtures.poco.freeze() as frozen_poco:
    for guardian in guardians:
        if guardian == 'guardianLul':
            assert_text_equal(frozen_poco(guardian).offspring("countdown"),"Immune")
        else:
            assert_text_match(frozen_poco(guardian).offspring("countdown"),"Not Immune")

with pocofixtures.poco.freeze() as frozen_poco:
    for guardian in guardians:
        if guardian == 'guardianLul':
            assert_visible(frozen_poco(guardian).offspring("PetContainer"))
        else:
            assert_not_visible(frozen_poco(guardian).offspring("PetContainer"))
</code>```

This is one of the solutions I tried:

```<code>def custom_assert(func1, func1Args, func2, func2Args):
    guardians = ["guardianPogchamp", "guardianKappa", "guardianKappaPride", "guardianSmorc", "guardianTrihard"]

    with pocofixtures.poco.freeze() as frozen_poco:
        for guardian in guardians:
            if guardian == 'guardianLul':
                func1(*func1Args)
            else:
                func2(*func2Args)

custom_assert(assert_text_equal, (frozen_poco(guardian).offspring("countdown"), "Immune") , assert_text_match, (frozen_poco(guardian).offspring("countdown"),"Not Immune"))
custom_assert(assert_visible, frozen_poco(guardian).offspring("PetContainer"), assert_not_visible, frozen_poco(guardian).offspring("PetContainer"))
</code>```

But the variables frozen_poco and guardian are only defined inside the function and not when it is called so the code doesn't run. I also tried unpacking and repacking the the variables inside the function but it slows down the runtime a lot. I know there should be an elegant solution to this but i don't know what

答:
It should work like that, although that will mean less flexibility (as the frozen_poco-stuff will always be the first argument, but for your example this is enough).</p>

```<code>def custom_assert(func1, pocoarg1, func1Args, func2, pocoarg2, func2Args):
    guardians = ["guardianPogchamp", "guardianKappa", "guardianKappaPride", "guardianSmorc", "guardianTrihard"]
    with pocofixtures.poco.freeze() as frozen_poco:
        for guardian in guardians:
            if guardian == 'guardianLul':
                func1(frozen_poco(guardian).offspring(pocoarg1), *func1Args)
            else:
                func2(frozen_poco(guardian).offspring(pocoarg2), *func2Args)

custom_assert(assert_text_equal, "countdown", ["Immune"], assert_text_match, "countdown",["Not Immune"])

custom_assert(assert_visible, "PetContainer", [], assert_not_visible, "PetContainer", [])
</code>```

Body:
This block of code looks insanely similar and I'm looking for a way to create one function from the both of them:

guardians = ["guardianPogchamp", "guardianKappa", "guardianKappaPride", "guardianSmorc", "guardianTrihard"]

with pocofixtures.poco.freeze() as frozen_poco:
    for guardian in guardians:
        if guardian == 'guardianLul':
            assert_text_equal(frozen_poco(guardian).offspring("countdown"),"Immune")
        else:
            assert_text_match(frozen_poco(guardian).offspring("countdown"),"Not Immune")

with pocofixtures.poco.freeze() as frozen_poco:
    for guardian in guardians:
        if guardian == 'guardianLul':
            assert_visible(frozen_poco(guardian).offspring("PetContainer"))
        else:
            assert_not_visible(frozen_poco(guardian).offspring("PetContainer"))

This is one of the solutions I tried:

def custom_assert(func1, func1Args, func2, func2Args):
    guardians = ["guardianPogchamp", "guardianKappa", "guardianKappaPride", "guardianSmorc", "guardianTrihard"]

    with pocofixtures.poco.freeze() as frozen_poco:
        for guardian in guardians:
            if guardian == 'guardianLul':
                func1(*func1Args)
            else:
                func2(*func2Args)

custom_assert(assert_text_equal, (frozen_poco(guardian).offspring("countdown"), "Immune") , assert_text_match, (frozen_poco(guardian).offspring("countdown"),"Not Immune"))
custom_assert(assert_visible, frozen_poco(guardian).offspring("PetContainer"), assert_not_visible, frozen_poco(guardian).offspring("PetContainer"))

But the variables frozen_poco and guardian are only defined inside the function and not when it is called so the code doesn't run. I also tried unpacking and repacking the the variables inside the function but it slows down the runtime a lot. I know there should be an elegant solution to this but i don't know what

Body:
It should work like that, although that will mean less flexibility (as the frozen_poco-stuff will always be the first argument, but for your example this is enough).

def custom_assert(func1, pocoarg1, func1Args, func2, pocoarg2, func2Args):
    guardians = ["guardianPogchamp", "guardianKappa", "guardianKappaPride", "guardianSmorc", "guardianTrihard"]
    with pocofixtures.poco.freeze() as frozen_poco:
        for guardian in guardians:
            if guardian == 'guardianLul':
                func1(frozen_poco(guardian).offspring(pocoarg1), *func1Args)
            else:
                func2(frozen_poco(guardian).offspring(pocoarg2), *func2Args)

custom_assert(assert_text_equal, "countdown", ["Immune"], assert_text_match, "countdown",["Not Immune"])

custom_assert(assert_visible, "PetContainer", [], assert_not_visible, "PetContainer", [])


问:
Getting error UnsupportedMediaTypeException when trying to update maven dependency to spring-webflux from spring-boot-starter-webflux
As I am trying to update spring-webflux dependency from spring-boot-starter-webflux in maven. My working code start giving error like"

From :

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>
</code>```

changed to:

```<code><dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webflux</artifactId>
    <version>5.2.6.RELEASE</version>
</dependency>
</code>```

Getting below Error:

```<code>org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'application/json' not supported for bodyType=com.location.of.Object at org.springframework.web.reactive.function.BodyInserters.unsupportedError(BodyInserters.java:391)
</code>```

Note : I am trying Jackson library for POJO and having constructor in that.
What could be issue? How to solve it?

答: It is because of missing Jeckson dependency which I have't included in my project's submodule. I added the dependency in child module and it worked. Thanks all.</p>

Body:
As I am trying to update spring-webflux dependency from spring-boot-starter-webflux in maven. My working code start giving error like"

From :

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>

changed to:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webflux</artifactId>
    <version>5.2.6.RELEASE</version>
</dependency>

Getting below Error:

org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'application/json' not supported for bodyType=com.location.of.Object at org.springframework.web.reactive.function.BodyInserters.unsupportedError(BodyInserters.java:391)

Note : I am trying Jackson library for POJO and having constructor in that.
What could be issue? How to solve it?


问:
Make element blink with color
I am using jQuery 3.4.1.

I want this element to blink the user with its background color. Not be blinking, but just change background color and then change the color back again.

```<code>$code_sample.addClass("background-color-light-green").delay(500).removeClass("background-color-light-green");
</code>```

When I trigger the event, no visible effect is present.

https://jsfiddle.net/Nonverbis/nzx7dvm8/2/

What can I try to fix this?

答:
The problem is .removeClass(), .addClass() are very basic commands, hence do not use queue effects like .hide(), .show(),meaning they can't be chained, Hence we must use set timeout to handle such problems!

```<code>function remove_background_color($code_sample) {
    $code_sample.removeClass("background-color-light-green");
}

function blink_background_color($code_sample) {
    $code_sample.addClass("background-color-light-green");
    setTimeout(function(){
        remove_background_color($code_sample)
    } , 200);
}
blink_background_color($('#code-sample-1'))
</code>```

Title: Make element blink with color

Body:
I am using jQuery 3.4.1.

I want this element to blink the user with its background color. Not be blinking, but just change background color and then change the color back again.

$code_sample.addClass("background-color-light-green").delay(500).removeClass("background-color-light-green");

When I trigger the event, no visible effect is present.

https://jsfiddle.net/Nonverbis/nzx7dvm8/2/

What can I try to fix this?

Body:
The problem is .removeClass(), .addClass() are very basic commands, hence do not use queue effects like .hide(), .show(),meaning they can't be chained, Hence we must use set timeout to handle such problems!

function remove_background_color($code_sample) {
    $code_sample.removeClass("background-color-light-green");
}

function blink_background_color($code_sample) {
    $code_sample.addClass("background-color-light-green");
    setTimeout(function(){
        remove_background_color($code_sample)
    } , 200);
}
blink_background_color($('#code-sample-1'))


问:
TimerTask and Broadcast Receiver onReceive
I have multiple times onReceive triggered with different data for intent during each occurence. I need to combine all the intent data into a list of intents inside a background thread. How can I achieve this?
I tried using timer task, but couldn't achieve the same. Is there any other way? Kindly explain with examples as I don't have much knowledge on background thread
BlockingQueue cannot be used as It will block UI thread for a long time is what I saw in stackoverflow.</p>

答: You could use AsyncTask and do you operations in the doInBackground()-method. Check out Android's AsyncTask documentation. (Was deprecated in Android R, however)</p>


问:
I'm looking for an ember helper function like {{json JSON-flat-definition}} to define an attribute or argument. Where to find and how to use?
Built-In Helper Functions in Ember (over Handlebars) are already defined such as a {{let}}, an {{array}}, an {{hash}}, so for me the base of a {{json}} helper, accepting any json string as parameter to define attributes of the template or arguments of the component. Is there such a helper? How does the json-definition-string looks like, as the built-ins only use blanks to structure the data?

https://guides.emberjs.com/release/components/helper-functions/#toc_the-let-helper
https://guides.emberjs.com/release/components/helper-functions/#toc_the-array-helper
https://guides.emberjs.com/release/components/helper-functions/#toc_the-hash-helper

So expected is something like

```<code><Greeting @people={{json
    firstName='Tom'
    lastName='Dale'

    firstName='Yehuda'
    lastName='Katz'

    firstName='Jen'
    lastName='Weber'
  }} />
</code>```

答:
There is not. You would need to call array and hash yourself. So you can do this:

```<code>@people={{array
  (hash
    firstName='Tom'
    lastName='Dale'
  )
  (hash
    firstName='Yehuda'
    lastName='Katz'
  )
  (hash
    firstName='Jen'
    lastName='Weber'
  )
}}
</code>```

Be careful what you consider "a json string", because you used it for "a recursive data structure composed from arrays and dictionaries" and not actually JSON. Because JSON is a serialization format, or, by its very name "JavaScript Object Notation" a notation. If you have the same data in the same structure but a different format its no longer JSON.

So if you do

```<code>const foo = {
  name: "something"
};
</code>```

this is not a JSON Object! foo will definitly not be an JSON Object, it will just be an Object. You could argue that the part of the source code starting from { to } is a JSON Object but even that is wrong. JSON defines a subset of the valid Javascript Object Notation and

```<code>{
  name: "something"
}
</code>```

is not valid JSON because name is not in double quotes.

So if you would build a json helper it would be used like this:

```<code>  <MyComponent @data={{json "[{ \"firstName\": \"Tom\" }]"}} />
</code>```

thats in no way nice to use and would basically primarily useful if you have a actual JSON value inside a string and want to parse it. This helper would also be very easy to write:

```<code>import { helper } from '@ember/component/helper';

export default helper(function json([json]/*, hash*/) {
  return JSON.parse(json);
});
</code>```

One thing to mention here is that there is an RFC proposed to introduce a leteral syntax to define arrays and hashes into ember.

So maybe someday something like this could become part of ember:

```<code>@people={{[
  (
    firstName='Tom'
    lastName='Dale'
  )
  (
    firstName='Yehuda'
    lastName='Katz'
  )
  (
    firstName='Jen'
    lastName='Weber'
  )
]}}
</code>```

but currently you have to call array/hash at every level as shown above.

Body:
Built-In Helper Functions in Ember (over Handlebars) are already defined such as a {{let}}, an {{array}}, an {{hash}}, so for me the base of a {{json}} helper, accepting any json string as parameter to define attributes of the template or arguments of the component. Is there such a helper? How does the json-definition-string looks like, as the built-ins only use blanks to structure the data?

https://guides.emberjs.com/release/components/helper-functions/#toc_the-let-helper
https://guides.emberjs.com/release/components/helper-functions/#toc_the-array-helper
https://guides.emberjs.com/release/components/helper-functions/#toc_the-hash-helper

So expected is something like

<Greeting @people={{json
    firstName='Tom'
    lastName='Dale'

    firstName='Yehuda'
    lastName='Katz'

    firstName='Jen'
    lastName='Weber'
  }} />

Body:
There is not. You would need to call array and hash yourself. So you can do this:

@people={{array
  (hash
    firstName='Tom'
    lastName='Dale'
  )
  (hash
    firstName='Yehuda'
    lastName='Katz'
  )
  (hash
    firstName='Jen'
    lastName='Weber'
  )
}}

Be careful what you consider "a json string", because you used it for "a recursive data structure composed from arrays and dictionaries" and not actually JSON. Because JSON is a serialization format, or, by its very name "JavaScript Object Notation" a notation. If you have the same data in the same structure but a different format its no longer JSON.

So if you do

const foo = {
  name: "something"
};

this is not a JSON Object! foo will definitly not be an JSON Object, it will just be an Object. You could argue that the part of the source code starting from { to } is a JSON Object but even that is wrong. JSON defines a subset of the valid Javascript Object Notation and

{
  name: "something"
}

is not valid JSON because name is not in double quotes.

So if you would build a json helper it would be used like this:

  <MyComponent @data={{json "[{ \"firstName\": \"Tom\" }]"}} />

thats in no way nice to use and would basically primarily useful if you have a actual JSON value inside a string and want to parse it. This helper would also be very easy to write:

import { helper } from '@ember/component/helper';

export default helper(function json([json]/*, hash*/) {
  return JSON.parse(json);
});

One thing to mention here is that there is an RFC proposed to introduce a leteral syntax to define arrays and hashes into ember.

So maybe someday something like this could become part of ember:

@people={{[
  (
    firstName='Tom'
    lastName='Dale'
  )
  (
    firstName='Yehuda'
    lastName='Katz'
  )
  (
    firstName='Jen'
    lastName='Weber'
  )
]}}

but currently you have to call array/hash at every level as shown above.


问:
How I guarantee a graphviz cluster is ALWAYS on the end?
I looked here in many other questions, but none of them do what I want, some rely on messing with lots of settings totally unrelated to the cluster itself, and hoping it will end where you want.

Basically I want a cluster to be the last one, no matter what, like the "rank=sink" option would do to a node, but to a cluster.

How I do that without resorting to mininum length edges and other ugly hacks?

EDIT: end I mean the end of the graph, the bottommost item on the default direction, or rightmost item in the LR one.

答:
I am unaware of anything as nice as rank=...  However,  This works pretty well:

Embed "everything else" within a (new) cluster.  add peripheries=0 if you like

Create 1 or more invisible edges from nodes near the bottom of the "everything else" cluster to nodes near the top of the "end" cluster

digraph {
  subgraph cluster0{

    peripheries=0

    a->b->c->d->e->f

  }

  subgraph cluster1{

    x1->x2

  }

  f->x1 [style=dashed ]

}


问:
Why does shuffling train and test data in time series produce a high R-Squared score?
I got a question about splitting the data into a training and test set in Time Series tasks.
I know that the data can't be shuffled because it's important to keep the time nature of the data, so we do not create scenarios where we are able to look into the future.
However, when I shuffle the data (for experimenting), I get a ridiculously high R-Squared score.
And yes, the R-squared is evaluated with the test set.

Can someone maybe simply explain why this is the case?

Why does shuffling train and test data in time series produce a high R-Squared score? My guess is that it has something to the with the trend of the time series, but I am not sure. I am just asking out of curiosity, thanks!

答:
It really depends upon your problem. If:

If your model has no memory, and merely a mapping tasks then attached timestamp does not have any significance it is better in fact recommended to shuffle the data for better distribution. If this is the case and you are getting a higher R-squaed value you shoud definitely go for it. (I assume this is the case since R-squared is usually used for these types of tasks).

If your task is pattern dependent and each prediction is affecting next in the sequence. This is where order matters. In this case you should never shuffle the data. Any metric which suggest that is lying. The best you can do is split train and test set based on a timestamp prior to which you have your train set and afterwards test set. Then divide train and test sets into fixed time windows. You can shuffle those windows now only if the window span is large enough for your case.

Hope this helps!


问:
The cleaner approach to write code which parses DTO's
In the current project we have decided to use dto's to transfer data between the server and the client.

Dto's are flat, flattering is not the issue, it can be done without much troubles. But dto unflattering may become much difficult to implement, because user may delete, create and update some parts of the flattened entity graph.

So this is example code for one of the web service methods:

```<code>    [Update, EmpresaHasPermissions("PERMIT_INS_Employee")]
    public void UpdateBackground(EmployeeBackgroundDTO dto)
    {
        using (var context = GetObjectContext())
        {
            var user = EmpresaAuthentication.Current.User;

            Employee employee = context.Employees
                .Include(it => it.Nationality)
                .Include(it => it.EthnicOrigin)
                .Include(it => it.MaritalStatus)
                .Include(it => it.Religion)
                .Include(it => it.CRB)
                .Include(it => it.Passport)
                .Single(it => it.OwnerOrganizationId == user.OrganizationId &&
                              !it.Deleted && it.Id == dto.Id);

            var updater = new EmployeeBackgroundUpdater(context);

            updater.UpdateEntity(employee, dto);

            context.SaveChanges();

            dto.MaritalStatusId = employee.MaritalStatusId;
            dto.EthnicOriginId = employee.EthnicOriginId;
            dto.ReligionId = employee.ReligionId;
        }
    }
</code>```

As you can see there are a lot of stuff mixed here:
 context creation
 data selection
 calling to data updater
 sending id of newly created dto's back to the client

Things starts to be getting worth when you see how EmployeeBackgroundUpdater is implemented:

```<code>public override void UpdateEntity(Employee employee, EmployeeBackgroundDTO dto)
{
    employee.InjectFrom(dto);

    if (!IsPassportNull(dto))
    {
        if (employee.Passport == null)
        {
            employee.Passport = new Passport();
        }

        employee.Passport.IssueDate = dto.PassportIssueDate.Value;
        employee.Passport.ExpiryDate = dto.PassportExpiryDate.Value;
        employee.Passport.PassportNo = dto.PassportPassportNo;
        employee.Passport.IssuingCountryId = dto.PassportIssuingCountryId.Value;
        employee.Passport.OwnerUserId = UserId;
    }
    else
    {
        if (employee.Passport != null)
        {
            DeleteObject(employee.Passport);
            employee.Passport = null;
        }
    }

    if (!IsCRBNull(dto))
    {
        if (employee.CRB == null)
        {
            employee.CRB = new CRB();
        }

        employee.CRB.IssueDate = dto.CRBIssueDate.Value;
        employee.CRB.ExpiryDate = dto.CRBExpiryDate.Value;
        employee.CRB.Registration = dto.CRBRegistration;
        employee.CRB.Notes = dto.CRBNotes;
    }
    else
    {
        if (employee.CRB != null)
        {
            DeleteObject(employee.CRB);
            employee.CRB = null;
        }
    }

    var epmpresaContext = (EmpresaEntities)ObjectContext;

    AddMaritalStatus(employee, dto, epmpresaContext);

    AddReligion(employee, dto, epmpresaContext);

    AddEthnicOrigin(employee, dto, epmpresaContext);

    employee.NationalityId = dto.NationalityId;
}

private void AddMaritalStatus(Employee employee, EmployeeBackgroundDTO dto, EmpresaEntities epmpresaContext)
{
    if (!dto.MaritalStatusId.HasValue && !String.IsNullOrWhiteSpace(dto.MaritalStatusDescription))
    {
        var item = epmpresaContext.MaritalStatuses.FirstOrDefault(
            it => it.Description.ToUpper() == dto.MaritalStatusDescription.ToUpper());

        if (item == null)
        {
            employee.MaritalStatus = new MaritalStatus
            {
                Description = dto.MaritalStatusDescription
            };
        }
        else
        {
            employee.MaritalStatus = item;
        }
    }
    else
    {
        employee.MaritalStatusId = dto.MaritalStatusId;
    }
}
</code>```

The code is same in structure, the only difference is the types of Entity sets and Entity types. And this is scary, because I will have to rewrite same code in a bunch of different places along the projects if we will choose to update validation logic or something similar.

Thank you for reading to this point. And there is a set of questions from me:

1) How to parse flat dto's, which can have child objects, to the valid entity graph?

2) Should dto (or presentation model maybe) contain hierarchy of objects?

3) How to get rid of the repeating code?

答: For parsing entities to DTOs and vice-versa you can check AutoMapper. DTO can be hierarchy of objects(it doesn't have to be flatten). I'm afraid that you will never avoid some repeating code because each entity type is somehow special and you have to deal with it manually - that is the complexity included in using DTOs.</p>

Body:
In the current project we have decided to use dto's to transfer data between the server and the client.

Dto's are flat, flattering is not the issue, it can be done without much troubles. But dto unflattering may become much difficult to implement, because user may delete, create and update some parts of the flattened entity graph.

So this is example code for one of the web service methods:

    [Update, EmpresaHasPermissions("PERMIT_INS_Employee")]
    public void UpdateBackground(EmployeeBackgroundDTO dto)
    {
        using (var context = GetObjectContext())
        {
            var user = EmpresaAuthentication.Current.User;

            Employee employee = context.Employees
                .Include(it => it.Nationality)
                .Include(it => it.EthnicOrigin)
                .Include(it => it.MaritalStatus)
                .Include(it => it.Religion)
                .Include(it => it.CRB)
                .Include(it => it.Passport)
                .Single(it => it.OwnerOrganizationId == user.OrganizationId &&
                              !it.Deleted && it.Id == dto.Id);

            var updater = new EmployeeBackgroundUpdater(context);

            updater.UpdateEntity(employee, dto);

            context.SaveChanges();

            dto.MaritalStatusId = employee.MaritalStatusId;
            dto.EthnicOriginId = employee.EthnicOriginId;
            dto.ReligionId = employee.ReligionId;
        }
    }

As you can see there are a lot of stuff mixed here:
 context creation
 data selection
 calling to data updater
 sending id of newly created dto's back to the client

Things starts to be getting worth when you see how EmployeeBackgroundUpdater is implemented:

public override void UpdateEntity(Employee employee, EmployeeBackgroundDTO dto)
{
    employee.InjectFrom(dto);

    if (!IsPassportNull(dto))
    {
        if (employee.Passport == null)
        {
            employee.Passport = new Passport();
        }

        employee.Passport.IssueDate = dto.PassportIssueDate.Value;
        employee.Passport.ExpiryDate = dto.PassportExpiryDate.Value;
        employee.Passport.PassportNo = dto.PassportPassportNo;
        employee.Passport.IssuingCountryId = dto.PassportIssuingCountryId.Value;
        employee.Passport.OwnerUserId = UserId;
    }
    else
    {
        if (employee.Passport != null)
        {
            DeleteObject(employee.Passport);
            employee.Passport = null;
        }
    }

    if (!IsCRBNull(dto))
    {
        if (employee.CRB == null)
        {
            employee.CRB = new CRB();
        }

        employee.CRB.IssueDate = dto.CRBIssueDate.Value;
        employee.CRB.ExpiryDate = dto.CRBExpiryDate.Value;
        employee.CRB.Registration = dto.CRBRegistration;
        employee.CRB.Notes = dto.CRBNotes;
    }
    else
    {
        if (employee.CRB != null)
        {
            DeleteObject(employee.CRB);
            employee.CRB = null;
        }
    }

    var epmpresaContext = (EmpresaEntities)ObjectContext;

    AddMaritalStatus(employee, dto, epmpresaContext);

    AddReligion(employee, dto, epmpresaContext);

    AddEthnicOrigin(employee, dto, epmpresaContext);

    employee.NationalityId = dto.NationalityId;
}

private void AddMaritalStatus(Employee employee, EmployeeBackgroundDTO dto, EmpresaEntities epmpresaContext)
{
    if (!dto.MaritalStatusId.HasValue && !String.IsNullOrWhiteSpace(dto.MaritalStatusDescription))
    {
        var item = epmpresaContext.MaritalStatuses.FirstOrDefault(
            it => it.Description.ToUpper() == dto.MaritalStatusDescription.ToUpper());

        if (item == null)
        {
            employee.MaritalStatus = new MaritalStatus
            {
                Description = dto.MaritalStatusDescription
            };
        }
        else
        {
            employee.MaritalStatus = item;
        }
    }
    else
    {
        employee.MaritalStatusId = dto.MaritalStatusId;
    }
}

The code is same in structure, the only difference is the types of Entity sets and Entity types. And this is scary, because I will have to rewrite same code in a bunch of different places along the projects if we will choose to update validation logic or something similar.

Thank you for reading to this point. And there is a set of questions from me:

1) How to parse flat dto's, which can have child objects, to the valid entity graph?

2) Should dto (or presentation model maybe) contain hierarchy of objects?

3) How to get rid of the repeating code?


问:
find how many elements from the beginning of the array must be added to get a total of more than 10
I have an array with numbers. Need to find how many elements from the beginning of the array must be added to get a total of more than 10. In the code I have to use reduce

    let arr = [2, 3, 1, 0, 4, 5, 4];

The console in this case must display the number 6.

My code didn't work:

```<code>let arr = [2, 3, 1, 0, 4, 5, 4];
let sumNumber = arr.reduce((sum, elem, index) => {

    let ourSum = 0;
    while (ourSum <= 10) {
        return sum + elem;
    }
    index++

}, 0)
console.log(sumNumber);
</code>```

答:
```<code>let arr = [2, 3, 1, 0, 4, 5, 4];
// i is to store the element count at which it gets greater than 10
let i=0;
let sumNumber = arr.reduce((sum, elem, index) => {
    // Checks if sum is greater than 10 yet?
    if(sum>=10){
        // this condn below will only evaluate once when for the
        // first time the sum is greater than or equal to 10
        if(i===0) i=index+1;
    }
    // updates the sum for every loop run
    return sum+elem;
});
console.log("Element count for which sum is greater than equal to 10 is:",i);
</code>```

Body:
I have an array with numbers. Need to find how many elements from the beginning of the array must be added to get a total of more than 10. In the code I have to use reduce

    let arr = [2, 3, 1, 0, 4, 5, 4];

The console in this case must display the number 6.

My code didn't work:

let arr = [2, 3, 1, 0, 4, 5, 4];
let sumNumber = arr.reduce((sum, elem, index) => {

    let ourSum = 0;
    while (ourSum <= 10) {
        return sum + elem;
    }
    index++

}, 0)
console.log(sumNumber);


问:
Is incrementing a _Bool defined?
A _Bool is defined by the C standard to be an unsigned type containing either 0 or 1. If a value of 1 of type _Bool is incremented, there are, as far as I can see, two options:

The value wraps around from 1 to 0

The value is incremented to 2, which is nonzero, and hence is changed into 1 when converted back to a _Bool

On GCC and Clang on my system, the behaviour seems to be the latter. Is this well-defined by the standard?

答:
From the C Standard (6.3.1.2 Boolean type)

1 When any scalar value is converted to _Bool, the result is 0 if the
  value compares equal to 0; otherwise, the result is 1.

And for example 6.5.3.1 Prefix increment and decrement operators

2 The value of the operand of the prefix ++ operator is incremented.
  The result is the new value of the operand after incrementation. The
  expression ++E is equivalent to (E+=1).

And at last 6.5.16.2 Compound assignment

3 A compound assignment of the form E1 op = E2 is equivalent to the
  simple assignment expression E1 = E1 op (E2), except that the lvalue
  E1 is evaluated only once, and with respect to an
  indeterminately-sequenced function call, the operation of a compound
  assignment is a single evaluation. If E1 has an atomic  type, compound
  assignment is a read-modify-write operation with memory_order_seq_cst
  memory order semantics.

Pay attention to that (6.3 Conversions)

— The rank of _Bool shall be less than the rank of all other standard
  integer types.

So used in expressions the type _Bool is converted to other types with a greater rank.

Title: Is incrementing a _Bool defined?


问:
InlineShapes.AddOLEObject without opening the MSWord UI
I am trying to use VBA to add an embedded OLE (Empty MSWord document, Icon:=True) from an open MSWord document without opening the User Interface for the newly created Empty MSWord document).  The following VBA replaces the second paragraph in the current document with the MSWord OLE Icon, But it opens the MSWord Icon document in its own window.

Sub InsertOLEobject()
    ActiveDocument.InlineShapes.AddOLEObject _
    ClassType:="Word.Document", DisplayAsIcon:=True, _
    Range:=ActiveDocument.Paragraphs(2).Range 'Replaces the second paragraph with the MSWord Icon
End Sub
```

<p>Can anyone give me some advice?</p>

<p>The following is the latest VBA code to do what I wanted to do.  The InlineShapes.AddOLEObject will not open the Word User Interface if you use an existing file. I was just hoping for a more elegant way without creating a file that needs to be deleted.</p>

<pre class="lang-vb prettyprint-override"><code>Sub InsertOLEobject()
    Dim docNewBlank As Document
    Set docNewBlank = Documents.Add
    Set DocA = ActiveDocument
    With docNewBlank
        'Centering the paragraph within the blank document
        .Paragraphs(1).Alignment = wdAlignParagraphCenter
        'Saved the file to a temporary scratch location
        .SaveAs FileName:="c:\temp\Blank.doc"
        .Close 'Close the word document
    End With

    'Add the embedded MSWord OLE Icon
    ActiveDocument.InlineShapes.AddOLEObject _
        ClassType:="Word.Document", _
        FileName:="c:\Temp\Blank.doc", _
        DisplayAsIcon:=True, _
        IconLabel:="Blank.doc", _
        IconFileName:="WINWORD.EXE", _
        Range:=ActiveDocument.Paragraphs(2).Range
        'Set the filename of your choice
        'Set the Range to the destination of the ole icon
        'Set the icon to the path of your WINWORD.EXE
End Sub
</code>```

答:
The ultimate solution was to add "ActiveWindow.Close" after inserting the Word OLE Icon with a blank name; this closes the window just opened by the "ActiveDocument.InlineShapes.AddOLEObject".  So I did not have to create a blank.doc first; so I deleted that VBA code.

I was asked what my goal was going into this project; my goal was to cut Tables and Images within a document and paste them in place into Word OLE objects icons.  The resulting word file with all images and tables encapsulated into Word OLE object icons that can be used as an input to the Rational DOORS (DOORS) export Addin. I could have exported the images and tables in DOORS directly so they are viewable within DOORS but if you have ever double clicked on an image or table in DOORS you would find out that the OLE object opens within the cell and is very hard to edit, resize, or position.  I separated the table function from the inlineshapes sub; my VBA code is as follows:

'================================================================================
' Cut all Tables and paste them into Word OLE Icons
'================================================================================
Sub IconizeInlineTables()
'================================================================================
Dim iTable As Table
Dim RngA As Range
Dim RngB As Range
Dim RngC As Range
Dim DocA As Document
Dim DocC As Document
Set DocA = ActiveDocument

For Each iTable In DocA.Tables
    Set RngA = iTable.Range 'Go to the start of the table
    RngA.Expand Unit:=wdTable
    Set RngB = RngA.Duplicate 'Duplicate the range to keep track of table location
    RngB.Collapse Direction:=wdCollapseEnd 'Collapse the Duplicate range to the point after the Table
    RngA.Select

    'MsgBox "Tables Left to Process =" & DocA.Tables.Count

    Selection.Cut 'Cut the Table and put it in the paste buffer

    'Insert the MSWord.doc OLE icon

    ActiveDocument.InlineShapes.AddOLEObject _
        ClassType:="Word.Document", _
        FileName:="", _
        LinkToFile:=False, _
        DisplayAsIcon:=True, _
        IconFileName:="WINWORD.EXE", _
        IconLabel:="Table-" & iTableCount & ".doc", _
        Range:=RngB
    ActiveWindow.Close

    'Expand the range to include the OLE icon then select the new range

    With RngB
        .Expand Unit:=wdParagraph
        .Paragraphs(1).Style = wdStyleBodyText 'Apply the Body Text style
        .Paragraphs(1).Format.Alignment = wdAlignParagraphCenter 'Center the paragraph
        .InlineShapes(1).Select 'Select the inlineshape containing the OLE
    End With

    'Make sure that the InlineShape is the OLE icon

    If InStr(1, RngB.InlineShapes(1).OLEFormat.ProgID, "Word.Document.", vbTextCompare) Then
        Set DocC = RngB.InlineShapes(1).OLEFormat.Object 'Select the OLE Object
        Set RngC = DocC.Paragraphs(1).Range 'Select the first Paragraph within the OLE Object
        With RngC
            .Paragraphs(1).Style = wdStyleBodyText 'Apply the Body Text style
            .Paragraphs(1).Format.Alignment = wdAlignParagraphCenter 'Center the paragraph
            .Collapse Direction:=wdCollapseEnd 'Collapse to just beyond end of paragraph
            .MoveEnd Unit:=wdCharacter, Count:=-1 'Back the RngC up one character to not include the paragraph marker
            .Select
            .Paste 'Paste the Table cut with RngA.cut here
        End With
    Else 'Something I did not expect happened
        MsgBox "Error: " & Selection.InlineShapes(1).OLEFormat.ProgID & "Not Expected"
    End If
Next
End Sub

'================================================================================
' Cut all Figures and paste them into Word OLE Icons
'================================================================================
Sub IconizeInlineShapes()
'================================================================================
Dim iShape As InlineShape
Dim RngA As Range
Dim RngB As Range
Dim RngC As Range
Dim DocA As Document
Dim DocC As Document
Set DocA = ActiveDocument

Selection.GoTo What:=wdGoToSection, Which:=wdGoToFirst 'Start at the beginning of the document

For Each iShape In DocA.InlineShapes
    If iShape.Type = wdInlineShapePicture Then
        Set RngA = iShape.Range 'Set the range to the image
        Set RngB = RngA.Duplicate 'Duplicate the range to keep track of location
        RngB.Collapse Direction:=wdCollapseEnd 'Collapses to the end of the selection
        RngA.Select
        Selection.Cut 'Cut the image and put it in the paste buffer
       'Insert the MSWord OLE icon
        ActiveDocument.InlineShapes.AddOLEObject _
            ClassType:="Word.Document", _
            FileName:="", _
            LinkToFile:=False, _
            DisplayAsIcon:=True, _
            IconFileName:="WINWORD.EXE", _
            IconLabel:="Figure-" & DocA.InlineShapes.Count & ".doc", _
            Range:=RngB
        ActiveWindow.Close

        'The inserted OLE is the next InlineShape to be found so you don't have to select it just loop around to next iShape

    ElseIf InStr(1, iShape.OLEFormat.ProgID, "Word.Document.", vbTextCompare) Then 'Make sure iShape OLE object was next
        Set DocC = iShape.OLEFormat.Object 'Select the OLE object
        Set RngC = DocC.Paragraphs(1).Range 'Select the first Paragraph within the OLE Object
        RngC.Paragraphs(1).Style = wdStyleBodyText 'Apply the Body Text style
        RngC.Paragraphs(1).Format.Alignment = wdAlignParagraphCenter 'Center the paragraph
        RngC.Collapse Direction:=wdCollapseEnd 'Collapse to just beyond end of paragraph
        RngC.MoveEnd Unit:=wdCharacter, Count:=-1 'Back the RngC up one character to not include the paragraph marker
        RngC.Select
        RngC.Paste 'Paste the image cut with RngA.cut here
    Else 'Something I did not expect happened
        MsgBox "Warning: " & iShape.OLEFormat.ProgID & "Not handled by this software"
    End If
Next
End Sub

```

Note the "IconFileName:="WINWORD.EXE" is generic but may have to be modified for your particular installation.

Body:
I am trying to use VBA to add an embedded OLE (Empty MSWord document, Icon:=True) from an open MSWord document without opening the User Interface for the newly created Empty MSWord document).  The following VBA replaces the second paragraph in the current document with the MSWord OLE Icon, But it opens the MSWord Icon document in its own window.

Sub InsertOLEobject()
    ActiveDocument.InlineShapes.AddOLEObject _
    ClassType:="Word.Document", DisplayAsIcon:=True, _
    Range:=ActiveDocument.Paragraphs(2).Range 'Replaces the second paragraph with the MSWord Icon
End Sub

Can anyone give me some advice?

The following is the latest VBA code to do what I wanted to do.  The InlineShapes.AddOLEObject will not open the Word User Interface if you use an existing file. I was just hoping for a more elegant way without creating a file that needs to be deleted.

Sub InsertOLEobject()
    Dim docNewBlank As Document
    Set docNewBlank = Documents.Add
    Set DocA = ActiveDocument
    With docNewBlank
        'Centering the paragraph within the blank document
        .Paragraphs(1).Alignment = wdAlignParagraphCenter
        'Saved the file to a temporary scratch location
        .SaveAs FileName:="c:\temp\Blank.doc"
        .Close 'Close the word document
    End With

    'Add the embedded MSWord OLE Icon
    ActiveDocument.InlineShapes.AddOLEObject _
        ClassType:="Word.Document", _
        FileName:="c:\Temp\Blank.doc", _
        DisplayAsIcon:=True, _
        IconLabel:="Blank.doc", _
        IconFileName:="WINWORD.EXE", _
        Range:=ActiveDocument.Paragraphs(2).Range
        'Set the filename of your choice
        'Set the Range to the destination of the ole icon
        'Set the icon to the path of your WINWORD.EXE
End Sub

Body:
The ultimate solution was to add "ActiveWindow.Close" after inserting the Word OLE Icon with a blank name; this closes the window just opened by the "ActiveDocument.InlineShapes.AddOLEObject".  So I did not have to create a blank.doc first; so I deleted that VBA code.

I was asked what my goal was going into this project; my goal was to cut Tables and Images within a document and paste them in place into Word OLE objects icons.  The resulting word file with all images and tables encapsulated into Word OLE object icons that can be used as an input to the Rational DOORS (DOORS) export Addin. I could have exported the images and tables in DOORS directly so they are viewable within DOORS but if you have ever double clicked on an image or table in DOORS you would find out that the OLE object opens within the cell and is very hard to edit, resize, or position.  I separated the table function from the inlineshapes sub; my VBA code is as follows:

'================================================================================
' Cut all Tables and paste them into Word OLE Icons
'================================================================================
Sub IconizeInlineTables()
'================================================================================
Dim iTable As Table
Dim RngA As Range
Dim RngB As Range
Dim RngC As Range
Dim DocA As Document
Dim DocC As Document
Set DocA = ActiveDocument

For Each iTable In DocA.Tables
    Set RngA = iTable.Range 'Go to the start of the table
    RngA.Expand Unit:=wdTable
    Set RngB = RngA.Duplicate 'Duplicate the range to keep track of table location
    RngB.Collapse Direction:=wdCollapseEnd 'Collapse the Duplicate range to the point after the Table
    RngA.Select

    'MsgBox "Tables Left to Process =" & DocA.Tables.Count

    Selection.Cut 'Cut the Table and put it in the paste buffer

    'Insert the MSWord.doc OLE icon

    ActiveDocument.InlineShapes.AddOLEObject _
        ClassType:="Word.Document", _
        FileName:="", _
        LinkToFile:=False, _
        DisplayAsIcon:=True, _
        IconFileName:="WINWORD.EXE", _
        IconLabel:="Table-" & iTableCount & ".doc", _
        Range:=RngB
    ActiveWindow.Close

    'Expand the range to include the OLE icon then select the new range

    With RngB
        .Expand Unit:=wdParagraph
        .Paragraphs(1).Style = wdStyleBodyText 'Apply the Body Text style
        .Paragraphs(1).Format.Alignment = wdAlignParagraphCenter 'Center the paragraph
        .InlineShapes(1).Select 'Select the inlineshape containing the OLE
    End With

    'Make sure that the InlineShape is the OLE icon

    If InStr(1, RngB.InlineShapes(1).OLEFormat.ProgID, "Word.Document.", vbTextCompare) Then
        Set DocC = RngB.InlineShapes(1).OLEFormat.Object 'Select the OLE Object
        Set RngC = DocC.Paragraphs(1).Range 'Select the first Paragraph within the OLE Object
        With RngC
            .Paragraphs(1).Style = wdStyleBodyText 'Apply the Body Text style
            .Paragraphs(1).Format.Alignment = wdAlignParagraphCenter 'Center the paragraph
            .Collapse Direction:=wdCollapseEnd 'Collapse to just beyond end of paragraph
            .MoveEnd Unit:=wdCharacter, Count:=-1 'Back the RngC up one character to not include the paragraph marker
            .Select
            .Paste 'Paste the Table cut with RngA.cut here
        End With
    Else 'Something I did not expect happened
        MsgBox "Error: " & Selection.InlineShapes(1).OLEFormat.ProgID & "Not Expected"
    End If
Next
End Sub

'================================================================================
' Cut all Figures and paste them into Word OLE Icons
'================================================================================
Sub IconizeInlineShapes()
'================================================================================
Dim iShape As InlineShape
Dim RngA As Range
Dim RngB As Range
Dim RngC As Range
Dim DocA As Document
Dim DocC As Document
Set DocA = ActiveDocument

Selection.GoTo What:=wdGoToSection, Which:=wdGoToFirst 'Start at the beginning of the document

For Each iShape In DocA.InlineShapes
    If iShape.Type = wdInlineShapePicture Then
        Set RngA = iShape.Range 'Set the range to the image
        Set RngB = RngA.Duplicate 'Duplicate the range to keep track of location
        RngB.Collapse Direction:=wdCollapseEnd 'Collapses to the end of the selection
        RngA.Select
        Selection.Cut 'Cut the image and put it in the paste buffer
       'Insert the MSWord OLE icon
        ActiveDocument.InlineShapes.AddOLEObject _
            ClassType:="Word.Document", _
            FileName:="", _
            LinkToFile:=False, _
            DisplayAsIcon:=True, _
            IconFileName:="WINWORD.EXE", _
            IconLabel:="Figure-" & DocA.InlineShapes.Count & ".doc", _
            Range:=RngB
        ActiveWindow.Close

        'The inserted OLE is the next InlineShape to be found so you don't have to select it just loop around to next iShape

    ElseIf InStr(1, iShape.OLEFormat.ProgID, "Word.Document.", vbTextCompare) Then 'Make sure iShape OLE object was next
        Set DocC = iShape.OLEFormat.Object 'Select the OLE object
        Set RngC = DocC.Paragraphs(1).Range 'Select the first Paragraph within the OLE Object
        RngC.Paragraphs(1).Style = wdStyleBodyText 'Apply the Body Text style
        RngC.Paragraphs(1).Format.Alignment = wdAlignParagraphCenter 'Center the paragraph
        RngC.Collapse Direction:=wdCollapseEnd 'Collapse to just beyond end of paragraph
        RngC.MoveEnd Unit:=wdCharacter, Count:=-1 'Back the RngC up one character to not include the paragraph marker
        RngC.Select
        RngC.Paste 'Paste the image cut with RngA.cut here
    Else 'Something I did not expect happened
        MsgBox "Warning: " & iShape.OLEFormat.ProgID & "Not handled by this software"
    End If
Next
End Sub

Note the "IconFileName:="WINWORD.EXE" is generic but may have to be modified for your particular installation.


问:
Declare variable in lighthouse graphql files
I've created a graphql file like this:

```<code>type Field {
    id: ID!
    name_en: String!
    name_fa: String!
    description: String!
    img_url: String!
    created_at: DateTime!
    updated_at: DateTime!

    subFields: [SubField] @hasMany
}

extend type Query {
    fields(input: ListInput @spread): [Field] @paginate(model: "App\\Models\\CustomerManagement\\BusinessInformation\\Field" defaultCount: 10)
    field(id: ID! @eq): Field @find(model: "App\\Models\\CustomerManagement\\BusinessInformation\\Field")
}

extend type Mutation {
    createField(
        name_en: String! @rules(apply: ["required"])
        name_fa: String
        description: String
        img_url: String
    ): Field @create(model: "App\\Models\\CustomerManagement\\BusinessInformation\\Field")

    updateField(
        id: ID! @rules(apply: ["required", "int"])
        name_en: String @rules(apply: ["required"])
        name_fa: String
        description: String
        img_url: String
    ): Field @update(model: "App\\Models\\CustomerManagement\\BusinessInformation\\Field")

    deleteField(
        id: ID! @rules(apply: ["required", "int"])
    ): Field @delete(model: "App\\Models\\CustomerManagement\\BusinessInformation\\Field")
}
</code>```

Every time I want to refer to Field model, I have to type the whole App\\Models\\CustomerManagement\\BusinessInformation\\Field. I was wondering if I could declare a variable like model_namespace and use it instead of the big model namespace.

答:
EDIT:

https://lighthouse-php.com/4.4/api-reference/directives.html#namespace

You should use the @namespace directive

```<code>extend type Query @namespace(field: "App\\Blog") {
  posts: [Post!]! @field(resolver: "Post@resolveAll")
}
</code>```

You have a couple of options:
You can basically load a default namespace array using namespace configuration:
https://github.com/nuwave/lighthouse/pull/525/files

Or alternatively use a group directive:
https://lighthouse-php.com/3.0/api-reference/directives.html#group

Body:
I've created a graphql file like this:

type Field {
    id: ID!
    name_en: String!
    name_fa: String!
    description: String!
    img_url: String!
    created_at: DateTime!
    updated_at: DateTime!

    subFields: [SubField] @hasMany
}

extend type Query {
    fields(input: ListInput @spread): [Field] @paginate(model: "App\\Models\\CustomerManagement\\BusinessInformation\\Field" defaultCount: 10)
    field(id: ID! @eq): Field @find(model: "App\\Models\\CustomerManagement\\BusinessInformation\\Field")
}

extend type Mutation {
    createField(
        name_en: String! @rules(apply: ["required"])
        name_fa: String
        description: String
        img_url: String
    ): Field @create(model: "App\\Models\\CustomerManagement\\BusinessInformation\\Field")

    updateField(
        id: ID! @rules(apply: ["required", "int"])
        name_en: String @rules(apply: ["required"])
        name_fa: String
        description: String
        img_url: String
    ): Field @update(model: "App\\Models\\CustomerManagement\\BusinessInformation\\Field")

    deleteField(
        id: ID! @rules(apply: ["required", "int"])
    ): Field @delete(model: "App\\Models\\CustomerManagement\\BusinessInformation\\Field")
}

Every time I want to refer to Field model, I have to type the whole App\\Models\\CustomerManagement\\BusinessInformation\\Field. I was wondering if I could declare a variable like model_namespace and use it instead of the big model namespace.

Body:
EDIT:

https://lighthouse-php.com/4.4/api-reference/directives.html#namespace

You should use the @namespace directive

extend type Query @namespace(field: "App\\Blog") {
  posts: [Post!]! @field(resolver: "Post@resolveAll")
}

You have a couple of options:
You can basically load a default namespace array using namespace configuration:
https://github.com/nuwave/lighthouse/pull/525/files

Or alternatively use a group directive:
https://lighthouse-php.com/3.0/api-reference/directives.html#group


问:
How can I deal with Highcharts inline styles to prevent Content-Security-Policy violations?
I have an app that uses Highcharts to display data to users, and it's working well. I'm now applying a Content-Security-Policy header to this app and, again, that's working fine (in Report-Only mode for now).

The issue is that Highcharts uses inline styles, and these are obviously reported as violations of the CSP. I'd therefore like to prevent these violations of the policy, without just allowing inline styles (which reduces the value of having a CSP).

My question is thus: is there a way to inject the nonce into Highcharts so that the violations stop?

The error report is:

[Report Only] Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' https: 'nonce-M/dyQoRv6ZpuH6yj1/q6tA=='". Either the 'unsafe-inline' keyword, a hash ('sha256-7wj/+4oyhC/Un8WKFeS81vcvueSVhV/Hk8Tuw/NlDC8='), or a nonce ('nonce-...') is required to enable inline execution.
H   @   highcharts.js:91

The app is built with Rails 6.0.2 using webpacker and Highcharts 7.2.1.

My config/initializers/content_security_policy.rb file is pretty much the default:

```<code># frozen_string_literal: true

Rails.application.config.content_security_policy do |policy|
  policy.default_src :self, :https
  policy.font_src    :self, :https, :data
  policy.img_src     :self, :https, :data
  policy.object_src  :none
  policy.script_src  :self, :https
  policy.style_src   :self, :https
  # If you are using webpack-dev-server then specify webpack-dev-server host
  policy.connect_src :self, :https, "http://localhost:3035", "ws://localhost:3035" if Rails.env.development? || Rails.env.test?

  # Specify URI for violation reports
  # policy.report_uri "/csp-violation-report-endpoint"
end

# If you are using UJS then enable automatic nonce generation
Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }

Rails.application.config.content_security_policy_report_only = true
</code>```

答:
As noted in the comments to the original question, the answer is enabling styledMode. This stops HighCharts using inline styles and instead uses a stylesheet. This may mean updating the default stylesheets to reflect how you want the charts to look, because the commands used to do this in the default mode will now do nothing (for colours, lines, markers etc.).

API: https://api.highcharts.com/highcharts/chart.styledMode

Body:
I have an app that uses Highcharts to display data to users, and it's working well. I'm now applying a Content-Security-Policy header to this app and, again, that's working fine (in Report-Only mode for now).

The issue is that Highcharts uses inline styles, and these are obviously reported as violations of the CSP. I'd therefore like to prevent these violations of the policy, without just allowing inline styles (which reduces the value of having a CSP).

My question is thus: is there a way to inject the nonce into Highcharts so that the violations stop?

The error report is:

[Report Only] Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' https: 'nonce-M/dyQoRv6ZpuH6yj1/q6tA=='". Either the 'unsafe-inline' keyword, a hash ('sha256-7wj/+4oyhC/Un8WKFeS81vcvueSVhV/Hk8Tuw/NlDC8='), or a nonce ('nonce-...') is required to enable inline execution.
H   @   highcharts.js:91

The app is built with Rails 6.0.2 using webpacker and Highcharts 7.2.1.

My config/initializers/content_security_policy.rb file is pretty much the default:

# frozen_string_literal: true

Rails.application.config.content_security_policy do |policy|
  policy.default_src :self, :https
  policy.font_src    :self, :https, :data
  policy.img_src     :self, :https, :data
  policy.object_src  :none
  policy.script_src  :self, :https
  policy.style_src   :self, :https
  # If you are using webpack-dev-server then specify webpack-dev-server host
  policy.connect_src :self, :https, "http://localhost:3035", "ws://localhost:3035" if Rails.env.development? || Rails.env.test?

  # Specify URI for violation reports
  # policy.report_uri "/csp-violation-report-endpoint"
end

# If you are using UJS then enable automatic nonce generation
Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }

Rails.application.config.content_security_policy_report_only = true


问:
Which standard does VS2005, VS2008 follow?
Do they both follow the C++03 released in 2003?</p>

答:
Yes, VS2005 & VS2008 both follow C++03. They do support some features of C++0x though but they are not fully C++0x compliant, most probably none of the compilers is at the moment since the final specification is to be published yet. GCC povides compliance to C++0x than any other compiler at the moment.

C++0x is not yet released.The final specification is expected to be published sometime in mid-2011.

You should see this.


问:
How can one use multiprocessing to run a run a function faster?
I am calling a function and saving the two outputs to variables but this process is taking time because the outputs are generated by solving an ODE.

Is it possible to use multiple cores to run the function faster so the values are saved sooner? If so, could someone provide a simple example?

Thank you

答:
Simply running the same code on multiple cores will not make it run faster. It really depends on the type of tasks your doing. Here are some questions you need to find answers to before you can decide if the code will benefit from parallel processing:

Are the steps in your computation sequence dependent? In other words, does one part of the code depend on the calculations done in the previous? Or can some of them be calculated in parallel? Look at Amdahl's law to learn about how much speedup to expect based on how much of your code you can parallelize

Does your code involve lots of reading/writing to disk and memory? Or is it just lots of computation? If you are doing significant reads and rights to disk, then creating multiple processes to do other work while your threads wait for disk can result in significant speedups. But again, this depend on your answer to the previous point about sequence dependency

How long does your code currently take to run? And is the overhead of creating multiple processes going to be more than the time it takes to run sequentially? In your question you don't give specific times - if you're talking about speeding up a task that takes a few seconds then the time required to create multiple processes might be significant compared to the time for the total task. But if you're talking about a task that takes minutes, then the overhead won't be as significant

Have you considered whether your code is is data parallel or task parallel? If so, you can decide if you want to parallelize using CPU or GPU. For large mathematical operations, look at Numpy for CPU-based and Cupy for GPU-based operations.


问:
How to assign a new value for class variable from class methods?
```<code>x = int(input("enter x:"))
class hello:
    var = x

h = hello()

print(hello.var)
</code>```

Test run:

```<code>enter x:15
15
</code>```

How to access the static variable from the methods of the class? I'm stuck at this one

答:
If you want hello.var to have a value, then you can assign something to it:

```<code>class hello:
    var = None

h = hello()
x = int(input("enter x:"))
h.var = x
print(hello.var)
</code>```

Body:
x = int(input("enter x:"))
class hello:
    var = x

h = hello()

print(hello.var)

Test run:

enter x:15
15

How to access the static variable from the methods of the class? I'm stuck at this one

Body:
If you want hello.var to have a value, then you can assign something to it:

class hello:
    var = None

h = hello()
x = int(input("enter x:"))
h.var = x
print(hello.var)


问:
Why does using multiple ethernet connections slow down throughput of I/O bound task
So I've got an interesting problem that seems counterintuitive to me. I am building a tool where the biggest bottleneck is the rate at which I can send packets. Currently I can handle over a million requests in less than 30 seconds which is great but I'm trying to squeeze out as much speed as possible. My idea was to attach a second ethernet adapter to the machine and spin up two different net.Dialer's like so

```<code>net.Dialer{
        Timeout:   time.Duration(*timeoutPtr) * time.Second,
        LocalAddr: addr,
}
</code>```

where addr is one of the two ethernet adapters. Then I assign the dialers to a job round robin style like so:

```<code>for i, target :=  range targets {
    dialer = dialers[i%len(dialers)]
    ....
    go someNetworkFunction(dialer)
}
</code>```

What's surprising to me is that when I run it with 2 adapters it executes much much slower, 30 seconds vs 2 minutes! I'm just trying to understand why giving the code two connections to send packets slows down the code instead of speeding it up. It doesn't appear that the modulus operation there should cause a 300% slowdown. Is there something happening at the kernel layer when trying to use both adapters to send at the same time? Any help would be appreciated.

答:
There can be multiple factors in play:

Kernel or benchmark process in general.

If you run a profile of your app, which with mln request in 30seconds, is spending not too much application time, you will probably see that syscall is using more of your time. syscall represents the (out of view) cpu time spend out of view of your application.

If this syscall time increases non-linear compared to the process you are benchmarking, you have a bottleneck outside of your program.

Go routines

go routines are scheduled against CPU cores (on the physical level). While they are easy create, the actual switching between go routines is not overhead free. The implementation of someNetworkFunction can make a difference in the throughput where you can block resources, or just switch too often. You can try to manage this by instructing the go program to use less threads with GOMAXPROCS. By tweaking this value, you can determine for your program and hardware what an optimal value is.

A more in depth explanation of the scheduler can be found at https://rakyll.org/scheduler/

Body:
So I've got an interesting problem that seems counterintuitive to me. I am building a tool where the biggest bottleneck is the rate at which I can send packets. Currently I can handle over a million requests in less than 30 seconds which is great but I'm trying to squeeze out as much speed as possible. My idea was to attach a second ethernet adapter to the machine and spin up two different net.Dialer's like so

net.Dialer{
        Timeout:   time.Duration(*timeoutPtr) * time.Second,
        LocalAddr: addr,
}

where addr is one of the two ethernet adapters. Then I assign the dialers to a job round robin style like so:

for i, target :=  range targets {
    dialer = dialers[i%len(dialers)]
    ....
    go someNetworkFunction(dialer)
}

What's surprising to me is that when I run it with 2 adapters it executes much much slower, 30 seconds vs 2 minutes! I'm just trying to understand why giving the code two connections to send packets slows down the code instead of speeding it up. It doesn't appear that the modulus operation there should cause a 300% slowdown. Is there something happening at the kernel layer when trying to use both adapters to send at the same time? Any help would be appreciated.


问:
SQL Server Management Studio missing
i just installed sql server 2008 r2 and SQL Server Management Studio.
After installation i found that the SQL Server Management Studio has not been installed.

i wanted to install SQL Server Management Studio, but cannot find the installation for this. Any idea how to install it?

答:
Try restarting your computer if you just installed SQL Server and there's no choice in the SQL Server Installation Center to install SQL Server Management Studio.

This choice (see image below) only appeared for me after I installed SQL Server, then restarted my computer:

Title: SQL Server Management Studio missing


问:
Why my ASP.NET / SQL Server web app crashes when resumed after a period of inactivity?
I wrote a simple query of a SQL Server database for my app. Multiple queries one after the other work fine. But if I leave the browser and the app active and do another query after a period of inactivity, the app crashes. It's not only slow; it actually crashes hard with the follwing error code:

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that  configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

What do I have to do in my code to prevent this? Thanks.

答:
If you are using sessions perhaps your session expired and when you revisit that is the error?

Can you please post the error you are recieving.

Also if you are executing the query directly are you properly closing your connection.  Its hard to say much more without better information like the exact error you get and how you define "crashing hard"

If its the MAC error I know what it is now. You are hosting in a shared hosting environment.  You will need to explicitly provide a MAC value in your web.config file.  The problem occurs because the belated request could be directed at a different server and there will be a mismatch between your application.

aspnetresources.com/tools/machineKey