问:
Unicode degree symbol not visible in command prompt?
I'm working on a small program that includes temperature displays. I want to have it display the degree symbol(°) next to the temperature, and the current code does that properly when I run it inside of my IDE(IntelliJ), but as soon as I try to run it from the command line, it isn't visible.

The print statement is written as follows:

```<code>System.out.println("The current temperature is " + currentTemp +"\u00B0");
</code>```

Again, it displays properly in IntelliJ, but when I try to run it from a default command prompt, it doesn't have the degree symbol.

I'm using Java 14.0.1, Windows 10 version 1909. Let me know if any other information would help

答:
You can try this :

```<code>PrintStream out = new PrintStream( System.out, true );
out.println("The current temperature is "+currentTemp  + "\u00B0" + "C" );
</code>```

The ouput :

Body:
I'm working on a small program that includes temperature displays. I want to have it display the degree symbol(°) next to the temperature, and the current code does that properly when I run it inside of my IDE(IntelliJ), but as soon as I try to run it from the command line, it isn't visible.

The print statement is written as follows:

System.out.println("The current temperature is " + currentTemp +"\u00B0");

Again, it displays properly in IntelliJ, but when I try to run it from a default command prompt, it doesn't have the degree symbol.

I'm using Java 14.0.1, Windows 10 version 1909. Let me know if any other information would help

Body:
You can try this :

PrintStream out = new PrintStream( System.out, true );
out.println("The current temperature is "+currentTemp  + "\u00B0" + "C" );

The ouput :


来源: stackexchange

问:
How to convert human readable memory size into bytes?
I'm trying to convert strings that match /(\d)+(\.\d+)?(m|g|t)?b?/i into bytes.

For example, 1KB would return 1024. 1.2mb would return 1258291.

ContentLicense: CC BY-SA 3.0

Body:
One liner solution:

"1.5 MB".replace(/(\d+)+(\.(\d+))?\s?(k|m|g|t)?b?/i, function(value, p1, p2, p3, p4) { return parseFloat(p1 + (p2 || ""))*({ 'K' : 1<<10, 'M' : 1<<20, 'G' : 1<<30, 'T' : 1<<40 }[p4] || 1); })

# 1572864

ContentLicense: CC BY-SA 4.0


问:
I Need to Call delete[] on a Dynamic Array within a Class but It Doesn't Work
I wrote code very similar to this (although not identical) for a game I'm making. This has the same issue, so I'll provide it.

```<code>#include <iostream>

using namespace std;

class test {
public:
    int* arr;
    test(int n) {
        arr = new int[n];
        for(int i=0; i<=9; i++) {
            arr[i] = i;
        }
    }
    ~test() {
        delete[] arr;
    }
};

int main() {

    test obj = test(10);
    for(int i=0; i<=8; i++) {
        cout << obj.arr[i] << endl;
    }
    cout << obj.arr[9];
    obj.~test();
    return 0;

}
</code>```

I know that I could rework my code and use the vector class to avoid this problem, but I want to actually understand why it's crashing. Removing the deconstructor call fixes the error, but that also introduces a memory leak, so I would prefer to just fix the deconstructor.

答:
Just adding to the first answer that aptly notes that manual destructor invocation is errorneous here, I will also note that

```<code>class test {
public:
    int* arr;
    test(int n) {
        arr = new int[n];
        /* Redacted fro brevity */
    }
    ~test() {
        delete[] arr;
    }
};
</code>```

has default copy-ctor and assignment operator. Those operators will crash the program and also leak the memory. Special copy-ctor, move-ctor, etc. should be defined in this context to provide proper memory management.

Even better, use std::vector that does that automatically.

Body:
I wrote code very similar to this (although not identical) for a game I'm making. This has the same issue, so I'll provide it.

#include <iostream>

using namespace std;

class test {
public:
    int* arr;
    test(int n) {
        arr = new int[n];
        for(int i=0; i<=9; i++) {
            arr[i] = i;
        }
    }
    ~test() {
        delete[] arr;
    }
};

int main() {

    test obj = test(10);
    for(int i=0; i<=8; i++) {
        cout << obj.arr[i] << endl;
    }
    cout << obj.arr[9];
    obj.~test();
    return 0;

}

I know that I could rework my code and use the vector class to avoid this problem, but I want to actually understand why it's crashing. Removing the deconstructor call fixes the error, but that also introduces a memory leak, so I would prefer to just fix the deconstructor.

Body:
Just adding to the first answer that aptly notes that manual destructor invocation is errorneous here, I will also note that

class test {
public:
    int* arr;
    test(int n) {
        arr = new int[n];
        /* Redacted fro brevity */
    }
    ~test() {
        delete[] arr;
    }
};

has default copy-ctor and assignment operator. Those operators will crash the program and also leak the memory. Special copy-ctor, move-ctor, etc. should be defined in this context to provide proper memory management.

Even better, use std::vector that does that automatically.


问:
How to force VS2019 ignore exceptions inside "try" section
Just installed VS2019 and noticed one uncomfortable thing: in Debug it stops ("falls") at the each exception, even inside try sections. How can I force it to ignore these exceptions, go to catch and work further?

After answer of Perry Qian-MSFT. Now I see this when I have UNHANDLED exception.

Translation: "application is in pause mode". And call stack is empty.

答:
You probably have the debugger set to break on first chance exceptions, which  means it will break when the exception is thrown regardless of any code to catch it. To prevent this behavior, uncheck the respective exception types under Debug / Windows / Exception Settings.

From Manage exceptions with the debugger in Visual Studio:

The debugger can break execution at the point where an exception is thrown, so you may examine the exception before a handler is invoked. [...]

If you select an exception in the Exception Settings window, debugger execution will break wherever the exception is thrown, no matter whether it's handled. Now the exception is called a first chance exception.


问:
Google DataflowRunner "A JNI error has occurred, please check your installation and try again" - Gradle Beam Project
I have  Gradle Apache beam java project that reads events from pubsub and writes to Cloud Firestore. I can run this streaming job using DirectRunner. While executing on DataflowRunner, the worker startup logs shows following error lines :

```<code>Line1 : "A JNI error has occurred, please check your installation and try again"
Line2 : "java.lang.NoClassDefFoundError: org/apache/beam/vendor/guava/v26_0_jre/com/google/common/graph/Network
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
    at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
    at java.lang.Class.getMethod0(Class.java:3018)
    at java.lang.Class.getMethod(Class.java:1784)
    at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
 Caused by: java.lang.ClassNotFoundException: org.apache.beam.vendor.guava.v26_0_jre.com.google.common.graph.Network
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)"

Line 3: "Error syncing pod 8db0cbe852963b21f84ca2ee52e431a4 ("dataflow-streamprocessorapplicatio-06011028-n4lo-harness-sz6k_default(8db0cbe852963b21f84ca2ee52e431a4)"), skipping: failed to "StartContainer" for "java-streaming" with CrashLoopBackOff: "Back-off 5m0s restarting failed container=java-streaming pod=dataflow-streamprocessorapplicatio-06011028-n4lo-harness-sz6k_default(8db0cbe852963b21f84ca2ee52e431a4)"
</code>```

I also tried adding beam-vendors-guava and beam-vendors-grpc dependency. But it didnt help while running on DataflowRunner.

Here is my build.gradle file dependencies section. I am using gradle shade plugin to build uber jar and execute it/create dataflow template and run it:

```<code>dependencies {
    testCompile('org.junit.jupiter:junit-jupiter-api:5.4.0')
    testCompile('org.junit.jupiter:junit-jupiter-params:5.4.0')
    testCompile('org.junit.jupiter:junit-jupiter-engine:5.4.0')
    testCompile(group: 'org.mockito', name: 'mockito-junit-jupiter', version: '3.2.4')
    testCompile(group: 'org.powermock', name: 'powermock-module-junit4', version: '2.0.4')
    testCompile(group: 'org.mockito', name: 'mockito-core', version: '2.28.2') { force true }
    testCompile(group: 'org.powermock', name: 'powermock-api-mockito2', version: '2.0.4')
    testCompile(group: 'org.hamcrest', name: 'hamcrest-all', version: '1.3')

//    compile(group: 'org.apache.beam', name: 'beam-runners-google-cloud-dataflow-java', version: '2.19.0')
//    runtimeClasspath(group: 'org.apache.beam', name: 'beam-runners-google-cloud-dataflow-java', version: '2.19.0')
    runtime(group: 'org.apache.beam', name: 'beam-runners-google-cloud-dataflow-java', version: '2.19.0')

    compile(group: 'org.apache.beam', name: 'beam-sdks-java-io-google-cloud-platform', version: '2.19.0') {
        exclude(group: 'io.grpc', module: 'grpc-all')
    }

    // https://mvnrepository.com/artifact/org.apache.beam/beam-sdks-java-core
    compile group: 'org.apache.beam', name: 'beam-sdks-java-core', version: '2.19.0'

    compile group: 'org.apache.beam', name: 'beam-sdks-java-io-redis', version: '2.19.0'
    compile(group: 'org.apache.beam', name: 'beam-sdks-java-maven-archetypes-starter', version: '2.19.0')
//    runtime(group: 'org.apache.beam', name: 'beam-sdks-java-maven-archetypes-starter', version: '2.19.0')
    compileOnly group: 'org.apache.beam', name: 'beam-runners-direct-java', version: '2.19.0'
    compile(group: 'io.grpc', name: 'grpc-all', version: '1.25.0') {
        force true
    }

    compile group: 'org.projectlombok', name: 'lombok', version: '1.18.10'
    annotationProcessor 'org.projectlombok:lombok:1.18.8'

    compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25'
    compile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.25'

    compile group: 'com.google.cloud', name: 'google-cloud-firestore', version: '1.32.2'
    compile group: 'org.apache.commons', name: 'commons-collections4', version: '4.0'
}
</code>```

Any help/suggestions in this case would be helpful. I am using Apache Beam SDK 2.19.0 for Java.

答:
Since your question says "any help suggestions" I will write my comments also as an answer to "how can I try to debug this"?

Check that org/apache/beam/vendor/guava/v26_0_jre/com/google/common/graph/Network is in the uber jar. If not, it is a shadow plugin configuration issue.

Check that the uber jar is being staged. If not, there may be a problem with the runtime classpath. You can also specify --filesToStage on the command line on setFilesToStage in Java code.

Check that the uber jar has downloaded properly on the worker.

Body:
I have  Gradle Apache beam java project that reads events from pubsub and writes to Cloud Firestore. I can run this streaming job using DirectRunner. While executing on DataflowRunner, the worker startup logs shows following error lines :

Line1 : "A JNI error has occurred, please check your installation and try again"
Line2 : "java.lang.NoClassDefFoundError: org/apache/beam/vendor/guava/v26_0_jre/com/google/common/graph/Network
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
    at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
    at java.lang.Class.getMethod0(Class.java:3018)
    at java.lang.Class.getMethod(Class.java:1784)
    at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
 Caused by: java.lang.ClassNotFoundException: org.apache.beam.vendor.guava.v26_0_jre.com.google.common.graph.Network
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)"

Line 3: "Error syncing pod 8db0cbe852963b21f84ca2ee52e431a4 ("dataflow-streamprocessorapplicatio-06011028-n4lo-harness-sz6k_default(8db0cbe852963b21f84ca2ee52e431a4)"), skipping: failed to "StartContainer" for "java-streaming" with CrashLoopBackOff: "Back-off 5m0s restarting failed container=java-streaming pod=dataflow-streamprocessorapplicatio-06011028-n4lo-harness-sz6k_default(8db0cbe852963b21f84ca2ee52e431a4)"

I also tried adding beam-vendors-guava and beam-vendors-grpc dependency. But it didnt help while running on DataflowRunner.

Here is my build.gradle file dependencies section. I am using gradle shade plugin to build uber jar and execute it/create dataflow template and run it:

dependencies {
    testCompile('org.junit.jupiter:junit-jupiter-api:5.4.0')
    testCompile('org.junit.jupiter:junit-jupiter-params:5.4.0')
    testCompile('org.junit.jupiter:junit-jupiter-engine:5.4.0')
    testCompile(group: 'org.mockito', name: 'mockito-junit-jupiter', version: '3.2.4')
    testCompile(group: 'org.powermock', name: 'powermock-module-junit4', version: '2.0.4')
    testCompile(group: 'org.mockito', name: 'mockito-core', version: '2.28.2') { force true }
    testCompile(group: 'org.powermock', name: 'powermock-api-mockito2', version: '2.0.4')
    testCompile(group: 'org.hamcrest', name: 'hamcrest-all', version: '1.3')

//    compile(group: 'org.apache.beam', name: 'beam-runners-google-cloud-dataflow-java', version: '2.19.0')
//    runtimeClasspath(group: 'org.apache.beam', name: 'beam-runners-google-cloud-dataflow-java', version: '2.19.0')
    runtime(group: 'org.apache.beam', name: 'beam-runners-google-cloud-dataflow-java', version: '2.19.0')

    compile(group: 'org.apache.beam', name: 'beam-sdks-java-io-google-cloud-platform', version: '2.19.0') {
        exclude(group: 'io.grpc', module: 'grpc-all')
    }

    // https://mvnrepository.com/artifact/org.apache.beam/beam-sdks-java-core
    compile group: 'org.apache.beam', name: 'beam-sdks-java-core', version: '2.19.0'

    compile group: 'org.apache.beam', name: 'beam-sdks-java-io-redis', version: '2.19.0'
    compile(group: 'org.apache.beam', name: 'beam-sdks-java-maven-archetypes-starter', version: '2.19.0')
//    runtime(group: 'org.apache.beam', name: 'beam-sdks-java-maven-archetypes-starter', version: '2.19.0')
    compileOnly group: 'org.apache.beam', name: 'beam-runners-direct-java', version: '2.19.0'
    compile(group: 'io.grpc', name: 'grpc-all', version: '1.25.0') {
        force true
    }

    compile group: 'org.projectlombok', name: 'lombok', version: '1.18.10'
    annotationProcessor 'org.projectlombok:lombok:1.18.8'

    compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25'
    compile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.25'

    compile group: 'com.google.cloud', name: 'google-cloud-firestore', version: '1.32.2'
    compile group: 'org.apache.commons', name: 'commons-collections4', version: '4.0'
}

Any help/suggestions in this case would be helpful. I am using Apache Beam SDK 2.19.0 for Java.


问:
Moving HTML to a parent using jQuery in WordPress - CLOSED
I am creating a WordPress webshop using WooCommerce and the Divi theme.

On PC all is great, but on mobile the theme places my custom mobile cart quantity counter inside the mobile menu dropdown. This makes it not visible until you open the mobile menu. (which uses JavaScript to add display:none to the parent when collapsed.)

Now I'm trying to move the cart quantity counter up in the HTML so it stays visible.

Here is the code that I'm using. But for some reason it's not taking effect.

```<code><script type="text/javascript">
    (function() {
        $('#mobile_menu li.cart_menu').appendTo('#main-header');
    })(jQuery);
</script>
</code>```

I just want the code snippet to be fired automatically.

I did some testing, and this code snippet does work, but only fires after the add to cart action has been activated:

```<code><script type="text/javascript">
    (function() {
        $('body').on('added_to_cart',
                     $('#mobile_menu li.cart_menu').appendTo('#main-header');
    });
    })(jQuery);
</script>
</code>```

What am I doing wrong here?

UPDATE:

This script works:

```<code><script type="text/javascript">
    (function($) {
        $(window).on('load', function() {
            $('#mobile_menu li.cart_menu').appendTo('#main-header');
        });
    })(jQuery);
</script>
</code>```

答:
Put your code to the ready function like this example:

```<code>$(document).ready(function() {
    (function() {
        $('#mobile_menu li.cart_menu').appendTo('#main-header');
    })(jQuery);
});
</code>```

Body:
I am creating a WordPress webshop using WooCommerce and the Divi theme.

On PC all is great, but on mobile the theme places my custom mobile cart quantity counter inside the mobile menu dropdown. This makes it not visible until you open the mobile menu. (which uses JavaScript to add display:none to the parent when collapsed.)

Now I'm trying to move the cart quantity counter up in the HTML so it stays visible.

Here is the code that I'm using. But for some reason it's not taking effect.

I just want the code snippet to be fired automatically.

I did some testing, and this code snippet does work, but only fires after the add to cart action has been activated:

What am I doing wrong here?

UPDATE:

This script works:

Body:
Put your code to the ready function like this example:

$(document).ready(function() {
    (function() {
        $('#mobile_menu li.cart_menu').appendTo('#main-header');
    })(jQuery);
});


问:
How do I Mock a method that makes multiple POST and GET request all requiring different response data?
I have looked at How to mock REST API and I have read the answers but I still can't seem to get my head around how I would go about dealing with a method that executes multiple GET and POST requests.  Here is some of my code below.

I have a class, UserAliasGroups(). Its __init__() method executes requests.post() to login into the external REST API.   I have in my unit test this code to handling the mocking of the login and it works as expected.

```<code>    @mock.patch('aliases.user_alias_groups.requests.get')
    @mock.patch('aliases.user_alias_groups.requests.post')
    def test_user_alias_groups_class(self, mock_post, mock_get):
        init_response = {
            'HID-SessionData': 'token==',
            'errmsg': '',
            'success': True
        }
        mock_response = Mock()
        mock_response.json.return_value = init_response
        mock_response.status_code = status.HTTP_201_CREATED
        mock_post.return_value = mock_response

        uag = UserAliasGroups(auth_user='TEST_USER.gen',
                              auth_pass='FakePass',
                              groups_api_url='https://example.com')
        self.assertEqual(uag.headers, {'HID-SessionData': 'token=='})
</code>```

I also have defined several methods like obtain_request_id(), has_group_been_deleted(), does_group_already_exists() and others.  I also define a method called create_user_alias_group() that calls obtain_request_id(), has_group_been_deleted(), does_group_already_exists() and others.

I also have code in my unit test to mock a GET request to the REST API to test my has_group_been_deleted() method that looks like this:

```<code>        has_group_been_deleted_response = {
            'error_code': 404,
            'error_message': 'A group with this ID does not exist'
        }
        mock_response = Mock()
        mock_response.json.return_value = has_group_been_deleted_response
        mock_response.status_code = status.HTTP_404_NOT_FOUND
        mock_get.return_value = mock_response
</code>```

Now I can get to my question.  Below is the pertinent part of my code.

```<code>class UserAliasGroups:

    def __init__(
            self,
            auth_user=settings.GENERIC_USER,
            auth_pass=settings.GENERIC_PASS,
            groups_api_url=settings.GROUPS_API_URL
    ):
        """ __init__() does the login to groups. """
        self.auth_user = auth_user
        self.auth_pass = auth_pass
        self.headers = None
        self.groups_api_url = groups_api_url
        # Initializes a session with the REST API service. Each login session times out after 5 minutes of inactivity.
        self.login_url = f'{self.groups_api_url}/api/login'

        response = requests.post(self.login_url, json={}, headers={'Content-type': 'application/json'},
                                 auth=(auth_user, auth_pass))
        if response.status_code is not 201:
            try:
                json = response.json()
            except:
                json = "Could not decode json."
            raise self.UserAliasGroupsException(f"Error: User {self.auth_user}, failed to login into "
                                                f"{self.login_url} {json}")

        response_json = response.json()
        self.headers = {'HID-SessionData': response_json['HID-SessionData']}

    def obtain_request_id(self, request_reason):
        payload = {'request_reason': request_reason}
        url = f'{self.groups_api_url}/api/v1/session/requests'
        response = requests.post(url=url, json=payload, headers=self.headers)
        if response.status_code is not status.HTTP_200_OK:
            try:
                json = response.json()
            except:
                json = "Could not decode json."
            msg = f'obtain_request_id() Error url={url} {response.status_code} {json}.'
            raise self.UserAliasGroupsException(msg)
        request_id = response.json().get('request_id')
        return request_id

    def has_group_been_deleted(self, group_name):
        url = f'{self.groups_api_url}/api/v1/groups/{group_name}/attributes/RESATTR_GROUP_DELETED_ON'
        response = requests.get(url=url, headers=self.headers)
        return response.status_code == status.HTTP_200_OK

    def does_group_already_exists(self, group_name):
        url = f'{self.groups_api_url}/api/v1/groups/{group_name}'
        response = requests.get(url=url, headers=self.headers)
        if response.status_code is status.HTTP_200_OK:
            # check if the group has been "deleted".
            return not self.has_group_been_deleted(group_name=group_name)
        return False

    def create_user_alias_group(
            self,
            ... long list of params omitted for brevity ...
    ):

       if check_exists:
            # Check if group already exists or not.
            if self.does_group_already_exists(group_name):
                msg = f'Cannot create group {group_name}. Group already exists.'
                raise self.UserAliasGroupsException(msg)
       ... more code omitted for brevity ...
</code>```

My question is how do I write my unit test to deal with multiple calls to requests.post() and request.get() all resulting in different responses in my create_user_alias_group() method?

I want to call create_user_alias_group() in my unit test so I have to figure out how to mock multiple requests.get() and requests.post() calls.

Do I have use multiple decorators like this:

```<code>@mock.patch('aliases.user_alias_groups.obtain_request_id.requests.post')
@mock.patch('aliases.user_alias_groups.does_group_already_exists.requests.get')
@mock.patch('aliases.user_alias_groups.has_group_been_deleted.requests.get')
def test_user_alias_groups_class(self, mock_post, mock_get):
    ...
</code>```

?

Thanks for looking my long question :)

答:
You can use mock.side_effect which takes an iterable. Then different calls will return different values:

```<code>mock = Mock()
mock.side_effect = ['a', 'b', 'c']
</code>```

This way the first call to mock returns "a", then the next one "b" and so on. (In your case, you'll set mock_get.side_effect).

Body:
I have looked at How to mock REST API and I have read the answers but I still can't seem to get my head around how I would go about dealing with a method that executes multiple GET and POST requests.  Here is some of my code below.

I have a class, UserAliasGroups(). Its __init__() method executes requests.post() to login into the external REST API.   I have in my unit test this code to handling the mocking of the login and it works as expected.

    @mock.patch('aliases.user_alias_groups.requests.get')
    @mock.patch('aliases.user_alias_groups.requests.post')
    def test_user_alias_groups_class(self, mock_post, mock_get):
        init_response = {
            'HID-SessionData': 'token==',
            'errmsg': '',
            'success': True
        }
        mock_response = Mock()
        mock_response.json.return_value = init_response
        mock_response.status_code = status.HTTP_201_CREATED
        mock_post.return_value = mock_response

        uag = UserAliasGroups(auth_user='TEST_USER.gen',
                              auth_pass='FakePass',
                              groups_api_url='https://example.com')
        self.assertEqual(uag.headers, {'HID-SessionData': 'token=='})

I also have defined several methods like obtain_request_id(), has_group_been_deleted(), does_group_already_exists() and others.  I also define a method called create_user_alias_group() that calls obtain_request_id(), has_group_been_deleted(), does_group_already_exists() and others.

I also have code in my unit test to mock a GET request to the REST API to test my has_group_been_deleted() method that looks like this:

        has_group_been_deleted_response = {
            'error_code': 404,
            'error_message': 'A group with this ID does not exist'
        }
        mock_response = Mock()
        mock_response.json.return_value = has_group_been_deleted_response
        mock_response.status_code = status.HTTP_404_NOT_FOUND
        mock_get.return_value = mock_response

Now I can get to my question.  Below is the pertinent part of my code.

class UserAliasGroups:

    def __init__(
            self,
            auth_user=settings.GENERIC_USER,
            auth_pass=settings.GENERIC_PASS,
            groups_api_url=settings.GROUPS_API_URL
    ):
        """ __init__() does the login to groups. """
        self.auth_user = auth_user
        self.auth_pass = auth_pass
        self.headers = None
        self.groups_api_url = groups_api_url
        # Initializes a session with the REST API service. Each login session times out after 5 minutes of inactivity.
        self.login_url = f'{self.groups_api_url}/api/login'

        response = requests.post(self.login_url, json={}, headers={'Content-type': 'application/json'},
                                 auth=(auth_user, auth_pass))
        if response.status_code is not 201:
            try:
                json = response.json()
            except:
                json = "Could not decode json."
            raise self.UserAliasGroupsException(f"Error: User {self.auth_user}, failed to login into "
                                                f"{self.login_url} {json}")

        response_json = response.json()
        self.headers = {'HID-SessionData': response_json['HID-SessionData']}

    def obtain_request_id(self, request_reason):
        payload = {'request_reason': request_reason}
        url = f'{self.groups_api_url}/api/v1/session/requests'
        response = requests.post(url=url, json=payload, headers=self.headers)
        if response.status_code is not status.HTTP_200_OK:
            try:
                json = response.json()
            except:
                json = "Could not decode json."
            msg = f'obtain_request_id() Error url={url} {response.status_code} {json}.'
            raise self.UserAliasGroupsException(msg)
        request_id = response.json().get('request_id')
        return request_id

    def has_group_been_deleted(self, group_name):
        url = f'{self.groups_api_url}/api/v1/groups/{group_name}/attributes/RESATTR_GROUP_DELETED_ON'
        response = requests.get(url=url, headers=self.headers)
        return response.status_code == status.HTTP_200_OK

    def does_group_already_exists(self, group_name):
        url = f'{self.groups_api_url}/api/v1/groups/{group_name}'
        response = requests.get(url=url, headers=self.headers)
        if response.status_code is status.HTTP_200_OK:
            # check if the group has been "deleted".
            return not self.has_group_been_deleted(group_name=group_name)
        return False

    def create_user_alias_group(
            self,
            ... long list of params omitted for brevity ...
    ):

       if check_exists:
            # Check if group already exists or not.
            if self.does_group_already_exists(group_name):
                msg = f'Cannot create group {group_name}. Group already exists.'
                raise self.UserAliasGroupsException(msg)
       ... more code omitted for brevity ...

My question is how do I write my unit test to deal with multiple calls to requests.post() and request.get() all resulting in different responses in my create_user_alias_group() method?

I want to call create_user_alias_group() in my unit test so I have to figure out how to mock multiple requests.get() and requests.post() calls.

Do I have use multiple decorators like this:

@mock.patch('aliases.user_alias_groups.obtain_request_id.requests.post')
@mock.patch('aliases.user_alias_groups.does_group_already_exists.requests.get')
@mock.patch('aliases.user_alias_groups.has_group_been_deleted.requests.get')
def test_user_alias_groups_class(self, mock_post, mock_get):
    ...

?

Thanks for looking my long question :)

Body:
You can use mock.side_effect which takes an iterable. Then different calls will return different values:

mock = Mock()
mock.side_effect = ['a', 'b', 'c']

This way the first call to mock returns "a", then the next one "b" and so on. (In your case, you'll set mock_get.side_effect).


问:
Is it okay to use GitHub Secrets with a public repo?
I have a private repo with a GitHub Action that pushes the code to an AWS S3 bucket when there's a new push to the master branch. I need a pair of access keys to be able to push the contents and I'm storing them as GitHub Secrets and referencing them as environment variables in the build script. Now I would like to make this repo public in the near future, and I was wondering if it's a safe thing to do. The workflow (.github/workflows/main.yml) itself for the action is indeed publicly visible and what it does, but it only has the single command aws s3 cp myfile s3://my-bucket and absolutely no access keys in the code itself.

Is it safe to use GitHub Secrets for the Actions in a public repo? I am the sole owner and only contributor, this will not change in the future. I might switch to CodePipeline with a webhook later but wanted to try GitHub Actions first. Thanks.

答:
Yes, it appears so. According to Github, you have organization-level access control policies to who can access your secrets.

For secrets stored at the organization-level, you can use access policies to control which repositories can use organization secrets. Organization-level secrets let you share secrets between multiple repositories, which reduces the need for creating duplicate secrets. Updating an organization secret in one location also ensures that the change takes effect in all repository workflows that use that secret.

Whether the repository is public or private does not affect this, and that makes sense. Public projects need secrets, too.


问:
how to send Ctrl + G to another application?
I'm trying to send CTRL + G keys using InputSimulator with ForegroundWindow but it doesn't work. With other keys it works as expected, for example Ctrl + A or Ctrl + C

hotkeys menu options

I have tried with:

```<code>Process[] p = Process.GetProcessesByName("notepad");
if (p != null && p.Length > 0)
{
    IntPtr h = p[0].MainWindowHandle;
    SetForegroundWindow(h);
    InputSimulator sim = new InputSimulator();
    sim.Keyboard.ModifiedKeyStroke (VirtualKeyCode.CONTROL, VirtualKeyCode.VK_G) .Sleep (300);
 }
</code>```

or

```<code> Process[] p = Process.GetProcessesByName("notepad");
 if (p != null && p.Length > 0)
 {
    IntPtr h = p[0].MainWindowHandle;
    SetForegroundWindow(h);
    InputSimulator sim = new InputSimulator();
    sim.Keyboard.KeyDown(VirtualKeyCode.CONTROL);
    sim.Keyboard.KeyPress(VirtualKeyCode.VK_G).Sleep(300);
    sim.Keyboard.KeyUp(VirtualKeyCode.CONTROL).Sleep(300);
}
</code>```

Also try:

```<code>SendKeys.Send ("^ (g)");
</code>```

I have even tried keybd_event (user32.dll function)

答:
You need to force the other window into focus before sending the keystrokes. The Microsoft docs have examples detailing this process - link

In short, they use FindWindow followed by SetForegroundWindow, then send the keys via SendKeys.SendWait(), though you can optionally use SendKeys.Send()

This answer seems like a concise implementation of the FindWindow + SetForegroundWindow process.

Body:
I'm trying to send CTRL + G keys using InputSimulator with ForegroundWindow but it doesn't work. With other keys it works as expected, for example Ctrl + A or Ctrl + C

hotkeys menu options

I have tried with:

Process[] p = Process.GetProcessesByName("notepad");
if (p != null && p.Length > 0)
{
    IntPtr h = p[0].MainWindowHandle;
    SetForegroundWindow(h);
    InputSimulator sim = new InputSimulator();
    sim.Keyboard.ModifiedKeyStroke (VirtualKeyCode.CONTROL, VirtualKeyCode.VK_G) .Sleep (300);
 }

or

 Process[] p = Process.GetProcessesByName("notepad");
 if (p != null && p.Length > 0)
 {
    IntPtr h = p[0].MainWindowHandle;
    SetForegroundWindow(h);
    InputSimulator sim = new InputSimulator();
    sim.Keyboard.KeyDown(VirtualKeyCode.CONTROL);
    sim.Keyboard.KeyPress(VirtualKeyCode.VK_G).Sleep(300);
    sim.Keyboard.KeyUp(VirtualKeyCode.CONTROL).Sleep(300);
}

Also try:

SendKeys.Send ("^ (g)");

I have even tried keybd_event (user32.dll function)


问:
left join messing the query up
I'm having some troubles with this query, its not returning all rows as it should be:

```<code>SELECT DE.user_id,
       DE.id,
       DE.title,
       DE.limit_new_cards,
       DE.limit_old_cards,
       DE.deleted,
       Count(DISTINCT TCA.id) total_cards,
       Count(DISTINCT NCA.id) new_cards,
       Count(DISTINCT OCA.id) due_cards
FROM   decks AS DE
       LEFT JOIN cards AS TCA
              ON TCA.deck_id = DE.id
       LEFT JOIN cards AS NCA
              ON NCA.deck_id = DE.id
                 AND NCA.is_new = 1
       LEFT JOIN cards AS OCA
              ON OCA.deck_id = DE.id
                 AND OCA.due_date <= CURRENT_DATE()
WHERE  DE.user_id = 47
GROUP  BY TCA.deck_id
ORDER  BY DE.id;
</code>```

Should it return the same number of rows as this query does? or not?

```<code>SELECT user_id,
       id,
       title,
       limit_new_cards,
       limit_old_cards,
       deleted,
FROM   decks
WHERE  user_id = 47
ORDER  BY id;
</code>```

I'd be glad if someone could help me.

答:
I suspect that the problem is your GROUP BY clause:

```<code>GROUP BY TCA.deck_id
</code>```

Should be:

```<code>GROUP BY DE.id
</code>```

Rationale: TCA is a LEFT JOINed table that has the following condition:

```<code>ON TCA.deck_id = DE.id
</code>```

When there is no match in TCA, TCA.deck_id is NULL, which you then GROUP BY. So you end up with all DE.ids that have no match in TCA grouped together. Instead you should use the corresponding column from base table DE - which, presumably, is never NULL.

Title: left join messing the query up

Body:
I'm having some troubles with this query, its not returning all rows as it should be:

SELECT DE.user_id,
       DE.id,
       DE.title,
       DE.limit_new_cards,
       DE.limit_old_cards,
       DE.deleted,
       Count(DISTINCT TCA.id) total_cards,
       Count(DISTINCT NCA.id) new_cards,
       Count(DISTINCT OCA.id) due_cards
FROM   decks AS DE
       LEFT JOIN cards AS TCA
              ON TCA.deck_id = DE.id
       LEFT JOIN cards AS NCA
              ON NCA.deck_id = DE.id
                 AND NCA.is_new = 1
       LEFT JOIN cards AS OCA
              ON OCA.deck_id = DE.id
                 AND OCA.due_date <= CURRENT_DATE()
WHERE  DE.user_id = 47
GROUP  BY TCA.deck_id
ORDER  BY DE.id;

Should it return the same number of rows as this query does? or not?

SELECT user_id,
       id,
       title,
       limit_new_cards,
       limit_old_cards,
       deleted,
FROM   decks
WHERE  user_id = 47
ORDER  BY id;

I'd be glad if someone could help me.

Body:
I suspect that the problem is your GROUP BY clause:

GROUP BY TCA.deck_id

Should be:

GROUP BY DE.id

Rationale: TCA is a LEFT JOINed table that has the following condition:

ON TCA.deck_id = DE.id

When there is no match in TCA, TCA.deck_id is NULL, which you then GROUP BY. So you end up with all DE.ids that have no match in TCA grouped together. Instead you should use the corresponding column from base table DE - which, presumably, is never NULL.


问:
Python Timezone conversion
How do I convert a time to another timezone in Python?</p>

答:
Python 3.9 adds the zoneinfo module so now only the the standard library is needed!

```<code>>>> from zoneinfo import ZoneInfo
>>> from datetime import datetime

>>> d = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo('America/Los_Angeles'))
>>> d.astimezone(ZoneInfo('Europe/Berlin'))  # 12:00 in Cali will be 20:00 in Berlin
datetime.datetime(2020, 10, 31, 20, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))
</code>```

Wikipedia list of available time zones

Some functions such as now() and utcnow() return timezone-unaware datetimes, meaning they contain no timezone information. I recommend only requesting timezone-aware values from them using the keyword tz=ZoneInfo('localtime').

If astimezone gets a timezone-unaware input, it will assume it is local time, which can lead to errors:

```<code>>>> datetime.utcnow()  # UTC -- NOT timezone-aware!!
datetime.datetime(2020, 6, 1, 22, 39, 57, 376479)
>>> datetime.now()     # Local time -- NOT timezone-aware!!
datetime.datetime(2020, 6, 2, 0, 39, 57, 376675)

>>> datetime.now(tz=ZoneInfo('localtime'))  # timezone-aware
datetime.datetime(2020, 6, 2, 0, 39, 57, 376806, tzinfo=zoneinfo.ZoneInfo(key='localtime'))
>>> datetime.now(tz=ZoneInfo('Europe/Berlin'))  # timezone-aware
datetime.datetime(2020, 6, 2, 0, 39, 57, 376937, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))
>>> datetime.utcnow().astimezone(ZoneInfo('Europe/Berlin'))  # WRONG!!
datetime.datetime(2020, 6, 1, 22, 39, 57, 377562, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))
</code>```

Windows has no system time zone database, so here an extra package is needed:

```<code>pip install tzdata
</code>```

There is a backport to allow use in Python 3.6 to 3.8:

```<code>sudo pip install backports.zoneinfo
</code>```

Then:

```<code>from backports.zoneinfo import ZoneInfo
</code>```

Title: Python Timezone conversion

Body:
Python 3.9 adds the zoneinfo module so now only the the standard library is needed!

>>> from zoneinfo import ZoneInfo
>>> from datetime import datetime

>>> d = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo('America/Los_Angeles'))
>>> d.astimezone(ZoneInfo('Europe/Berlin'))  # 12:00 in Cali will be 20:00 in Berlin
datetime.datetime(2020, 10, 31, 20, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))

Wikipedia list of available time zones

Some functions such as now() and utcnow() return timezone-unaware datetimes, meaning they contain no timezone information. I recommend only requesting timezone-aware values from them using the keyword tz=ZoneInfo('localtime').

If astimezone gets a timezone-unaware input, it will assume it is local time, which can lead to errors:

>>> datetime.utcnow()  # UTC -- NOT timezone-aware!!
datetime.datetime(2020, 6, 1, 22, 39, 57, 376479)
>>> datetime.now()     # Local time -- NOT timezone-aware!!
datetime.datetime(2020, 6, 2, 0, 39, 57, 376675)

>>> datetime.now(tz=ZoneInfo('localtime'))  # timezone-aware
datetime.datetime(2020, 6, 2, 0, 39, 57, 376806, tzinfo=zoneinfo.ZoneInfo(key='localtime'))
>>> datetime.now(tz=ZoneInfo('Europe/Berlin'))  # timezone-aware
datetime.datetime(2020, 6, 2, 0, 39, 57, 376937, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))
>>> datetime.utcnow().astimezone(ZoneInfo('Europe/Berlin'))  # WRONG!!
datetime.datetime(2020, 6, 1, 22, 39, 57, 377562, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))

Windows has no system time zone database, so here an extra package is needed:

pip install tzdata

There is a backport to allow use in Python 3.6 to 3.8:

sudo pip install backports.zoneinfo

Then:

from backports.zoneinfo import ZoneInfo


问:
How to store a const char* in std :: string?
```<code>    char       *buffer1 = "abc";

    const char *buffer2 = (const char*) buffer;

    std :: string str (buffer2);
</code>```

This works, but I want to declare the std::string object i.e. str, once and use it many times to store different const char*.

What's the way out?

答:
Make a Class say MyString which compose String buffer.
Have a constant of that class.
and then u can reassign the value of the composed string buffer, while using the same constant.</p>

Body:
    char       *buffer1 = "abc";

    const char *buffer2 = (const char*) buffer;

    std :: string str (buffer2);

This works, but I want to declare the std::string object i.e. str, once and use it many times to store different const char*.

What's the way out?


问:
Select Time property from Test-Connection in Powershell
Hello I found this script online below and I am trying to add time as a output but it seems like I cannot select time from test-connection command. I can select for address but not time? </p>

```<code>#selecting for address works
Test-Connection -computername 10.15.31.1 | select Address

#selecting for time does not work
Test-Connection -computername 10.15.31.1 | select Time

#You can see below what I am trying to achieve

 $output=foreach ($name in $names) {
 [PSCustomObject][ordered]@{
    Source= $ipaddress
    Destination = $name
  #  Time=Test-Connection -computername 10.15.31.1 | select Time
    Ping = Test-Connection -ComputerName $name -Quiet -Count 1
  }
}
</code>```

答:
So lets figure this out.

```<code>(Test-Connection -computername 8.8.8.8 -Count 1) | select *
</code>```

Will bring back

```<code>PSComputerName                 : Test-Computer
IPV4Address                    : 8.8.4.4
IPV6Address                    :
__GENUS                        : 2
__CLASS                        : Win32_PingStatus
__SUPERCLASS                   :
__DYNASTY                      : Win32_PingStatus
__RELPATH                      : Win32_PingStatus.Address="8.8.8.8",BufferSize=32,NoFragmentation=FALSE,RecordRoute=0,ResolveAddressNames=FALSE,SourceRoute="",SourceRouteType
                                 =0,Timeout=4000,TimestampRoute=0,TimeToLive=80,TypeofService=0
__PROPERTY_COUNT               : 24
__DERIVATION                   : {}
__SERVER                       : Test-Computer
__NAMESPACE                    : root\cimv2
__PATH                         : \\Test-Computer\root\cimv2:Win32_PingStatus.Address="8.8.8.8",BufferSize=32,NoFragmentation=FALSE,RecordRoute=0,ResolveAddressNames=FALSE,Source
                                 Route="",SourceRouteType=0,Timeout=4000,TimestampRoute=0,TimeToLive=80,TypeofService=0
Address                        : 8.8.8.8
BufferSize                     : 32
NoFragmentation                : False
PrimaryAddressResolutionStatus : 0
ProtocolAddress                : 8.8.8.8
ProtocolAddressResolved        :
RecordRoute                    : 0
ReplyInconsistency             : False
ReplySize                      : 32
ResolveAddressNames            : False
ResponseTime                   : 16
ResponseTimeToLive             : 54
RouteRecord                    :
RouteRecordResolved            :
SourceRoute                    :
SourceRouteType                : 0
StatusCode                     : 0
Timeout                        : 4000
TimeStampRecord                :
TimeStampRecordAddress         :
TimeStampRecordAddressResolved :
TimestampRoute                 : 0
TimeToLive                     : 80
TypeofService                  : 0
Scope                          : System.Management.ManagementScope
Path                           : \\Test-Computer\root\cimv2:Win32_PingStatus.Address="8.8.8.8",BufferSize=32,NoFragmentation=false,RecordRoute=0,ResolveAddressNames=false,Source
                                 Route="",SourceRouteType=0,Timeout=4000,TimestampRoute=0,TimeToLive=80,TypeofService=0
Options                        : System.Management.ObjectGetOptions
ClassPath                      : \\Test-Computer\root\cimv2:Win32_PingStatus
Properties                     : {Address, BufferSize, NoFragmentation, PrimaryAddressResolutionStatus...}
SystemProperties               : {__GENUS, __CLASS, __SUPERCLASS, __DYNASTY...}
Qualifiers                     : {dynamic, provider}
Site                           :
Container                      :
</code>```

We can see that you are looking for ResponseTime

```<code>Test-Connection -computername 8.8.8.8 | select ResponseTime
</code>```

Will Return

```<code>ResponseTime
------------
          18
          18
          15
          13
</code>```

Now Test-Connection -computername 8.8.8.8 -Quiet
Will only return a $true or $false so make sure you DO NOT use that if you are trying to get more detailed information.

Body:
Hello I found this script online below and I am trying to add time as a output but it seems like I cannot select time from test-connection command. I can select for address but not time?

#selecting for address works
Test-Connection -computername 10.15.31.1 | select Address

#selecting for time does not work
Test-Connection -computername 10.15.31.1 | select Time

#You can see below what I am trying to achieve

 $output=foreach ($name in $names) {
 [PSCustomObject][ordered]@{
    Source= $ipaddress
    Destination = $name
  #  Time=Test-Connection -computername 10.15.31.1 | select Time
    Ping = Test-Connection -ComputerName $name -Quiet -Count 1
  }
}

Body:
So lets figure this out.

(Test-Connection -computername 8.8.8.8 -Count 1) | select *

Will bring back

PSComputerName                 : Test-Computer
IPV4Address                    : 8.8.4.4
IPV6Address                    :
__GENUS                        : 2
__CLASS                        : Win32_PingStatus
__SUPERCLASS                   :
__DYNASTY                      : Win32_PingStatus
__RELPATH                      : Win32_PingStatus.Address="8.8.8.8",BufferSize=32,NoFragmentation=FALSE,RecordRoute=0,ResolveAddressNames=FALSE,SourceRoute="",SourceRouteType
                                 =0,Timeout=4000,TimestampRoute=0,TimeToLive=80,TypeofService=0
__PROPERTY_COUNT               : 24
__DERIVATION                   : {}
__SERVER                       : Test-Computer
__NAMESPACE                    : root\cimv2
__PATH                         : \\Test-Computer\root\cimv2:Win32_PingStatus.Address="8.8.8.8",BufferSize=32,NoFragmentation=FALSE,RecordRoute=0,ResolveAddressNames=FALSE,Source
                                 Route="",SourceRouteType=0,Timeout=4000,TimestampRoute=0,TimeToLive=80,TypeofService=0
Address                        : 8.8.8.8
BufferSize                     : 32
NoFragmentation                : False
PrimaryAddressResolutionStatus : 0
ProtocolAddress                : 8.8.8.8
ProtocolAddressResolved        :
RecordRoute                    : 0
ReplyInconsistency             : False
ReplySize                      : 32
ResolveAddressNames            : False
ResponseTime                   : 16
ResponseTimeToLive             : 54
RouteRecord                    :
RouteRecordResolved            :
SourceRoute                    :
SourceRouteType                : 0
StatusCode                     : 0
Timeout                        : 4000
TimeStampRecord                :
TimeStampRecordAddress         :
TimeStampRecordAddressResolved :
TimestampRoute                 : 0
TimeToLive                     : 80
TypeofService                  : 0
Scope                          : System.Management.ManagementScope
Path                           : \\Test-Computer\root\cimv2:Win32_PingStatus.Address="8.8.8.8",BufferSize=32,NoFragmentation=false,RecordRoute=0,ResolveAddressNames=false,Source
                                 Route="",SourceRouteType=0,Timeout=4000,TimestampRoute=0,TimeToLive=80,TypeofService=0
Options                        : System.Management.ObjectGetOptions
ClassPath                      : \\Test-Computer\root\cimv2:Win32_PingStatus
Properties                     : {Address, BufferSize, NoFragmentation, PrimaryAddressResolutionStatus...}
SystemProperties               : {__GENUS, __CLASS, __SUPERCLASS, __DYNASTY...}
Qualifiers                     : {dynamic, provider}
Site                           :
Container                      :

We can see that you are looking for ResponseTime

Test-Connection -computername 8.8.8.8 | select ResponseTime

Will Return

ResponseTime
------------
          18
          18
          15
          13

Now Test-Connection -computername 8.8.8.8 -Quiet
Will only return a $true or $false so make sure you DO NOT use that if you are trying to get more detailed information.


问:
Is there a way to predict that `Marshal.GetExceptionForHR(code, pointers)` would throw an `AccessViolationException`
I have a whole sequence of interlinked questions. I would like to know answers for all of them independantly, so *yes*, some of them appear to be X-Y questions; but I do want to know the solution to them anyway!. See end of question for list of other questions in this set.

I have a situation in which calling Marshal.GetExceptionForHR(code, pointers) throws an AccessViolationException.

Apparently this a VeryBadThing. So bad that try...catch just shrugs at me and wanders off for a fag ... which I didn't know was a thing :(

Suppose a premise of "calling .GetExceptionForHR() is what I want to do" (see other questions for a discussion of whether this is a good idea!).

Suppose further that whatever causes the AccessViolation is unavoidable in some scenarios.

Given those premises, is there any way to predict in advance that calling them method will blow up?
Some equivalent of TryGetExceptionForHR() that'll return false rather than blowing up my entire Program.

Other questions in this problem set.

C#: How do I prevent a pipe reading error, when closing the exe on one end of a DuplexChannel connected by Named Pipes?

Ascertain reason for Channel Fault in WCF+NamedPipes

Is using the `Marshal` static class in otherwise normal C# code unwise?

Is there a way to predict that `Marshal.GetExceptionForHR(code, pointers)` would throw an `AccessViolationException`

Is this a suitable use of `HandleProcessCorruptedStateExceptions`

答:
Just having a look at the Microsoft docs, Marshall.GetExceptionForHR doesn't throw an exception that can be caught.

Instead, they recommend using Marshall.ThrowExceptionForHR to get a thrown exception that you can then handle. This does not throw an exception when using a success HResult.

If you want to use Marshall.GetExceptionForHR then double-check that the correct pointer is being used. IntPtr(0) will use the current IErrorInfo interface while IntPtr(-1) will attempt to reconstruct the exception from just the code.

It's also possible that rather than throwing unexpected exceptions, GetExceptionForHR just returns the unexpected exception from a catch block e.g.:

```<code>catch(Exception ex)
{
   return ex;
};
</code>```

Unfortunately, I can't be 100% certain at this point, I'm trying to track down the Marshall class on Microsoft's Github and I'll run some of my own attempts to see if I can get the same effect as yourself.

Related links:

ThrowExceptionForHR

GetExceptionForHR

Body:
Just having a look at the Microsoft docs, Marshall.GetExceptionForHR doesn't throw an exception that can be caught.

Instead, they recommend using Marshall.ThrowExceptionForHR to get a thrown exception that you can then handle. This does not throw an exception when using a success HResult.

If you want to use Marshall.GetExceptionForHR then double-check that the correct pointer is being used. IntPtr(0) will use the current IErrorInfo interface while IntPtr(-1) will attempt to reconstruct the exception from just the code.

It's also possible that rather than throwing unexpected exceptions, GetExceptionForHR just returns the unexpected exception from a catch block e.g.:

catch(Exception ex)
{
   return ex;
};

Unfortunately, I can't be 100% certain at this point, I'm trying to track down the Marshall class on Microsoft's Github and I'll run some of my own attempts to see if I can get the same effect as yourself.

Related links:

ThrowExceptionForHR

GetExceptionForHR


问:
JQUERY - Change hidden input with multiple submit
I Have a simple FORM with a Hidden Input only - and multiple submit buttons (1 to infinite)

When the user click on submit - the button change the hidden input value to submit the form.

```<code><form action="" id="form">
    <input type="hidden" name="answer" id="answer">
    <input type="submit" value="A">
    <input type="submit" value="B">
    <input type="submit" value="C">
</form>
</code>```

```<code>$("#form").on("submit", function (event) {
   event.preventDefault();
   var currentForm = $(this);
   $("#answer").val() = $("#submit").val();
});
</code>```

how can I do this?

I'm trying Jquery, but - something is wrong. I know this is easy, but I'm not an expert

tks a lot!
Daniel

答:
If I know what you mean...
For example, this is HTML of your form

```<code><form action="" id="form_id_example">
    <input type="hidden" name="change_value" id="change_value">
    <input type="submit" name="">
</form>
</code>```

The jQuery is something similar to that

```<code>$("#form_id_example").on("submit", function (event) {
   event.preventDefault();
   var currentForm = $(this);
   $("#change_value").val("new input value");
   $("#form_id_example").off("submit");
   currentForm.submit();
});
</code>```

Body:
I Have a simple FORM with a Hidden Input only - and multiple submit buttons (1 to infinite)

When the user click on submit - the button change the hidden input value to submit the form.

<form action="" id="form">
    <input type="hidden" name="answer" id="answer">
    <input type="submit" value="A">
    <input type="submit" value="B">
    <input type="submit" value="C">
</form>

$("#form").on("submit", function (event) {
   event.preventDefault();
   var currentForm = $(this);
   $("#answer").val() = $("#submit").val();
});

how can I do this?

I'm trying Jquery, but - something is wrong. I know this is easy, but I'm not an expert

tks a lot!
Daniel

Body:
If I know what you mean...
For example, this is HTML of your form

<form action="" id="form_id_example">
    <input type="hidden" name="change_value" id="change_value">
    <input type="submit" name="">
</form>

The jQuery is something similar to that

$("#form_id_example").on("submit", function (event) {
   event.preventDefault();
   var currentForm = $(this);
   $("#change_value").val("new input value");
   $("#form_id_example").off("submit");
   currentForm.submit();
});


问:
rotate PDF 90 degrees relative to current rotation
I have rotated a PDF using fitz by 90 degrees using this code:

```<code>fitz_doc = fitz.open(origin, filetype="pdf")
fitz_doc_name = f"{fitz_doc.name}.pdf"

page = fitz_doc[int(0)]
page.setRotation(90)
fitz_doc.save(fitz_doc_name)
fitz_doc.close()
</code>```

However, if I want to rotate the document again by another 90 degrees, I have to set page.setRotation to 180 and not 90. I suspect this has to do with how the 3x3 Matrix values are being manipulated but not sure if that is correct or how to manipulate the values directly.

How can I rotate a document relative to the current rotation so that if a document was previously rotated by 90 I only need to set rotation value to 90 and not 180 for the second rotation?

答:
I'm not sure there's a direct way to do this. Instead, you get the current rotation value and then add to it how much more you want to rotate.</p>

```<code>more_rot = 90  # extra rotation desired
current_rot = page.rotation
page.setRotation(current_rot + more_rot)
</code>```

Body:
I have rotated a PDF using fitz by 90 degrees using this code:

fitz_doc = fitz.open(origin, filetype="pdf")
fitz_doc_name = f"{fitz_doc.name}.pdf"

page = fitz_doc[int(0)]
page.setRotation(90)
fitz_doc.save(fitz_doc_name)
fitz_doc.close()

However, if I want to rotate the document again by another 90 degrees, I have to set page.setRotation to 180 and not 90. I suspect this has to do with how the 3x3 Matrix values are being manipulated but not sure if that is correct or how to manipulate the values directly.

How can I rotate a document relative to the current rotation so that if a document was previously rotated by 90 I only need to set rotation value to 90 and not 180 for the second rotation?

Body:
I'm not sure there's a direct way to do this. Instead, you get the current rotation value and then add to it how much more you want to rotate.

more_rot = 90  # extra rotation desired
current_rot = page.rotation
page.setRotation(current_rot + more_rot)


问:
SuiteScript2.0 Please Add Value To Amount
I have a suitelet that is creating an order. Most times this works but sometimes, maybe 1 in 50 it fails with this error. "Please enter a value for amount."

The error is thrown when sommitting this.

```<code>if(orderLine.amount){
    log.debug("itemrate", orderLine.itemrate);
    salesOrder.setCurrentSublistValue({
        sublistId   : 'item',
        fieldId     : 'rate',
        value       : Number(orderLine.itemrate ? orderLine.itemrate : (orderLine.amount / orderLine.qty))
    });
    fieldServices.sleep(1000);
    log.debug("Amount", orderLine.amount);
    salesOrder.setCurrentSublistValue({
        sublistId   : 'item',
        fieldId     : 'amount',
        value       : Number(orderLine.amount)
    });
}
</code>```

The logs on a fail execution reads

```<code>2   View    Debug   Amount      26/05/2020  11:21 AM    -System-    118.0909090909091
3   View    Debug   itemrate    26/05/2020  11:21 AM    -System-    118.0909
</code>```

So the amount is getting set with an amount but when I try to commit the line it doesn't work 100% of the time.

答:
So here was the problem. I assumed the logging was on the line that I posted but it turned out it was trying to add another line with the amount of 0. JavaScript being JavaScript saw 0 as false in

```<code> if(orderLine.amount)
</code>```

so the amount was never added to the line. I changed this if statement to read

```<code>if(orderLine.amount || orderLine.amount == 0)
</code>```

This solved the problem.

Body:
I have a suitelet that is creating an order. Most times this works but sometimes, maybe 1 in 50 it fails with this error. "Please enter a value for amount."

The error is thrown when sommitting this.

if(orderLine.amount){
    log.debug("itemrate", orderLine.itemrate);
    salesOrder.setCurrentSublistValue({
        sublistId   : 'item',
        fieldId     : 'rate',
        value       : Number(orderLine.itemrate ? orderLine.itemrate : (orderLine.amount / orderLine.qty))
    });
    fieldServices.sleep(1000);
    log.debug("Amount", orderLine.amount);
    salesOrder.setCurrentSublistValue({
        sublistId   : 'item',
        fieldId     : 'amount',
        value       : Number(orderLine.amount)
    });
}

The logs on a fail execution reads

2   View    Debug   Amount      26/05/2020  11:21 AM    -System-    118.0909090909091
3   View    Debug   itemrate    26/05/2020  11:21 AM    -System-    118.0909

So the amount is getting set with an amount but when I try to commit the line it doesn't work 100% of the time.

Body:
So here was the problem. I assumed the logging was on the line that I posted but it turned out it was trying to add another line with the amount of 0. JavaScript being JavaScript saw 0 as false in

 if(orderLine.amount)

so the amount was never added to the line. I changed this if statement to read

if(orderLine.amount || orderLine.amount == 0)

This solved the problem.


问:
Recursion error in R (Fibonacci sequence)
So I am trying to learn R on my own and am just working through the online tutorial. I am trying to code a recursive function that prints the first n terms of the Fibonacci sequence and can't get the code to run without the error:

Error in if (nterms <= 0) { : missing value where TRUE/FALSE needed

My code does ask me for input before entering the if else statement either which I think is odd as well. Below is my code any help is appreciated.

```<code>#Define the fibonacci sequence

recurse_fibonacci <- function(n) {
    # Define the initial two values of the sequence

    if (n <= 1){
        return(n)
    } else {

    # define the rest of the terms of the sequence using recursion
    return(recurse_fibonacci(n-1) + recurse_fibonacci(n-2))
    }
}

#Take input from the user
nterms = as.integer(readline(prompt="How many terms? "))

# check to see if the number of terms entered is valid
if(nterms <= 0) {
    print("please enter a positive integer")
} else {

    # This part actually calculates and displays the first n terms of the sequence
    print("Fibonacci Sequence: ")
    for(i in 0:(nterms - 1)){
        print(recurse_fibonacci(i))
    }
}
</code>```

答:
This is a problem of readline in non-interactive mode. readline does not wait for a keypress and immediately executes the next instruction. The solution below is the solution posted in this other SO post.

I post below a complete answer, with the Fibonnaci numbers function a bit modified.

```<code>recurse_fibonacci <- function(n) {
  # Define the initial two values of the sequence
  if (n <= 1){
    n
  } else{
    # define the rest of the terms of the sequence using recursion
    Recall(n - 1) + Recall(n - 2)
  }
}

#Take input from the user
cat("How many terms?\n")
repeat{
  nterms <- scan("stdin", what = character(), n = 1)
  if(nchar(nterms) > 0) break
}
nterms <- as.integer(nterms)

# check to see if the number of terms entered is valid
if(nterms <= 0) {
  print("please enter a positive integer")
} else {
  # This part actually calculates and displays the first n terms of the sequence
  print("Fibonacci Sequence: ")
  for(i in 0:(nterms - 1)){
    print(recurse_fibonacci(i))
  }
}
</code>```

This code is the contents of file fib.R. Running in a Ubuntu 20.04 terminal gives

```<code>rui@rui:~$ Rscript fib.R
How many terms?
8
Read 1 item
[1] "Fibonacci Sequence: "
[1] 0
[1] 1
[1] 1
[1] 2
[1] 3
[1] 5
[1] 8
[1] 13
rui@rui:~$
</code>```

Body:
So I am trying to learn R on my own and am just working through the online tutorial. I am trying to code a recursive function that prints the first n terms of the Fibonacci sequence and can't get the code to run without the error:

Error in if (nterms <= 0) { : missing value where TRUE/FALSE needed

My code does ask me for input before entering the if else statement either which I think is odd as well. Below is my code any help is appreciated.

#Define the fibonacci sequence

recurse_fibonacci <- function(n) {
    # Define the initial two values of the sequence

    if (n <= 1){
        return(n)
    } else {

    # define the rest of the terms of the sequence using recursion
    return(recurse_fibonacci(n-1) + recurse_fibonacci(n-2))
    }
}

#Take input from the user
nterms = as.integer(readline(prompt="How many terms? "))

# check to see if the number of terms entered is valid
if(nterms <= 0) {
    print("please enter a positive integer")
} else {

    # This part actually calculates and displays the first n terms of the sequence
    print("Fibonacci Sequence: ")
    for(i in 0:(nterms - 1)){
        print(recurse_fibonacci(i))
    }
}

Body:
This is a problem of readline in non-interactive mode. readline does not wait for a keypress and immediately executes the next instruction. The solution below is the solution posted in this other SO post.

I post below a complete answer, with the Fibonnaci numbers function a bit modified.

recurse_fibonacci <- function(n) {
  # Define the initial two values of the sequence
  if (n <= 1){
    n
  } else{
    # define the rest of the terms of the sequence using recursion
    Recall(n - 1) + Recall(n - 2)
  }
}

#Take input from the user
cat("How many terms?\n")
repeat{
  nterms <- scan("stdin", what = character(), n = 1)
  if(nchar(nterms) > 0) break
}
nterms <- as.integer(nterms)

# check to see if the number of terms entered is valid
if(nterms <= 0) {
  print("please enter a positive integer")
} else {
  # This part actually calculates and displays the first n terms of the sequence
  print("Fibonacci Sequence: ")
  for(i in 0:(nterms - 1)){
    print(recurse_fibonacci(i))
  }
}

This code is the contents of file fib.R. Running in a Ubuntu 20.04 terminal gives

rui@rui:~$ Rscript fib.R
How many terms?
8
Read 1 item
[1] "Fibonacci Sequence: "
[1] 0
[1] 1
[1] 1
[1] 2
[1] 3
[1] 5
[1] 8
[1] 13
rui@rui:~$


问:
What is the difference between localStorage, sessionStorage, session and cookies?
What are the technical pros and cons of localStorage, sessionStorage, session and cookies, and when would I use one over the other?

答:
here is a quick review and with a simple and quick understanding

from instructor Beau Carnes from freecodecamp


问:
How to model REST URL for which there is no equivalent HTTP method?
I have customers and I want to activate and cancel their plans. I am trying to be as RESTful as possible.

Should the action to perform 'active' or 'suspend' be part of URI ?

1) POST customers/{customerId}/activatePlan/{planName}
2) POST customers/{customerId}/suspendPlan/{planName}

My problem is that both activate and cancel are verbs or actions. They do not have any equivalent HTTP action ( GET, POST, PATCH etc.)

Are my URL's restful ? if not, how to make them REST ful.

答:
Everything is a resource on the RESTful paradigm and these resources are manipulated with one of the HTTP methods (GET, POST, PUT, DELETE, etc ...).

You can create a plan with POST:

POST customers/{customerId}/{planName}

once a plan is created we have to activate or deactivate it and here we have a couple of choices:

Using the action in the URI. We use PUT in this case as the planName resource exists (so it is an update):

PUT customers/{customerId}/{planName}/activate

Set a property on the planName resource (still a PUT as it is an update on the planName resource). The activate property in the body of the HTTP PUT request (i.e.: activate=true or activate=false):

PUT customers/{customerId}/{planName}

then you can use GET to return the status of the planName resource

GET customers/{customerId}/{planName}

and DELETE if you want to remove planName from a customer:

GET customers/{customerId}/{planName}


问:
Window Workflow SendReceive Activity timeout issue
I have hosted a state machine Worklow as a WCF service..And the workflow is called in an ASP.NET code. I used netTcpContextBinding for workflow hosting. Problem is that if a SendRecieve activity within the workflow is taking a lot of time (say 1 minute) to execute, then it will show transaction aborted error and will terminate.. i have already set the binding values for send, recieve, open, close timeouts to maximum values in both web.config and the app.config..

How can i overcome this issue?

答: A TransactionScope has a default timeout of 60 seconds so if whatever you are doing in there takes longer it will time out and abort. You can increase the timeout on the TransactionScope but quite frankly the 60 seconds is already quite long. In most cases you are better of at doing any long running work to collect data before the transaction and keep your transaction time as short as possible.</p>


问:
error converting YAML to JSON, did not find expected key kubernetes
I am doing a lab about kubernetes in google cloud.

I have create the YAML file, but when I am trying to deploy it a shell shows me this error:

```<code>error converting YAML to JSON: yaml: line 34: did not find expected key
</code>```

YAML file:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
    spec:
      volumes:
      - name: nginx-config
        configMap:
          name: nginx-config
      - name: php-config
        configMap:
          name: php-config
      containers:
      - image: php-fpm:7.2
        name: php
        ports:
        - containerPort: 9000
        volumeMounts:
        - name: persistent-storage
          mountPath: /var/www/data
        - name: php-config
          mountPath: /usr/local/etc/php-fpm.d/www.conf
          subPath: www.conf
      - image: nginx:latest
        name: nginx
        - containerPort: 80
        volumeMounts:
        - name: persistent-storage
          mountPath: /var/www/data
        - name: nginx-config
          mountPath: /etc/nginx/nginx.conf
          subPath: nginx.conf
      volumes:
        - name: persistent-storage
          persistentVolumeClaim:
            claimName: nfs-pvc
</code>```

答:
Following higuita's answer you can lint your yaml and check for errors without installing a module in your machine using npx. I prefer this approach for commands that I do not intend to use often. NPX downloads the package, executes the command and remove the package when finishes.

```<code>npx yaml-lint yamllint file_name
</code>```

Body:
I am doing a lab about kubernetes in google cloud.

I have create the YAML file, but when I am trying to deploy it a shell shows me this error:

error converting YAML to JSON: yaml: line 34: did not find expected key

YAML file:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
    spec:
      volumes:
      - name: nginx-config
        configMap:
          name: nginx-config
      - name: php-config
        configMap:
          name: php-config
      containers:
      - image: php-fpm:7.2
        name: php
        ports:
        - containerPort: 9000
        volumeMounts:
        - name: persistent-storage
          mountPath: /var/www/data
        - name: php-config
          mountPath: /usr/local/etc/php-fpm.d/www.conf
          subPath: www.conf
      - image: nginx:latest
        name: nginx
        - containerPort: 80
        volumeMounts:
        - name: persistent-storage
          mountPath: /var/www/data
        - name: nginx-config
          mountPath: /etc/nginx/nginx.conf
          subPath: nginx.conf
      volumes:
        - name: persistent-storage
          persistentVolumeClaim:
            claimName: nfs-pvc

Body:
Following higuita's answer you can lint your yaml and check for errors without installing a module in your machine using npx. I prefer this approach for commands that I do not intend to use often. NPX downloads the package, executes the command and remove the package when finishes.

npx yaml-lint yamllint file_name


问:
Creating a continuous counter with Javascript?
```<code>function lemath()
{
    var count;
    count = 0;
    stuff.innerHTML = "stuff" + count;

}

function begin()
{
    lemath();
    setTimeout(function() {
        begin();
    }, 1000);

}
</code>```

I'm trying to create an infinite loop that will count each time it loops and display it, but when I do the code above it just gives back undefined?
Thank you very much with the help! :)

答:
you can use setInterval javascript method for increase your counter

// setInterval(fn, time);

 // your counter state should be start from 0
let count = 0;

// Your function should be run each time (for example each second)
const increment = () => {
    count++
// show count in console or in DOM
    console.log(count)
    element.innerHTML = count
}

setInterval(increment, 1000);

```
<h3>For Performance reason and for stop or reset timer you can use <code>clearInterval</code> method</h3>
<pre class="lang-js prettyprint-override"><code>
const timer = setInterval(increment, 1000);

 // stop counter

  clearInterval(timer)

</code>```

Body:
function lemath()
{
    var count;
    count = 0;
    stuff.innerHTML = "stuff" + count;

}

function begin()
{
    lemath();
    setTimeout(function() {
        begin();
    }, 1000);

}

I'm trying to create an infinite loop that will count each time it loops and display it, but when I do the code above it just gives back undefined?
Thank you very much with the help! :)

Body:
you can use setInterval javascript method for increase your counter

// setInterval(fn, time);

 // your counter state should be start from 0
let count = 0;

// Your function should be run each time (for example each second)
const increment = () => {
    count++
// show count in console or in DOM
    console.log(count)
    element.innerHTML = count
}

setInterval(increment, 1000);

For Performance reason and for stop or reset timer you can use clearInterval method

const timer = setInterval(increment, 1000);

 // stop counter

  clearInterval(timer)


问:
How to resolve a steam custom vanity profile URL to steamID64
I am using Steam's API to fetch player data. To do this you need to provide a steamID64 (76561197960435530) like this example shown here: http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=440&key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&steamid=76561197960435530 however this can sometimes be tricky for my users as many have their own custom vanity url which does not provide the steamID64 for them to easily input. I know they could use use a website to look it up but this is not an option.

How would I take the input of a custom vanity profile URL like this: https://steamcommunity.com/id/customNameHere and convert this programatically into a steamID64 like this: 76561197960435530

I would like to implement this using JavaScript or by using an API.

答:
Found the solution. Here it says you can use the following syntax to resolve a vanity url:

http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=XXXXXXXXXXXXXXXXXXXXXXX&vanityurl=userVanityUrlName

Don't quite know why it was hiding on the TF2 wiki though...


问:
d3v4 Timeline chart - upgrading from version 3 to 4

I have a timeline application - that was using the old d3. I've tried upgrading it and refactoring the codebase - but I've hit a snag with the scale change. This is good as a gantt chart.

//version 3
https://jsfiddle.net/5xsu76ck/1/

//version 4
https://jsfiddle.net/8cy719w0/2/

```<code>            //scales
            var x =  d3.scaletime()
                    .domain([timeBegin, timeEnd])
                    .range([0, width]);
            var x1 = d3.scaleLinear()
                    .range([0, width]);
            var y1 = d3.scaleLinear()
                    .domain([0, laneLength])
                    .range([0, mainHeight]);
            var y2 = d3.scaleLinear()
                    .domain([0, laneLength])
                    .range([0, miniHeight]);

            var scaleFactor = (1/(timeEnd - timeBegin)) * (width);
</code>```

current issue
https://jsfiddle.net/8cy719w0/2/ -- I've managed to get pass some issues - but now got a problem with the brush

```<code>            //brush
    var brush = d3.brushX()
       .extent([
         [0, 0],
         [width, miniHeight]
       ])
       .on("brush", display);
</code>```

答:
d3 version 4 uses d3.scaleTime, so your x variable should be

```<code>var x =  d3.scaleTime()
.domain([timeBegin, timeEnd])
.range([0, width]);
</code>```

https://github.com/d3/d3-scale#time-scales

Body:
I have a timeline application - that was using the old d3. I've tried upgrading it and refactoring the codebase - but I've hit a snag with the scale change. This is good as a gantt chart.

//version 3
https://jsfiddle.net/5xsu76ck/1/

//version 4
https://jsfiddle.net/8cy719w0/2/

            //scales
            var x =  d3.scaletime()
                    .domain([timeBegin, timeEnd])
                    .range([0, width]);
            var x1 = d3.scaleLinear()
                    .range([0, width]);
            var y1 = d3.scaleLinear()
                    .domain([0, laneLength])
                    .range([0, mainHeight]);
            var y2 = d3.scaleLinear()
                    .domain([0, laneLength])
                    .range([0, miniHeight]);

            var scaleFactor = (1/(timeEnd - timeBegin)) * (width);

current issue
https://jsfiddle.net/8cy719w0/2/ -- I've managed to get pass some issues - but now got a problem with the brush

            //brush
    var brush = d3.brushX()
       .extent([
         [0, 0],
         [width, miniHeight]
       ])
       .on("brush", display);

Body:
d3 version 4 uses d3.scaleTime, so your x variable should be

var x =  d3.scaleTime()
.domain([timeBegin, timeEnd])
.range([0, width]);

https://github.com/d3/d3-scale#time-scales


问:
Why dosen't setting the className style the React element
I have been trying to add style element to my React, when I would do the following, the style does not show up:

```<code><body>
  <div id="root">
    <script src="https://unpkg.com/react@16.7.0/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16.7.0/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone@7.8.3/babel.js"></script>
    <style>
      .box {
        border: 1px solid black;
        display: flex;
        flex-direction: column;
        justify-content: center;
        text-align: center;
      }

      .box--large {
        width: 270px;
        height: 270px;
      }

      .box--medium {
        width: 180px;
        height: 180px;
      }

      .box--small {
        width: 90px;
        height: 90px;
      }
    </style>
    <script type="text/babel">
      const rootElement = document.getElementById("root");
      const element = (
        <div>
        <div className="box box--small">small lightblue box</div>
      </div>
        );
      ReactDOM.render(element, rootElement);
    </script>
</body>

</code>```

But, when I change the code to the following, it works:

```<code><body>
  <div id="root">
    <script src="https://unpkg.com/react@16.7.0/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16.7.0/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone@7.8.3/babel.js"></script>
    <script type="text/babel">
      const rootElement = document.getElementById("root");
      const element = (
       <div>
        <div className="box box--small" style={{fontStyle: 'italic',backgroundColor: 'lightblue',width: "90px",height: "90px"}}>small lightblue box</div>
      </div>
        );
      ReactDOM.render(element, rootElement);
    </script>
</body>

</code>```

Essentially, moving the style to the div element when I declare it adds the styling. I understand why the second one works, but why dosen't the first one work?

答:
In React, inline styles are not specified as a string. Instead they are specified with an object whose key is the camelCased version of the style name, and whose value is the style's value, usually a string (more on that later):
There are few way you can write style in React.</p>

```<code>1. inline styling
class MyHeader extends React.Component {
  render() {
    return (
      <div>
      <h1 style={{color: "red"}}>Hello Style!</h1>
      <p>Add a little style!</p>
      </div>
    );
  }
}

2. javascript object

class MyHeader extends React.Component {
  render() {
    const mystyle = {
      color: "white",
      backgroundColor: "DodgerBlue",
      padding: "10px",
      fontFamily: "Arial"
    };
    return (
      <div>
      <h1 style={mystyle}>Hello Style!</h1>
      <p>Add a little style!</p>
      </div>
    );
  }
}

3. External stylesheet
App.css:
- Create a new file called "App.css" and insert some CSS code in it:

body {
  background-color: #282c34;
  color: white;
  padding: 40px;
  font-family: Arial;
  text-align: center;
}

- Import the stylesheet in your application:

index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './App.css';

class MyHeader extends React.Component {
  render() {
    return (
      <div>
      <h1>Hello Style!</h1>
      <p>Add a little style!.</p>
      </div>
    );

}
}

ReactDOM.render(<MyHeader />, document.getElementById('root'));

4. css modules
mystyle.module.css:
- Create a new file called "mystyle.module.css" and insert some CSS code in it:

.bigblue {
  color: DodgerBlue;
  padding: 40px;
  font-family: Arial;
  text-align: center;
}

- Import the stylesheet in your component:

App.js:
import React from 'react';
import ReactDOM from 'react-dom';
import styles from './mystyle.module.css';

class Car extends React.Component {
  render() {
    return <h1 className={styles.bigblue}>Hello Car!</h1>;
  }
}

export default Car;
</code>```

Body:
I have been trying to add style element to my React, when I would do the following, the style does not show up:

But, when I change the code to the following, it works:

Essentially, moving the style to the div element when I declare it adds the styling. I understand why the second one works, but why dosen't the first one work?

Body:
In React, inline styles are not specified as a string. Instead they are specified with an object whose key is the camelCased version of the style name, and whose value is the style's value, usually a string (more on that later):
There are few way you can write style in React.

1. inline styling
class MyHeader extends React.Component {
  render() {
    return (
      <div>
      <h1 style={{color: "red"}}>Hello Style!</h1>
      <p>Add a little style!</p>
      </div>
    );
  }
}

2. javascript object

class MyHeader extends React.Component {
  render() {
    const mystyle = {
      color: "white",
      backgroundColor: "DodgerBlue",
      padding: "10px",
      fontFamily: "Arial"
    };
    return (
      <div>
      <h1 style={mystyle}>Hello Style!</h1>
      <p>Add a little style!</p>
      </div>
    );
  }
}

3. External stylesheet
App.css:
- Create a new file called "App.css" and insert some CSS code in it:

body {
  background-color: #282c34;
  color: white;
  padding: 40px;
  font-family: Arial;
  text-align: center;
}

- Import the stylesheet in your application:

index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './App.css';

class MyHeader extends React.Component {
  render() {
    return (
      <div>
      <h1>Hello Style!</h1>
      <p>Add a little style!.</p>
      </div>
    );

}
}

ReactDOM.render(<MyHeader />, document.getElementById('root'));

4. css modules
mystyle.module.css:
- Create a new file called "mystyle.module.css" and insert some CSS code in it:

.bigblue {
  color: DodgerBlue;
  padding: 40px;
  font-family: Arial;
  text-align: center;
}

- Import the stylesheet in your component:

App.js:
import React from 'react';
import ReactDOM from 'react-dom';
import styles from './mystyle.module.css';

class Car extends React.Component {
  render() {
    return <h1 className={styles.bigblue}>Hello Car!</h1>;
  }
}

export default Car;


问:
Does interrupting the SQL Server import and Export Wizard rollback the transaction?
I am loading several large CSV (8 million rows a piece) into a local SQL Server instance. On one of them, when it was about 70,000 rows in, I realized that I made a mistake in the mappings so I hit Stop to interrupt it and cancelled the operation. </p>

<p>Did those 70,000 or so rows get inserted and create duplicates when I imported the same file again or is the whole transaction rolled back? </p>

答:
If you are importing from the SQL Server Import and Export Wizard and you clicked on "Stop" during the "Copying to ..." Action, it does not automatically rollback the rows that were copied into the table before you clicked "Stop", those rows are in your table at that point.

To will need to manually delete those rows.

Body:
I am loading several large CSV (8 million rows a piece) into a local SQL Server instance. On one of them, when it was about 70,000 rows in, I realized that I made a mistake in the mappings so I hit Stop to interrupt it and cancelled the operation.

Did those 70,000 or so rows get inserted and create duplicates when I imported the same file again or is the whole transaction rolled back?


问:
Mapping AWS instances to GC instances
Let's say I want to deploy an instance on google cloud engine instead of AWS EC2.

According to the description I found on AWS website, an instance is defined by its CPU, Memory, storage and networking. And I found a mapping between EC2 and GCE instances on the GC website. However, the corresponding instances have very different CPU and Memory. Also, as it's possible to customize machine type on GCE, isn't it more adequate to just custom all my machines to give them the exact same characteristics as the equivalent instances with AWS ?

答:
Not sure if you're referring to this page:

https://cloud.google.com/docs/compare/aws/compute

Which is where the Google docs cover some terminology and equivalency between the two offerings. Note that where it's talking on that page around instance mapping, it isn't intended to be a 1:1 mapping of CPU/RAM/etc. It's just talking about general buckets and what they're named. So e.g. t2.micro vs. f1-micro, etc. I don't believe the intention is that those are necessarily the same machine configurations, but more that the bucket of "instance type" like "standard", "high memory", "high CPU", etc" and how the names line up with the general category between the two companies.

As Kolban mentioned in his comment, yes, GCE instances can just be configured specifically with RAM/CPU numbers rather than relying on the tier to make it equivalent to what you need.

One other piece, is that you'll also likely want to customize the storage. Out of the box there's limited options around storage for an instance, but if you (in the creation) go look at the options to add storage disk, it gives you the option of things like adding local SSDs, or persistent disks to the instance which allows you to tune it to be more specifically aligned with whatever you're coming from.

Title: Mapping AWS instances to GC instances


问:
Non-exhaustive patterns in function toEnum
For some reason, my ghci keeps giving this warning "Non-exhaustive patterns in function toEnum", here's my code:

```<code>data Rank = Numeric Int | Jack | Queen | King | Ace deriving (Eq,Ord)

instance Show Rank where
        show (Numeric n) = show n
        show Jack = "J"
        show Queen = "Q"
        show King = "K"
        show Ace = "A"

data Suit = Spades | Hearts | Diamonds | Clubs deriving (Eq,Ord,Bounded)

instance Show Suit where
        show Spades = "♠"
        show Hearts = "♥"
        show Diamonds = "♦"
        show Clubs = "♣"

data Card = Card {rank::Rank, suit::Suit} deriving (Eq, Ord)

instance Show Card where
        show (Card r s) = show r++show s

instance Enum Rank where
        succ (Numeric 10) = Jack
        succ (Numeric a) = Numeric (succ a)
        succ Jack = Queen
        succ Queen = King
        succ King = Ace
        succ Ace = Ace
        pred Ace = King
        pred King = Queen
        pred Queen = Jack
        pred Jack = (Numeric 10)
        pred (Numeric 2) = Numeric 2
        pred (Numeric a) = Numeric (pred a)
        fromEnum (Numeric a) = a
        fromEnum Jack = 11
        fromEnum Queen = 12
        fromEnum King = 13
        fromEnum Ace = 14
        toEnum 14 = Ace
        toEnum 13 = King
        toEnum 12 = Queen
        toEnum 11 = Jack
        toEnum a = (Numeric a)

instance Enum Suit where
        succ Spades = Hearts
        succ Hearts = Diamonds
        succ Diamonds = Clubs
        succ Clubs = Spades
        pred Clubs = Diamonds
        pred Diamonds = Hearts
        pred Hearts = Spades
        pred Spades = Clubs
        fromEnum Spades = 1
        fromEnum Hearts = 2
        fromEnum Diamonds = 3
        fromEnum Clubs = 4
        (toEnum) 4 = Clubs
        (toEnum) 3 = Diamonds
        (toEnum) 2 = Hearts
        (toEnum) 1 = Spades

instance Enum Card where
        succ (Card (a) (Clubs)) = Card (succ a) (succ Clubs)
        succ (Card (a) (b)) = Card (a) (succ b)
        fromEnum (Card (a) (b)) = (fromEnum(a) * 4) + (fromEnum b)
        toEnum a = Card (toEnum(a`div`4)) (toEnum(a`mod`4))
</code>```

So, he says it is in the line 60 until the line 63, when I'm using toEnum in the Suits data. So, I always have this error when I try to "toEnum" a card that belongs to the Spades class, the another classes I have no problem, can anyone help me?

答:
For some reason, my ghci keeps giving this warning "Non-exhaustive patterns in function toEnum".

That makes perfect sense since for all values except 4, 3, 2 and 1, there is no clause that will fire. One can pass any Int value to the toEnum function, hence for example for toEnum 0, it will error.

You can for example specify to raise an error with:

```<code>import GHC.Enum(<b>toEnumError</b>)

instance Enum Suit where
        succ Spades = Hearts
        succ Hearts = Diamonds
        succ Diamonds = Clubs
        succ Clubs = Spades
        pred Clubs = Diamonds
        pred Diamonds = Hearts
        pred Hearts = Spades
        pred Spades = Clubs
        fromEnum Spades = 1
        fromEnum Hearts = 2
        fromEnum Diamonds = 3
        fromEnum Clubs = 4
        toEnum 4 = Clubs
        toEnum 3 = Diamonds
        toEnum 2 = Hearts
        toEnum 1 = Spades
        <b>toEnum n = toEnumError "Suit" n (minBound :: Suit, maxBound)</b></code>```

Furthermore you better use values between 0 and 3, especially since later you use n `div` 4, which is a value between 0 and 3. So:

```<code>import GHC.Enum(<b>toEnumError</b>)

instance Enum Suit where
        succ Spades = Hearts
        succ Hearts = Diamonds
        succ Diamonds = Clubs
        succ Clubs = Spades
        pred Clubs = Diamonds
        pred Diamonds = Hearts
        pred Hearts = Spades
        pred Spades = Clubs
        fromEnum Spades = <b>0</b>
        fromEnum Hearts = <b>1</b>
        fromEnum Diamonds = <b>2</b>
        fromEnum Clubs = <b>3</b>
        toEnum <b>0</b> = Spades
        toEnum <b>1</b> = Hearts
        toEnum <b>2</b> = Diamonds
        toEnum <b>3</b> = Clubs
        <b>toEnum n = toEnumError "Suit" n (minBound :: Suit, maxBound)</b></code>```

Body:
For some reason, my ghci keeps giving this warning "Non-exhaustive patterns in function toEnum", here's my code:

data Rank = Numeric Int | Jack | Queen | King | Ace deriving (Eq,Ord)

instance Show Rank where
        show (Numeric n) = show n
        show Jack = "J"
        show Queen = "Q"
        show King = "K"
        show Ace = "A"

data Suit = Spades | Hearts | Diamonds | Clubs deriving (Eq,Ord,Bounded)

instance Show Suit where
        show Spades = "♠"
        show Hearts = "♥"
        show Diamonds = "♦"
        show Clubs = "♣"

data Card = Card {rank::Rank, suit::Suit} deriving (Eq, Ord)

instance Show Card where
        show (Card r s) = show r++show s

instance Enum Rank where
        succ (Numeric 10) = Jack
        succ (Numeric a) = Numeric (succ a)
        succ Jack = Queen
        succ Queen = King
        succ King = Ace
        succ Ace = Ace
        pred Ace = King
        pred King = Queen
        pred Queen = Jack
        pred Jack = (Numeric 10)
        pred (Numeric 2) = Numeric 2
        pred (Numeric a) = Numeric (pred a)
        fromEnum (Numeric a) = a
        fromEnum Jack = 11
        fromEnum Queen = 12
        fromEnum King = 13
        fromEnum Ace = 14
        toEnum 14 = Ace
        toEnum 13 = King
        toEnum 12 = Queen
        toEnum 11 = Jack
        toEnum a = (Numeric a)

instance Enum Suit where
        succ Spades = Hearts
        succ Hearts = Diamonds
        succ Diamonds = Clubs
        succ Clubs = Spades
        pred Clubs = Diamonds
        pred Diamonds = Hearts
        pred Hearts = Spades
        pred Spades = Clubs
        fromEnum Spades = 1
        fromEnum Hearts = 2
        fromEnum Diamonds = 3
        fromEnum Clubs = 4
        (toEnum) 4 = Clubs
        (toEnum) 3 = Diamonds
        (toEnum) 2 = Hearts
        (toEnum) 1 = Spades

instance Enum Card where
        succ (Card (a) (Clubs)) = Card (succ a) (succ Clubs)
        succ (Card (a) (b)) = Card (a) (succ b)
        fromEnum (Card (a) (b)) = (fromEnum(a) * 4) + (fromEnum b)
        toEnum a = Card (toEnum(a`div`4)) (toEnum(a`mod`4))

So, he says it is in the line 60 until the line 63, when I'm using toEnum in the Suits data. So, I always have this error when I try to "toEnum" a card that belongs to the Spades class, the another classes I have no problem, can anyone help me?

Body:
For some reason, my ghci keeps giving this warning "Non-exhaustive patterns in function toEnum".

That makes perfect sense since for all values except 4, 3, 2 and 1, there is no clause that will fire. One can pass any Int value to the toEnum function, hence for example for toEnum 0, it will error.

You can for example specify to raise an error with:

import GHC.Enum(toEnumError)

instance Enum Suit where
        succ Spades = Hearts
        succ Hearts = Diamonds
        succ Diamonds = Clubs
        succ Clubs = Spades
        pred Clubs = Diamonds
        pred Diamonds = Hearts
        pred Hearts = Spades
        pred Spades = Clubs
        fromEnum Spades = 1
        fromEnum Hearts = 2
        fromEnum Diamonds = 3
        fromEnum Clubs = 4
        toEnum 4 = Clubs
        toEnum 3 = Diamonds
        toEnum 2 = Hearts
        toEnum 1 = Spades
        toEnum n = toEnumError "Suit" n (minBound :: Suit, maxBound)

Furthermore you better use values between 0 and 3, especially since later you use n `div` 4, which is a value between 0 and 3. So:

import GHC.Enum(toEnumError)

instance Enum Suit where
        succ Spades = Hearts
        succ Hearts = Diamonds
        succ Diamonds = Clubs
        succ Clubs = Spades
        pred Clubs = Diamonds
        pred Diamonds = Hearts
        pred Hearts = Spades
        pred Spades = Clubs
        fromEnum Spades = 0
        fromEnum Hearts = 1
        fromEnum Diamonds = 2
        fromEnum Clubs = 3
        toEnum 0 = Spades
        toEnum 1 = Hearts
        toEnum 2 = Diamonds
        toEnum 3 = Clubs
        toEnum n = toEnumError "Suit" n (minBound :: Suit, maxBound)