问:
How to check if a class has a specific base class in Matlab
I define in Matlab a class that's a subclass of another one, like this:

```<code>classdef SpecificLimit < BaseLimit

  % Private properties section
  properties (SetAccess = private, GetAccess = private)
    options;
  end

  % Public section
  methods (Access = public)
    % ...
  end
end
</code>```

Now I've a variable named r and I want to check if this variable is a class instance that has BaseLimit as base class (I've a lot of them). Is there an easy way to do that? I've read about meta.class but I didn't find a way to perform this check.

I'm using Matlab r2014a.

答:
You can use the function superclasses

Something like:

```<code> any ( strcmp ( superclasses ( 'SpecificLimit' ), 'BaseLimit' ) )
</code>```

Body:
I define in Matlab a class that's a subclass of another one, like this:

classdef SpecificLimit < BaseLimit

  % Private properties section
  properties (SetAccess = private, GetAccess = private)
    options;
  end

  % Public section
  methods (Access = public)
    % ...
  end
end

Now I've a variable named r and I want to check if this variable is a class instance that has BaseLimit as base class (I've a lot of them). Is there an easy way to do that? I've read about meta.class but I didn't find a way to perform this check.

I'm using Matlab r2014a.

Body:
You can use the function superclasses

Something like:

 any ( strcmp ( superclasses ( 'SpecificLimit' ), 'BaseLimit' ) )


来源: stackexchange

问:
Should Java finalizer really be avoided also for native peer objects lifecycle management?
In my experience as a C++/Java/Android developer, I have come to learn that finalizers are almost always a bad idea, the only exception being the management of a "native peer" object needed by the java one to call C/C++ code through JNI.

I am aware of the JNI: Properly manage the lifetime of a java object question, but this question addresses the reasons not to use a finalizer anyway, neither for native peers. So it's a question/discussion on a confutation of the answers in the aforementioned question.

Joshua Bloch in his Effective Java explicitly lists this case as an exception to his famous advice on not using finalizers:

A second legitimate use of finalizers concerns objects with native peers. A native peer is a native object to which a normal object delegates via native methods. Because a native peer is not a normal object, the garbage collector doesn't know about it and can’t reclaim it when its Java peer is reclaimed. A finalizer is an appropriate vehicle for performing this task, assuming the native peer holds no critical resources. If the native peer holds resources that must be terminated promptly, the class should have an explicit termination method, as described above. The termination method should do whatever is required to free the critical resource. The termination method can be a native method, or it can invoke one.

(Also see "Why is the finalized method included in Java?" question on stackexchange)

Then I watched the really interesting How to manage native memory in Android talk at the Google I/O '17, where Hans Boehm actually advocates against using finalizers to manage native peers of a java object, also citing Effective Java as a reference. After quickly mentioning why explicit delete of the native peer or automatic closing based on scope might not be a viable alternative, he advises using java.lang.ref.PhantomReference instead.

He makes some interesting points, but I am not completely convinced. I will try to run through some of them and state my doubts, hoping someone can shed further light on them.

Starting from this example:

class BinaryPoly {

    long mNativeHandle; // holds a c++ raw pointer

    private BinaryPoly(long nativeHandle) {
        mNativeHandle = nativeHandle;
    }

    private static native long nativeMultiply(long xCppPtr, long yCppPtr);

    BinaryPoly multiply(BinaryPoly other) {
        return new BinaryPoly ( nativeMultiply(mNativeHandle, other.mNativeHandler) );
    }

    // …

    static native void nativeDelete (long cppPtr);

    protected void finalize() {
        nativeDelete(mNativeHandle);
    }
}
```
<p>Where a java class holds a reference to a native peer that gets deleted in the finalizer method, Bloch lists the shortcomings of such an approach.</p>
<p><strong>Finalizers can run in arbitrary order</strong></p>
<blockquote>
<p>If two objects become unreachable, the finalizers actually run in arbitrary order, that includes the case when two objects who point to each others become unreachable at the same time they can be finalized in the wrong order, meaning that the second one to be finalized actually tries to access an object that’s already been finalized. [...] As a result of that you can get dangling pointers and see deallocated c++ objects [...]</p>
</blockquote>
<p>And as an example:</p>
<pre class="lang-java prettyprint-override"><code>class SomeClass {
    BinaryPoly mMyBinaryPoly:
    …
    // DEFINITELY DON’T DO THIS WITH CURRENT BinaryPoly!
    protected void finalize() {
        Log.v(“BPC”, “Dropped + … + myBinaryPoly.toString());
    }
}
</code>```

Ok, but isn't this true also if myBinaryPoly is a pure Java object? As I understand it , the problem comes from operating on a possibly finalized object  inside its owner's finalizer. In case we are only using the finalizer of an object to delete its own private native peer and not doing anything else, we should be fine, right?

Finalizer may be invoked while the native method is till running

By Java rules, but not currently on Android:

Object x’s finalizer may be invoked while one of x’s methods is still running, and accessing the native object.

Pseudo-code of what multiply() gets compiled to is shown to explain this:

BinaryPoly multiply(BinaryPoly other) {
    long tmpx = this.mNativeHandle; // last use of “this”
    long tmpy = other.mNativeHandle; // last use of other
    BinaryPoly result = new BinaryPoly();
    // GC happens here. “this” and “other” can be reclaimed and finalized.
    // tmpx and tmpy are still needed. But finalizer can delete tmpx and tmpy here!
    result.mNativeHandle = nativeMultiply(tmpx, tmpy)
    return result;
}
```
<p>This is scary, and I am actually relieved this doesn't happen on android, because what I understand is that <code>this</code> and <code>other</code> get garbage collected before they go out of scope! This is even weirder considering that <code>this</code> is the object the method is called on, and that <code>other</code> is the argument of the method, so they both should already "be alive" in the scope where the method is being called.</p>
<p>A quick workaround to this would be to call some dummy methods on both <code>this</code> and <code>other</code> (ugly!), or passing them to the native method (where we can then retrieve the <code>mNativeHandle</code> and operate on it). And wait... <code>this</code> is already by default one of the arguments of the native method!</p>
```JNIEXPORT void JNICALL Java_package_BinaryPoly_multiply
(JNIEnv* env, jobject thiz, jlong xPtr, jlong yPtr) {}
```

How can this be possibly garbage collected?

Finalizers can be deferred for too long

“For this to work correctly, if you run an application that allocates lots of native memory and relatively little java memory it may actually not be the case that the garbage collector runs promptly enough to actually invoke finalizers [...] so you actually may have to invoke System.gc() and System.runFinalization() occasionally, which is tricky to do [...]”

If the native peer is only seen by a single java object which it is tied to, isn’t this fact transparent to the rest of the system, and thus the GC should just have to manage the lifecycle of the Java object as it was a pure java one? There's clearly something I fail to see here.

Finalizers can actually extend the lifetime of the java object

[...] Sometimes finalizers actually extend the lifetime of the java object for another garbage collection cycle, which means for generational garbage collectors they may actually cause it to survive into the old generation and the lifetime may be greatly extended as a result of just having a finalizer.

I admit I don't really get what's the issue here and how it relates to having a native peer, I will make some research and possibly update the question :)

In conclusion

For now, I still believe that using a sort of RAII approach were the native peer is created in the java object's constructor and deleted in the finalize method is not actually dangerous, provided that:

the native peer doesn't hold any critical resource (in that case there should be a separate method to release the resource, the native peer must only act as the the java object "counterpart" in the native realm)

the native peer doesn't span threads or do weird concurrent stuff in its destructor (who would want to do that?!?)

the native peer pointer is never shared outside the java object, only belongs to a single instance, and only accessed inside the java object's methods. On Android, a java object may access the native peer of another instance of the same class, right before calling a jni method accepting different native peers or, better, just passing the java objects to the native method itself

the java object's finalizer only deletes its own native peer, and does nothing else

Is there any other restriction that should be added, or there's really no way to ensure that a finalizer is safe even with all restrictions being respected?

答:
My own take is that one should release native objects as soon as you are done with them, in a deterministic fashion. As such, using scope to manage them is preferable to relying on the finalizer.  You can use the finalizer to cleanup as a last resort, but, i would not use solely to manage the actual lifetime for the reasons you actually pointed out in your own question.

As such, let the finalizer be the final attempt, but not the first.

ContentLicense: CC BY-SA 4.0

Body:
In my experience as a C++/Java/Android developer, I have come to learn that finalizers are almost always a bad idea, the only exception being the management of a "native peer" object needed by the java one to call C/C++ code through JNI.

I am aware of the JNI: Properly manage the lifetime of a java object question, but this question addresses the reasons not to use a finalizer anyway, neither for native peers. So it's a question/discussion on a confutation of the answers in the aforementioned question.

Joshua Bloch in his Effective Java explicitly lists this case as an exception to his famous advice on not using finalizers:

A second legitimate use of finalizers concerns objects with native peers. A native peer is a native object to which a normal object delegates via native methods. Because a native peer is not a normal object, the garbage collector doesn't know about it and can’t reclaim it when its Java peer is reclaimed. A finalizer is an appropriate vehicle for performing this task, assuming the native peer holds no critical resources. If the native peer holds resources that must be terminated promptly, the class should have an explicit termination method, as described above. The termination method should do whatever is required to free the critical resource. The termination method can be a native method, or it can invoke one.

(Also see "Why is the finalized method included in Java?" question on stackexchange)

Then I watched the really interesting How to manage native memory in Android talk at the Google I/O '17, where Hans Boehm actually advocates against using finalizers to manage native peers of a java object, also citing Effective Java as a reference. After quickly mentioning why explicit delete of the native peer or automatic closing based on scope might not be a viable alternative, he advises using java.lang.ref.PhantomReference instead.

He makes some interesting points, but I am not completely convinced. I will try to run through some of them and state my doubts, hoping someone can shed further light on them.

Starting from this example:

class BinaryPoly {

    long mNativeHandle; // holds a c++ raw pointer

    private BinaryPoly(long nativeHandle) {
        mNativeHandle = nativeHandle;
    }

    private static native long nativeMultiply(long xCppPtr, long yCppPtr);

    BinaryPoly multiply(BinaryPoly other) {
        return new BinaryPoly ( nativeMultiply(mNativeHandle, other.mNativeHandler) );
    }

    // …

    static native void nativeDelete (long cppPtr);

    protected void finalize() {
        nativeDelete(mNativeHandle);
    }
}

Where a java class holds a reference to a native peer that gets deleted in the finalizer method, Bloch lists the shortcomings of such an approach.

Finalizers can run in arbitrary order

If two objects become unreachable, the finalizers actually run in arbitrary order, that includes the case when two objects who point to each others become unreachable at the same time they can be finalized in the wrong order, meaning that the second one to be finalized actually tries to access an object that’s already been finalized. [...] As a result of that you can get dangling pointers and see deallocated c++ objects [...]

And as an example:

class SomeClass {
    BinaryPoly mMyBinaryPoly:
    …
    // DEFINITELY DON’T DO THIS WITH CURRENT BinaryPoly!
    protected void finalize() {
        Log.v(“BPC”, “Dropped + … + myBinaryPoly.toString());
    }
}

Ok, but isn't this true also if myBinaryPoly is a pure Java object? As I understand it , the problem comes from operating on a possibly finalized object  inside its owner's finalizer. In case we are only using the finalizer of an object to delete its own private native peer and not doing anything else, we should be fine, right?

Finalizer may be invoked while the native method is till running

By Java rules, but not currently on Android:

Object x’s finalizer may be invoked while one of x’s methods is still running, and accessing the native object.

Pseudo-code of what multiply() gets compiled to is shown to explain this:

BinaryPoly multiply(BinaryPoly other) {
    long tmpx = this.mNativeHandle; // last use of “this”
    long tmpy = other.mNativeHandle; // last use of other
    BinaryPoly result = new BinaryPoly();
    // GC happens here. “this” and “other” can be reclaimed and finalized.
    // tmpx and tmpy are still needed. But finalizer can delete tmpx and tmpy here!
    result.mNativeHandle = nativeMultiply(tmpx, tmpy)
    return result;
}

This is scary, and I am actually relieved this doesn't happen on android, because what I understand is that this and other get garbage collected before they go out of scope! This is even weirder considering that this is the object the method is called on, and that other is the argument of the method, so they both should already "be alive" in the scope where the method is being called.

A quick workaround to this would be to call some dummy methods on both this and other (ugly!), or passing them to the native method (where we can then retrieve the mNativeHandle and operate on it). And wait... this is already by default one of the arguments of the native method!

JNIEXPORT void JNICALL Java_package_BinaryPoly_multiply
(JNIEnv* env, jobject thiz, jlong xPtr, jlong yPtr) {}

How can this be possibly garbage collected?

Finalizers can be deferred for too long

“For this to work correctly, if you run an application that allocates lots of native memory and relatively little java memory it may actually not be the case that the garbage collector runs promptly enough to actually invoke finalizers [...] so you actually may have to invoke System.gc() and System.runFinalization() occasionally, which is tricky to do [...]”

If the native peer is only seen by a single java object which it is tied to, isn’t this fact transparent to the rest of the system, and thus the GC should just have to manage the lifecycle of the Java object as it was a pure java one? There's clearly something I fail to see here.

Finalizers can actually extend the lifetime of the java object

[...] Sometimes finalizers actually extend the lifetime of the java object for another garbage collection cycle, which means for generational garbage collectors they may actually cause it to survive into the old generation and the lifetime may be greatly extended as a result of just having a finalizer.

I admit I don't really get what's the issue here and how it relates to having a native peer, I will make some research and possibly update the question :)

In conclusion

For now, I still believe that using a sort of RAII approach were the native peer is created in the java object's constructor and deleted in the finalize method is not actually dangerous, provided that:

the native peer doesn't hold any critical resource (in that case there should be a separate method to release the resource, the native peer must only act as the the java object "counterpart" in the native realm)

the native peer doesn't span threads or do weird concurrent stuff in its destructor (who would want to do that?!?)

the native peer pointer is never shared outside the java object, only belongs to a single instance, and only accessed inside the java object's methods. On Android, a java object may access the native peer of another instance of the same class, right before calling a jni method accepting different native peers or, better, just passing the java objects to the native method itself

the java object's finalizer only deletes its own native peer, and does nothing else

Is there any other restriction that should be added, or there's really no way to ensure that a finalizer is safe even with all restrictions being respected?

ContentLicense: CC BY-SA 3.0


问:
Error when trying to RSA-decrypt a parameter string with libcrypto
I am a beginner with the libcrypto library. I am trying to give an encrypted string to a function, decrypt it and return it decrypted. The string is encoded with my public key which which is 4096-bit sized.

```<code>char* decodeStr(const char* str, const size_t sizeStr)
{
    puts("Starting");
    FILE* file = fopen(PRIVATE_KEY_PATH, "r");
    if (file == NULL)
    {
        perror("Error while trying to access to Presto's private key.\n");
        return NULL;
    }

    RSA *privateKey = RSA_new();
    privateKey = PEM_read_RSAPrivateKey(file, &privateKey, NULL, NULL);
    if (privateKey == NULL)
    {
        fprintf(stderr, "Error loading RSA private key.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    char* res = malloc(sizeStr);
    if (res == NULL)
    {
        perror("Memory allocating error ");
        return NULL;
    }
    const int sizeDecoded = RSA_private_decrypt(sizeStr, str, res, privateKey, RSA_PKCS1_PADDING);
    if (sizeDecoded == -1)
    {
        fprintf(stderr, "Error while decoding RSA-encoded wrapping key.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    if ((res = realloc(res, (size_t)sizeDecoded)) == NULL)
    {
        perror("Memory allocating error ");
        return NULL;
    }
    return res;

}
</code>```

The following code outputs :

```<code>Starting
Error while decoding RSA-encoded wrapping key.
6928:error;04069506C:lib<4>:func<101>:reason<108>:.\crypto\rsa\rsa_eay.c:518:
</code>```

Since the error is unknown and I haven't been able to find any information about it on the net, and moreover I am a beginner with libcrypto, does strneed to be in a certain format ?

Obivously it is this which breaks the program but I can't be sure of it, neither do I know how to fix this.

```<code>const int sizeDecoded = RSA_private_decrypt(sizeStr, str, res, privateKey, RSA_PKCS1_PADDING);
</code>```

EDIT : I have been working with a client  which provides me those encoded dat for me to decrypt them. I don't know how they are processed exactly. Unfortunately, the encoded strings are even more sensitive than the private key itself, so I can't share it. It looks like 0c79cc00deb89a614db6ebe42be748219089fb5356 but with 1024 characters.

答:
The problem

Your encoded strings

0c79cc00deb89a614db6ebe42be748219089fb5356 but with thousands of characters.

look like hexadecimal representation of the encoded message. I think you really need to convert the message to a raw data, converting hex to bytes.

Your strings are composed by 1024 (hex) chars => 512 bytes (you need two hex digits to represent one byte) => 4096 bits, which is equal to the key length.

Try this simple function.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

void hex_2_bytes(uint8_t *des, char *source, size_t size);

int main()
{
                char *str = "0c79cc00deb89a614db6ebe42be748219089fb5356";
                uint8_t *dest = (uint8_t *) malloc(sizeof(uint8_t) * strlen(str) / 2);
                hex_2_bytes(dest, str, strlen(str));
                for(int i = 0; i < strlen(str) / 2; i++) {
                                printf(" %02X ", dest[i]);
                }
                return 0;
}

void hex_2_bytes(uint8_t *des, char *source, size_t size) {
                for(int i = 0; i < size - 1; i+=2) {
                                sscanf(source+i, "%02x", des + (i/2));
                }
}
</code>```

What is raw data? Your encrypted message is a string, which is an array of characters. I see only digits (from 0 to 9) and the letters from a to f, which make me guess that your original message (which is, originally a binary string, raw data) has been represented as a very long number using hexadecimal digits. You need to convert it back.

If you have a message composed by n bytes, stored as a binary string (raw data), you will have an hexadecimal representation, stored as a text, which is 2*n bytes long.

Example:

```<code>uint8_t raw_data_message[] = {0x3c, 0x2f};  // 2 bytes
char hex_representation_as_string_message[] = {'3', 'c', '2', 'f'}; // 4 bytes
</code>```

Your messages a like hex_representation_as_string_message, but you need them as raw_data_message.

The solution

Here's a fully working example:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <openssl/pem.h>
#include <openssl/err.h>

#define PRIVATE_KEY_PATH ".ssh/id_rsa"

/*
 * Generation of the encrypted message:
 * echo "Hello, this is a super secret message" | openssl rsautl -encrypt -pubin -inkey ~/.ssh/id_rsa.pub.pem >message.encrypted
 *
 * Resulting encrypted message in hex representation:
 * 917ab2ebd663bba1dcd0f22aef98b93b039f001e19c997f015d90eaaf35731eb1895c13dfb08250aa28a9dac4f3e1b5fefc53926d3f6422f8055124bb15c24e2b73645dc61f29486deaf278705987738e916a6288531aa923dff15b667dabf4465506e1ee68e6f27a06e3fb4f5040a7775ce69ba10ec337f5bc5ef45969a8fe7c672c9b51243296677385f1b613f4f3edceef620f6ab5dcadec5034c330331bf8e8c3b42554f01c6cf1c0dbc58f23c8f0068e750fc4bb97636b2b3455e7f3932ab9559ff4de5bfc6769bbafefec722441458066ab4a6fdfe99c78bfdd5c1851d411a451925c5ad7ecb0c93618304ae6bc5402193f58af6e6a65208075be35a00
 * (converted with: hexdump -ve '1/1 "%.2x"' message.encrypted)
 */

void hex_2_bytes (uint8_t *des, char *source, size_t size);

int decode (uint8_t *dest, const uint8_t *src, const size_t size);

int main (int argc, char **argv) {
    // Reading the encrypted message in hex representation
    FILE *file = fopen(argv[1], "r");
    printf("%s\n", argv[1]);
    if (file == NULL) {
        perror("Error while trying to access to the encrypted message"
                       ".\n");
        return -1;
    }
    fseek(file, 0, SEEK_END);
    long fsize = ftell(file);
    fseek(file, 0, SEEK_SET);
    char *hex_repr = malloc(fsize);
    fread(hex_repr, fsize, 1, file);
    fclose(file);

    printf("Hexadecimal representation of the encrypted message\n");
    for (int i = 0; i < fsize; ++i) {
        printf("%c", hex_repr[i]);
    }
    printf("\nSize: %d\n", fsize);

    // Converting to raw data
    size_t raw_data_size = fsize / 2;
    uint8_t *raw_data = (uint8_t *) malloc(
            raw_data_size * sizeof(uint8_t));
    hex_2_bytes(raw_data, hex_repr, (size_t) fsize);
    printf("Raw encrypted message\n");
    for (int i = 0; i < raw_data_size; ++i) {
        printf("%02X", raw_data[i]);
    }
    printf("\nSize: %d\n", raw_data_size);

    // Decryption
    char *res = malloc(raw_data_size * sizeof(char));
    if (res == NULL) {
        perror("Memory allocating error ");
        return -1;
    }
    int msg_size = decode(res, raw_data, raw_data_size);
    printf("Decrypted message:\n");
    for (int j = 0; j < msg_size; ++j) {
        printf("%c", res[j]);
    }
    printf("\nSize: %d\n", msg_size);

    return 0;
}

void hex_2_bytes (uint8_t *des, char *source, size_t size) {
    for (int i = 0; i < size - 1; i += 2) {
        sscanf(source + i, "%02x", des + (i / 2));
    }
}

int decode (uint8_t *res, const uint8_t *src, const size_t size) {
    puts("Starting");
    FILE *file = fopen(PRIVATE_KEY_PATH, "r");
    if (file == NULL) {
        perror("Error while trying to access to Presto's private key.\n");
        return -1;
    }

    RSA *privateKey = RSA_new();
    privateKey = PEM_read_RSAPrivateKey(file, &privateKey, NULL, NULL);
    if (privateKey == NULL) {
        fprintf(stderr, "Error loading RSA private key.\n");
        ERR_print_errors_fp(stderr);
        return -1;
    }
    const int sizeDecoded = RSA_private_decrypt(size, src, res,
                                                privateKey,
                                                RSA_PKCS1_PADDING);
    if (sizeDecoded == -1) {
        fprintf(stderr,
                "Error while decoding RSA-encoded wrapping key.\n");
        ERR_print_errors_fp(stderr);
        return -1;
    }
    return sizeDecoded;
}
</code>```

And the results (as a proof of work):

Note that I'm using 2048 bit rsa keys.

Body:
I am a beginner with the libcrypto library. I am trying to give an encrypted string to a function, decrypt it and return it decrypted. The string is encoded with my public key which which is 4096-bit sized.

char* decodeStr(const char* str, const size_t sizeStr)
{
    puts("Starting");
    FILE* file = fopen(PRIVATE_KEY_PATH, "r");
    if (file == NULL)
    {
        perror("Error while trying to access to Presto's private key.\n");
        return NULL;
    }

    RSA *privateKey = RSA_new();
    privateKey = PEM_read_RSAPrivateKey(file, &privateKey, NULL, NULL);
    if (privateKey == NULL)
    {
        fprintf(stderr, "Error loading RSA private key.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    char* res = malloc(sizeStr);
    if (res == NULL)
    {
        perror("Memory allocating error ");
        return NULL;
    }
    const int sizeDecoded = RSA_private_decrypt(sizeStr, str, res, privateKey, RSA_PKCS1_PADDING);
    if (sizeDecoded == -1)
    {
        fprintf(stderr, "Error while decoding RSA-encoded wrapping key.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    if ((res = realloc(res, (size_t)sizeDecoded)) == NULL)
    {
        perror("Memory allocating error ");
        return NULL;
    }
    return res;

}

The following code outputs :

Starting
Error while decoding RSA-encoded wrapping key.
6928:error;04069506C:lib<4>:func<101>:reason<108>:.\crypto\rsa\rsa_eay.c:518:

Since the error is unknown and I haven't been able to find any information about it on the net, and moreover I am a beginner with libcrypto, does strneed to be in a certain format ?

Obivously it is this which breaks the program but I can't be sure of it, neither do I know how to fix this.

const int sizeDecoded = RSA_private_decrypt(sizeStr, str, res, privateKey, RSA_PKCS1_PADDING);

EDIT : I have been working with a client  which provides me those encoded dat for me to decrypt them. I don't know how they are processed exactly. Unfortunately, the encoded strings are even more sensitive than the private key itself, so I can't share it. It looks like 0c79cc00deb89a614db6ebe42be748219089fb5356 but with 1024 characters.

Body:
The problem

Your encoded strings

0c79cc00deb89a614db6ebe42be748219089fb5356 but with thousands of characters.

look like hexadecimal representation of the encoded message. I think you really need to convert the message to a raw data, converting hex to bytes.

Your strings are composed by 1024 (hex) chars => 512 bytes (you need two hex digits to represent one byte) => 4096 bits, which is equal to the key length.

Try this simple function.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

void hex_2_bytes(uint8_t *des, char *source, size_t size);

int main()
{
                char *str = "0c79cc00deb89a614db6ebe42be748219089fb5356";
                uint8_t *dest = (uint8_t *) malloc(sizeof(uint8_t) * strlen(str) / 2);
                hex_2_bytes(dest, str, strlen(str));
                for(int i = 0; i < strlen(str) / 2; i++) {
                                printf(" %02X ", dest[i]);
                }
                return 0;
}

void hex_2_bytes(uint8_t *des, char *source, size_t size) {
                for(int i = 0; i < size - 1; i+=2) {
                                sscanf(source+i, "%02x", des + (i/2));
                }
}

What is raw data? Your encrypted message is a string, which is an array of characters. I see only digits (from 0 to 9) and the letters from a to f, which make me guess that your original message (which is, originally a binary string, raw data) has been represented as a very long number using hexadecimal digits. You need to convert it back.

If you have a message composed by n bytes, stored as a binary string (raw data), you will have an hexadecimal representation, stored as a text, which is 2*n bytes long.

Example:

uint8_t raw_data_message[] = {0x3c, 0x2f};  // 2 bytes
char hex_representation_as_string_message[] = {'3', 'c', '2', 'f'}; // 4 bytes

Your messages a like hex_representation_as_string_message, but you need them as raw_data_message.

The solution

Here's a fully working example:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <openssl/pem.h>
#include <openssl/err.h>

#define PRIVATE_KEY_PATH ".ssh/id_rsa"

/*
 * Generation of the encrypted message:
 * echo "Hello, this is a super secret message" | openssl rsautl -encrypt -pubin -inkey ~/.ssh/id_rsa.pub.pem >message.encrypted
 *
 * Resulting encrypted message in hex representation:
 * 917ab2ebd663bba1dcd0f22aef98b93b039f001e19c997f015d90eaaf35731eb1895c13dfb08250aa28a9dac4f3e1b5fefc53926d3f6422f8055124bb15c24e2b73645dc61f29486deaf278705987738e916a6288531aa923dff15b667dabf4465506e1ee68e6f27a06e3fb4f5040a7775ce69ba10ec337f5bc5ef45969a8fe7c672c9b51243296677385f1b613f4f3edceef620f6ab5dcadec5034c330331bf8e8c3b42554f01c6cf1c0dbc58f23c8f0068e750fc4bb97636b2b3455e7f3932ab9559ff4de5bfc6769bbafefec722441458066ab4a6fdfe99c78bfdd5c1851d411a451925c5ad7ecb0c93618304ae6bc5402193f58af6e6a65208075be35a00
 * (converted with: hexdump -ve '1/1 "%.2x"' message.encrypted)
 */

void hex_2_bytes (uint8_t *des, char *source, size_t size);

int decode (uint8_t *dest, const uint8_t *src, const size_t size);

int main (int argc, char **argv) {
    // Reading the encrypted message in hex representation
    FILE *file = fopen(argv[1], "r");
    printf("%s\n", argv[1]);
    if (file == NULL) {
        perror("Error while trying to access to the encrypted message"
                       ".\n");
        return -1;
    }
    fseek(file, 0, SEEK_END);
    long fsize = ftell(file);
    fseek(file, 0, SEEK_SET);
    char *hex_repr = malloc(fsize);
    fread(hex_repr, fsize, 1, file);
    fclose(file);

    printf("Hexadecimal representation of the encrypted message\n");
    for (int i = 0; i < fsize; ++i) {
        printf("%c", hex_repr[i]);
    }
    printf("\nSize: %d\n", fsize);

    // Converting to raw data
    size_t raw_data_size = fsize / 2;
    uint8_t *raw_data = (uint8_t *) malloc(
            raw_data_size * sizeof(uint8_t));
    hex_2_bytes(raw_data, hex_repr, (size_t) fsize);
    printf("Raw encrypted message\n");
    for (int i = 0; i < raw_data_size; ++i) {
        printf("%02X", raw_data[i]);
    }
    printf("\nSize: %d\n", raw_data_size);

    // Decryption
    char *res = malloc(raw_data_size * sizeof(char));
    if (res == NULL) {
        perror("Memory allocating error ");
        return -1;
    }
    int msg_size = decode(res, raw_data, raw_data_size);
    printf("Decrypted message:\n");
    for (int j = 0; j < msg_size; ++j) {
        printf("%c", res[j]);
    }
    printf("\nSize: %d\n", msg_size);

    return 0;
}

void hex_2_bytes (uint8_t *des, char *source, size_t size) {
    for (int i = 0; i < size - 1; i += 2) {
        sscanf(source + i, "%02x", des + (i / 2));
    }
}

int decode (uint8_t *res, const uint8_t *src, const size_t size) {
    puts("Starting");
    FILE *file = fopen(PRIVATE_KEY_PATH, "r");
    if (file == NULL) {
        perror("Error while trying to access to Presto's private key.\n");
        return -1;
    }

    RSA *privateKey = RSA_new();
    privateKey = PEM_read_RSAPrivateKey(file, &privateKey, NULL, NULL);
    if (privateKey == NULL) {
        fprintf(stderr, "Error loading RSA private key.\n");
        ERR_print_errors_fp(stderr);
        return -1;
    }
    const int sizeDecoded = RSA_private_decrypt(size, src, res,
                                                privateKey,
                                                RSA_PKCS1_PADDING);
    if (sizeDecoded == -1) {
        fprintf(stderr,
                "Error while decoding RSA-encoded wrapping key.\n");
        ERR_print_errors_fp(stderr);
        return -1;
    }
    return sizeDecoded;
}

And the results (as a proof of work):

Note that I'm using 2048 bit rsa keys.


问:
Taking an expression as an argument in Julia function
I'm trying to implement OLS regression in Julia as a learning exercise. A feature I would like to have is excepting a formula as an argument (e.g. 'formula = Y ~ x1 + x2', where Y, x1, and x2 are columns in a DataFrame). Here is an existing example.

How do I "map" the formula/expression to the correct DataFrame columns?

答:
Here's a minimal example using the boston dataset from ISLR, regressing medv on lstat. (Check pg. 111 of ISLR if you want verify that the weight vector is correct)

```<code>julia> using DataFrames, RDatasets
julia> df = dataset("MASS", "Boston")
julia> fm = @formula(MedV ~ LStat)

julia> mf = ModelFrame(fm, df)
julia> X = ModelMatrix(mf).m
julia> y = Array(df[:MedV])
julia> w = X \ y

2-element Array{Float64,1}:
34.5538
-0.950049
</code>```

For more information: http://dataframesjl.readthedocs.io/en/latest/formulas.html

Body:
Here's a minimal example using the boston dataset from ISLR, regressing medv on lstat. (Check pg. 111 of ISLR if you want verify that the weight vector is correct)

julia> using DataFrames, RDatasets
julia> df = dataset("MASS", "Boston")
julia> fm = @formula(MedV ~ LStat)

julia> mf = ModelFrame(fm, df)
julia> X = ModelMatrix(mf).m
julia> y = Array(df[:MedV])
julia> w = X \ y

2-element Array{Float64,1}:
34.5538
-0.950049

For more information: http://dataframesjl.readthedocs.io/en/latest/formulas.html


问:
iphone - stuff inside alertview
I have a part on my app that I show the users, the files they have created and have stored inside the app's directory. I want to allow the users to rename the files.

I am wondering of doing this:

The user selects a file

The user taps on the RENAME button.

An alertview pops showing the old name and having a textview where the user can type the new name.

My question is: is this blessed by Apple? This sounds like a hack to the alertview.

Will the app be approved?

I googled around and I saw mixed opinions about that.

thanks

答:
Yes it is in iPhone sdk alertBox, alertBox can have the textField in which you rename the file.

check this link

for making such kind of stuff. No problem in accepting your app

ContentLicense: CC BY-SA 2.5

Title: iphone - stuff inside alertview


问:
Undefined variable sent from Ajax to MVC Controller
I have a method where my users can change their password,to a new one,requiring 2 variables,one is the new password,and the other,the repetition of the password.The thing is that when i call the method, it returns the string "undefined",and uses that string as the new password,saving it on the db.
Can someone tell me what I'm doing wrong?
Controller:

```<code> [HttpPost]
    public JsonResult ChangePwdEnt(string pwd, string repeatpwd)
    {
        if (pwd == null || repeatpwd == null)
        {
            ViewBag.Error = "Insira os campos obrigatórios";
        }
        else
        {
            if (pwd == repeatpwd)
            {
                changePwd_Entidades(Session["ID"].ToString(),pwd);
                return Json(true,JsonRequestBehavior.DenyGet);
            }
            else
            {
                ViewBag.Error = "As palavras chave precisam de ser iguais";
            }
        }

        return Json(false, JsonRequestBehavior.DenyGet);
    }
</code>```

Script:

```<code><script>

$('.alt-btn').on('click', function () {

    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: '@Url.Action("ChangePwdEnt", "Home")?pwd=' +
        $('#Info_pwd').val() + '&repeatpwd=' + $('#Info_repeatpwd').val(),

        error: function (e) {
            console.log(e);
        },

        success: function (Changed) {
            if (Changed) {
                window.location = "Entidades";
            } else if (!Changed) {
                window.location = "LoginEntidades";
            }
        }
    });
});
</code>```

答:
I think you are  using incorrect id to get value of password field.

And instead of sending both password to code better approach would be just compare your both password values at client side and if they both are same then parse those values to code side other wise ask user to input  same password .

Body:
I have a method where my users can change their password,to a new one,requiring 2 variables,one is the new password,and the other,the repetition of the password.The thing is that when i call the method, it returns the string "undefined",and uses that string as the new password,saving it on the db.
Can someone tell me what I'm doing wrong?
Controller:

 [HttpPost]
    public JsonResult ChangePwdEnt(string pwd, string repeatpwd)
    {
        if (pwd == null || repeatpwd == null)
        {
            ViewBag.Error = "Insira os campos obrigatórios";
        }
        else
        {
            if (pwd == repeatpwd)
            {
                changePwd_Entidades(Session["ID"].ToString(),pwd);
                return Json(true,JsonRequestBehavior.DenyGet);
            }
            else
            {
                ViewBag.Error = "As palavras chave precisam de ser iguais";
            }
        }

        return Json(false, JsonRequestBehavior.DenyGet);
    }

Script:


问:
Undo-Redo feature in Fabric.js
Is there any built-in support for for undo/redo in Fabric.js? Can you please guide me on how you used this cancel and repeat in [http://printio.ru/][1]</p>

答:
I know its late to answer this but this is my version of implementing this. Can be useful to someone.

I have implemented this feature by saving Canvas States as JSON. Whenever a user adds or modifies an object in the Canvas, it will save the changed canvas state and maintain it in an array. This array is then manipulated whenever user clicks on Undo or Redo button.

Take a look at this link. I have also provided a working Demo URL.

https://github.com/abhi06991/Undo-Redo-Fabricjs

HTML:

```<code><canvas id="canvas" width="400" height="400"></canvas>
<button type="button" id="undo" >Undo</button>
<button type="button" id="redo" disabled>Redo</button>
</code>```

JS:

```<code>var canvasDemo = (function(){
  var _canvasObject = new fabric.Canvas('canvas',{backgroundColor : "#f5deb3"});
    var _config = {
        canvasState             : [],
        currentStateIndex       : -1,
        undoStatus              : false,
        redoStatus              : false,
        undoFinishedStatus      : 1,
        redoFinishedStatus      : 1,
    undoButton              : document.getElementById('undo'),
        redoButton              : document.getElementById('redo'),
    };
    _canvasObject.on(
        'object:modified', function(){
            updateCanvasState();
        }
    );

  _canvasObject.on(
        'object:added', function(){
            updateCanvasState();
        }
    );

  var addObject = function(){
     var rect = new fabric.Rect({
            left   : 100,
            top    : 100,
            fill   : 'red',
            width  : 200,
            height : 200
    });
        _canvasObject.add(rect);
        _canvasObject.setActiveObject(rect);
    _canvasObject.renderAll();
  }

    var updateCanvasState = function() {
        if((_config.undoStatus == false && _config.redoStatus == false)){
            var jsonData        = _canvasObject.toJSON();
            var canvasAsJson        = JSON.stringify(jsonData);
            if(_config.currentStateIndex < _config.canvasState.length-1){
                var indexToBeInserted                  = _config.currentStateIndex+1;
                _config.canvasState[indexToBeInserted] = canvasAsJson;
                var numberOfElementsToRetain           = indexToBeInserted+1;
                _config.canvasState                    = _config.canvasState.splice(0,numberOfElementsToRetain);
            }else{
            _config.canvasState.push(canvasAsJson);
            }
        _config.currentStateIndex = _config.canvasState.length-1;
      if((_config.currentStateIndex == _config.canvasState.length-1) && _config.currentStateIndex != -1){
        _config.redoButton.disabled= "disabled";
      }
        }
    }

    var undo = function() {
        if(_config.undoFinishedStatus){
            if(_config.currentStateIndex == -1){
            _config.undoStatus = false;
            }
            else{
            if (_config.canvasState.length >= 1) {
            _config.undoFinishedStatus = 0;
              if(_config.currentStateIndex != 0){
                    _config.undoStatus = true;
                  _canvasObject.loadFromJSON(_config.canvasState[_config.currentStateIndex-1],function(){
                                var jsonData = JSON.parse(_config.canvasState[_config.currentStateIndex-1]);
                            _canvasObject.renderAll();
                        _config.undoStatus = false;
                        _config.currentStateIndex -= 1;
                                _config.undoButton.removeAttribute("disabled");
                                if(_config.currentStateIndex !== _config.canvasState.length-1){
                                    _config.redoButton.removeAttribute('disabled');
                                }
                            _config.undoFinishedStatus = 1;
                });
              }
              else if(_config.currentStateIndex == 0){
                _canvasObject.clear();
                        _config.undoFinishedStatus = 1;
                        _config.undoButton.disabled= "disabled";
                        _config.redoButton.removeAttribute('disabled');
                _config.currentStateIndex -= 1;
              }
            }
            }
        }
    }

    var redo = function() {
        if(_config.redoFinishedStatus){
            if((_config.currentStateIndex == _config.canvasState.length-1) && _config.currentStateIndex != -1){
                _config.redoButton.disabled= "disabled";
            }else{
            if (_config.canvasState.length > _config.currentStateIndex && _config.canvasState.length != 0){
                    _config.redoFinishedStatus = 0;
                _config.redoStatus = true;
              _canvasObject.loadFromJSON(_config.canvasState[_config.currentStateIndex+1],function(){
                            var jsonData = JSON.parse(_config.canvasState[_config.currentStateIndex+1]);
                        _canvasObject.renderAll();
                        _config.redoStatus = false;
                    _config.currentStateIndex += 1;
                            if(_config.currentStateIndex != -1){
                                _config.undoButton.removeAttribute('disabled');
                            }
                        _config.redoFinishedStatus = 1;
            if((_config.currentStateIndex == _config.canvasState.length-1) && _config.currentStateIndex != -1){
              _config.redoButton.disabled= "disabled";
            }
              });
            }
            }
        }
    }

    return {
        addObject  : addObject,
        undoButton : _config.undoButton,
        redoButton : _config.redoButton,
        undo       : undo,
        redo       : redo,
  }

  })();

  canvasDemo.undoButton.addEventListener('click',function(){
        canvasDemo.undo();
    });

    canvasDemo.redoButton.addEventListener('click',function(){
        canvasDemo.redo();
    });
  canvasDemo.addObject();
</code>```

Title: Undo-Redo feature in Fabric.js

Body:
I know its late to answer this but this is my version of implementing this. Can be useful to someone.

I have implemented this feature by saving Canvas States as JSON. Whenever a user adds or modifies an object in the Canvas, it will save the changed canvas state and maintain it in an array. This array is then manipulated whenever user clicks on Undo or Redo button.

Take a look at this link. I have also provided a working Demo URL.

https://github.com/abhi06991/Undo-Redo-Fabricjs

HTML:

<canvas id="canvas" width="400" height="400"></canvas>
<button type="button" id="undo" >Undo</button>
<button type="button" id="redo" disabled>Redo</button>

JS:

var canvasDemo = (function(){
  var _canvasObject = new fabric.Canvas('canvas',{backgroundColor : "#f5deb3"});
    var _config = {
        canvasState             : [],
        currentStateIndex       : -1,
        undoStatus              : false,
        redoStatus              : false,
        undoFinishedStatus      : 1,
        redoFinishedStatus      : 1,
    undoButton              : document.getElementById('undo'),
        redoButton              : document.getElementById('redo'),
    };
    _canvasObject.on(
        'object:modified', function(){
            updateCanvasState();
        }
    );

  _canvasObject.on(
        'object:added', function(){
            updateCanvasState();
        }
    );

  var addObject = function(){
     var rect = new fabric.Rect({
            left   : 100,
            top    : 100,
            fill   : 'red',
            width  : 200,
            height : 200
    });
        _canvasObject.add(rect);
        _canvasObject.setActiveObject(rect);
    _canvasObject.renderAll();
  }

    var updateCanvasState = function() {
        if((_config.undoStatus == false && _config.redoStatus == false)){
            var jsonData        = _canvasObject.toJSON();
            var canvasAsJson        = JSON.stringify(jsonData);
            if(_config.currentStateIndex < _config.canvasState.length-1){
                var indexToBeInserted                  = _config.currentStateIndex+1;
                _config.canvasState[indexToBeInserted] = canvasAsJson;
                var numberOfElementsToRetain           = indexToBeInserted+1;
                _config.canvasState                    = _config.canvasState.splice(0,numberOfElementsToRetain);
            }else{
            _config.canvasState.push(canvasAsJson);
            }
        _config.currentStateIndex = _config.canvasState.length-1;
      if((_config.currentStateIndex == _config.canvasState.length-1) && _config.currentStateIndex != -1){
        _config.redoButton.disabled= "disabled";
      }
        }
    }

    var undo = function() {
        if(_config.undoFinishedStatus){
            if(_config.currentStateIndex == -1){
            _config.undoStatus = false;
            }
            else{
            if (_config.canvasState.length >= 1) {
            _config.undoFinishedStatus = 0;
              if(_config.currentStateIndex != 0){
                    _config.undoStatus = true;
                  _canvasObject.loadFromJSON(_config.canvasState[_config.currentStateIndex-1],function(){
                                var jsonData = JSON.parse(_config.canvasState[_config.currentStateIndex-1]);
                            _canvasObject.renderAll();
                        _config.undoStatus = false;
                        _config.currentStateIndex -= 1;
                                _config.undoButton.removeAttribute("disabled");
                                if(_config.currentStateIndex !== _config.canvasState.length-1){
                                    _config.redoButton.removeAttribute('disabled');
                                }
                            _config.undoFinishedStatus = 1;
                });
              }
              else if(_config.currentStateIndex == 0){
                _canvasObject.clear();
                        _config.undoFinishedStatus = 1;
                        _config.undoButton.disabled= "disabled";
                        _config.redoButton.removeAttribute('disabled');
                _config.currentStateIndex -= 1;
              }
            }
            }
        }
    }

    var redo = function() {
        if(_config.redoFinishedStatus){
            if((_config.currentStateIndex == _config.canvasState.length-1) && _config.currentStateIndex != -1){
                _config.redoButton.disabled= "disabled";
            }else{
            if (_config.canvasState.length > _config.currentStateIndex && _config.canvasState.length != 0){
                    _config.redoFinishedStatus = 0;
                _config.redoStatus = true;
              _canvasObject.loadFromJSON(_config.canvasState[_config.currentStateIndex+1],function(){
                            var jsonData = JSON.parse(_config.canvasState[_config.currentStateIndex+1]);
                        _canvasObject.renderAll();
                        _config.redoStatus = false;
                    _config.currentStateIndex += 1;
                            if(_config.currentStateIndex != -1){
                                _config.undoButton.removeAttribute('disabled');
                            }
                        _config.redoFinishedStatus = 1;
            if((_config.currentStateIndex == _config.canvasState.length-1) && _config.currentStateIndex != -1){
              _config.redoButton.disabled= "disabled";
            }
              });
            }
            }
        }
    }

    return {
        addObject  : addObject,
        undoButton : _config.undoButton,
        redoButton : _config.redoButton,
        undo       : undo,
        redo       : redo,
  }

  })();

  canvasDemo.undoButton.addEventListener('click',function(){
        canvasDemo.undo();
    });

    canvasDemo.redoButton.addEventListener('click',function(){
        canvasDemo.redo();
    });
  canvasDemo.addObject();


问:
Regex pattern to separate string with semicolon and plus
Here I have used the below mentioned code.

```<code>MatchCollection matches = Regex.Matches(cellData, @"(^\[.*\]$|^\[.*\]_[0-9]*$)");
</code>```

The only this pattern is not doing is it's not separating the semicolon and plus from the main string.

A sample string is

```<code>[dbServer];[ciDBNAME];[dbLogin];[dbPasswd] AND [SIM_ErrorFound@1]_+[@IterationCount]
</code>```

I am trying to extract

```<code>[dbServer]
[ciDBNAME]
[dbLogin]
[dbPasswd]
[SIM_ErrorFound@1]
[@IterationCount]
</code>```

from the string.

答:
To extract the stuff in square brackets from [dbServer];[ciDBNAME];[dbLogin];[dbPasswd] AND [SIM_ErrorFound@1]_+[@IterationCount] (which is what I assume you're be trying to do),

The regular expression (I haven't quoted it) should be

\[([^\]]*)\]

You should not use ^ and $ as youre not interested in start and end of strings.  The parentheses will capture every instance of zero or more characters inside square brackets.
If you want to be more specific about what you're capturing in the brackets, you'll need to change the [^\] to something else.

Body:
Here I have used the below mentioned code.

MatchCollection matches = Regex.Matches(cellData, @"(^\[.*\]$|^\[.*\]_[0-9]*$)");

The only this pattern is not doing is it's not separating the semicolon and plus from the main string.

A sample string is

[dbServer];[ciDBNAME];[dbLogin];[dbPasswd] AND [SIM_ErrorFound@1]_+[@IterationCount]

I am trying to extract

[dbServer]
[ciDBNAME]
[dbLogin]
[dbPasswd]
[SIM_ErrorFound@1]
[@IterationCount]

from the string.


问:
Install two debug apk from same application (Flavors)
So I have this app1 and I want to create a app2, from the app1, It will be almost the same app, but with differences in the layout. I manage to do that using productFlavors. The result need to be two apps in the Play store, both free and the user can have both in his phone.

However I can build both apk for debug, but when I install one, the phone doesn't let me install the other. Will this happen after both are uploaded to the store?

This is my gradle:

```<code>defaultConfig {
    applicationId "com.example.app"
    minSdkVersion 16
    targetSdkVersion 25
    versionCode 48
    versionName "3.1.1"

    multiDexEnabled true
}

signingConfigs {
    String releaseFilename = "/.androidReleaseKeys/example_release.properties"

    Properties props = new Properties()
    props.load(new FileInputStream(file(releaseFilename)))

    release {
        storeFile file(props.getProperty('keystore'))
        storePassword props.getProperty('keystore.password')
        keyAlias props.getProperty('keyAlias')
        keyPassword props.getProperty('keyAlias.password')
    }

}

productFlavors{
    app1{
        applicationId "com.example.app"
        buildTypes {

            debug {
                buildConfigField "String", "GOOGLEMAPS_API_KEY", "\"${googleMapsAPIDev}\"";
                debuggable true
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }

            release {
                signingConfig signingConfigs.release
                buildConfigField "String", "GOOGLEMAPS_API_KEY", "\"${googleMapsAPIRelease}\"";
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }

    app2{
        applicationId "com.example2.app2"
        versionCode 1
        versionName "1"
        multiDexEnabled true

        buildTypes {

            debug {
                buildConfigField "String", "GOOGLEMAPS_API_KEY", "\"${googleMapsAPIDev}\"";
                debuggable true
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }

            release {
                signingConfig signingConfigs.release
                buildConfigField "String", "GOOGLEMAPS_API_KEY", "\"${googleMapsAPIRelease}\"";
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }

    }
</code>```

答:
Declare this permission in manifest with ${applicationId} placeholder:

```<code><uses-permission android:name="${applicationId}.permission.C2D_MESSAGE"/>
<permission
    android:name="${applicationId}.permission.C2D_MESSAGE"
    android:protectionLevel="signature"/>
</code>```

Do not hardcode package name in manifest.

Body:
So I have this app1 and I want to create a app2, from the app1, It will be almost the same app, but with differences in the layout. I manage to do that using productFlavors. The result need to be two apps in the Play store, both free and the user can have both in his phone.

However I can build both apk for debug, but when I install one, the phone doesn't let me install the other. Will this happen after both are uploaded to the store?

This is my gradle:

defaultConfig {
    applicationId "com.example.app"
    minSdkVersion 16
    targetSdkVersion 25
    versionCode 48
    versionName "3.1.1"

    multiDexEnabled true
}

signingConfigs {
    String releaseFilename = "/.androidReleaseKeys/example_release.properties"

    Properties props = new Properties()
    props.load(new FileInputStream(file(releaseFilename)))

    release {
        storeFile file(props.getProperty('keystore'))
        storePassword props.getProperty('keystore.password')
        keyAlias props.getProperty('keyAlias')
        keyPassword props.getProperty('keyAlias.password')
    }

}

productFlavors{
    app1{
        applicationId "com.example.app"
        buildTypes {

            debug {
                buildConfigField "String", "GOOGLEMAPS_API_KEY", "\"${googleMapsAPIDev}\"";
                debuggable true
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }

            release {
                signingConfig signingConfigs.release
                buildConfigField "String", "GOOGLEMAPS_API_KEY", "\"${googleMapsAPIRelease}\"";
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }

    app2{
        applicationId "com.example2.app2"
        versionCode 1
        versionName "1"
        multiDexEnabled true

        buildTypes {

            debug {
                buildConfigField "String", "GOOGLEMAPS_API_KEY", "\"${googleMapsAPIDev}\"";
                debuggable true
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }

            release {
                signingConfig signingConfigs.release
                buildConfigField "String", "GOOGLEMAPS_API_KEY", "\"${googleMapsAPIRelease}\"";
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }

    }

Body:
Declare this permission in manifest with ${applicationId} placeholder:

<uses-permission android:name="${applicationId}.permission.C2D_MESSAGE"/>
<permission
    android:name="${applicationId}.permission.C2D_MESSAGE"
    android:protectionLevel="signature"/>

Do not hardcode package name in manifest.


问:
comparing strings and decoded unicode in python3
I'm doing some socket/select programming and one of my events is triggered by the incoming byte string of 'OK'. I'm using utf_8 to encode everything sent from the server and decoding it on the client. However, my client comparisons aren't working and my if statement never evaluates to true. Here is the code in question:

Server side:

```<code>def broadcast_string(self, data, omit_sock): # broadcasts data utf_8 encoded to all socks
    for sock in self.descriptors:
        if sock is not self.server and sock is not omit_sock:
            sock.send(data.encode('utf_8'))
    print(data)

def start_game(self): # i call this to send 'OK'
    data = 'OK'
    self.broadcast_string(data, 0)
    self.new_round()
</code>```

Client side:

```<code>else:   # got data from server
    if data.decode('utf_8') == 'OK': # i've tried substituting this with a var, no luck
        self.playstarted = True
    else:
        sys.stdout.write(data.decode('utf_8') + "\n")
        sys.stdout.flush()

    if self.playstarted is True: # never reached because if statement never True
        command = input("-->")
</code>```

I've read this and I think I'm following it but apparently not. I've even done the examples using the python shell and have had them evaluate to True, but not when I run this program.

Thanks!

答:
TCP sockets don't have message boundaries.  As your last comment says you are getting multiple messages in one long string.  You are reponsible for queuing up data until you have a complete message, and then processing it as one complete message.

Each time select says a socket has some data to read, append the data to a read buffer, then check to see if the buffer contains a complete message.  If it does, extract just the message from the front of the buffer and process it.  Continue until no more complete messages are found, then call select again.  Note also you should only decode a complete message, since you might receive a partial UTF-8 multi-byte character otherwise.

Rough example using \n as a message terminator (no error handling):

```<code>tmp = sock.recv(1000)
readbuf += tmp
while b'\n' in readbuf:
    msg,readbuf = readbuf.split(b'\n',1)
    process(msg.decode('utf8'))
</code>```

Body:
I'm doing some socket/select programming and one of my events is triggered by the incoming byte string of 'OK'. I'm using utf_8 to encode everything sent from the server and decoding it on the client. However, my client comparisons aren't working and my if statement never evaluates to true. Here is the code in question:

Server side:

def broadcast_string(self, data, omit_sock): # broadcasts data utf_8 encoded to all socks
    for sock in self.descriptors:
        if sock is not self.server and sock is not omit_sock:
            sock.send(data.encode('utf_8'))
    print(data)

def start_game(self): # i call this to send 'OK'
    data = 'OK'
    self.broadcast_string(data, 0)
    self.new_round()

Client side:

else:   # got data from server
    if data.decode('utf_8') == 'OK': # i've tried substituting this with a var, no luck
        self.playstarted = True
    else:
        sys.stdout.write(data.decode('utf_8') + "\n")
        sys.stdout.flush()

    if self.playstarted is True: # never reached because if statement never True
        command = input("-->")

I've read this and I think I'm following it but apparently not. I've even done the examples using the python shell and have had them evaluate to True, but not when I run this program.

Thanks!

Body:
TCP sockets don't have message boundaries.  As your last comment says you are getting multiple messages in one long string.  You are reponsible for queuing up data until you have a complete message, and then processing it as one complete message.

Each time select says a socket has some data to read, append the data to a read buffer, then check to see if the buffer contains a complete message.  If it does, extract just the message from the front of the buffer and process it.  Continue until no more complete messages are found, then call select again.  Note also you should only decode a complete message, since you might receive a partial UTF-8 multi-byte character otherwise.

Rough example using \n as a message terminator (no error handling):

tmp = sock.recv(1000)
readbuf += tmp
while b'\n' in readbuf:
    msg,readbuf = readbuf.split(b'\n',1)
    process(msg.decode('utf8'))


问:
Is this possible to make a JS request with limited bandwidth?
I would like to use a JS to simulate a slow connection vs fast connection to client, is this possible to limited the AJAX call bandwidth in JS? thanks. </p>

答: in google chrome you can trolling a net, please see a image


问:
how to create a list containing of 100 number of strings whose names are in series
a list of string objects is like

```<code>nodes=["#A_CN1","#A_CN2","#A_CN3","#A_CN4","#A_CN5","#A_CN6","#A_CN7","#A_CN8","#A_CN9","#A_CN10"]
</code>```

Here in the above list there are 10 elements but i need to use around 100 elements and the element is like #A_CN100

Is there any way to represent it shortly rather than writing 100 times in python ?

If suppose there is a list of 100 elements where each element itself is a list like, node1 , node2.. all are some lists

```<code>nodes=[node1,node2,node3,node4,node5,node6....node100]
</code>```

if I express this as

```<code>nodes=[node{0}.format(i) for i in range(1,101)]
</code>```

But,this throws an error! How to rectify this?

答:
A one liner with list comprehensions

```<code>nodes = ["#A_CN{0}".format(i) for i in range(1,101)]
</code>```

There is also a suggestion in the comments that a generator version be demonstrated. It would look like this:

```<code>nodes = ("#A_CN{0}".format(i) for i in range(1,101))
</code>```

But more commonly this is passed to list

```<code>nodes = list("#A_CN{0}".format(i) for i in range(1,101))
</code>```

So we end up with the same result as the list comprehension. However the second form is useful if you want to generate about a million items.

Body:
a list of string objects is like

nodes=["#A_CN1","#A_CN2","#A_CN3","#A_CN4","#A_CN5","#A_CN6","#A_CN7","#A_CN8","#A_CN9","#A_CN10"]

Here in the above list there are 10 elements but i need to use around 100 elements and the element is like #A_CN100

Is there any way to represent it shortly rather than writing 100 times in python ?

If suppose there is a list of 100 elements where each element itself is a list like, node1 , node2.. all are some lists

nodes=[node1,node2,node3,node4,node5,node6....node100]

if I express this as

nodes=[node{0}.format(i) for i in range(1,101)]

But,this throws an error! How to rectify this?

Body:
A one liner with list comprehensions

nodes = ["#A_CN{0}".format(i) for i in range(1,101)]

There is also a suggestion in the comments that a generator version be demonstrated. It would look like this:

nodes = ("#A_CN{0}".format(i) for i in range(1,101))

But more commonly this is passed to list

nodes = list("#A_CN{0}".format(i) for i in range(1,101))

So we end up with the same result as the list comprehension. However the second form is useful if you want to generate about a million items.


问:
extract certain emails from a given list of email matching few conditions
This question was asked in a recent job interview I gave and I was unable to answer it. Here is the question:

From a given email list (johndoe@noemail.com, xyz@no-email.com, noemail@xyz.com, answers@no email.com, jpt@nooooemail.com, kondoe@nomail.com) extract only those emails ending with (@noemail.com, @no-email.com, and @no email.com).

I searched and tried to run the code but it didn't ran.

```<code><?php

  $email_list = (johndoe@noemail.com, xyz@no-email.com, noemail@xyz.com, answers@no email.com, jpt@nooooemail.com, kondoe@nomail.com);

  $pattern = ('@noemail.com', '@no-email.com', '@no email.com' );

  echo preg_match($pattern, $email_list);

?>
</code>```

答:
```<code>$email_list = array('johndoe@noemail.com', 'xyz@no-email.com',
                    'noemail@xyz.com', 'answers@no email.com',
                    'jpt@nooooemail.com', 'kondoe@nomail.com');
$result = array();

foreach ($email_list as $email) {
    if (preg_match('~@no[ -]?email\.com~', $email)) {
        $result[] = $email;
    }
}

var_export($result);
// output ->
//        array (
//          0 => 'johndoe@noemail.com',
//          1 => 'xyz@no-email.com',
//          2 => 'answers@no email.com',
//        )
</code>```

Body:
This question was asked in a recent job interview I gave and I was unable to answer it. Here is the question:

From a given email list (johndoe@noemail.com, xyz@no-email.com, noemail@xyz.com, answers@no email.com, jpt@nooooemail.com, kondoe@nomail.com) extract only those emails ending with (@noemail.com, @no-email.com, and @no email.com).

I searched and tried to run the code but it didn't ran.

<?php

  $email_list = (johndoe@noemail.com, xyz@no-email.com, noemail@xyz.com, answers@no email.com, jpt@nooooemail.com, kondoe@nomail.com);

  $pattern = ('@noemail.com', '@no-email.com', '@no email.com' );

  echo preg_match($pattern, $email_list);

?>


问:
Exception "CKR_FUNCTION_NOT_SUPPORTED", PKCS11Interop with OpenSC
I am trying to use PKCS11Interop Library with latest version (0.16) of OpenSC (opensc-pkcs11.dll). I have tried USB tokens from three vendors which are Yubico 4, NitroKey Pro/Start, Fetian ePass2003 but unable to use most of the functions from PKCS11Interop Library. I receive Net.Pkcs11Interop.Common.Pkcs11Exception: 'Method C_SignRecoverInit returned CKR_FUNCTION_NOT_SUPPORTED' for most of functions provided by the library. The functions that throw this exception are C_GetOperationState, C_SetOperationState, C_GenerateKey, C_GenerateKeyPair, Encrypt/Decrypt functions, Sign/Verify functions etc.

The strange thing is functions like GetSlotInfo, GetMechanisms, Login, Session works fine.

I have spent a lot of time trying to find a solution here. Would appreciate if anyone can help on this.

答:
Net.Pkcs11Interop.Common.Pkcs11Exception always indicates error returned by the underlying unmanaged PKCS#11 library which is usually provided by the device vendor.

Error you are receiving - CKR_FUNCTION_NOT_SUPPORTED - indicates that unmanaged PKCS#11 library does not support/implement particular function defined in PKCS#11 specification.

OpenSC source code confirms your finding that it does not support C_SignRecoverInit and also a few other functions.

BTW this is normal and pretty common behavior. You will hardly find PKCS#11 library that supports all PKCS#11 functions. If PKCS#11 library provided by OpenSC does not provide some function you really need then I suggest you check other solutions provided by commercial vendors.


问:
Converting UnixTime to day intervals (morning, evening, night etc.) in R
I have a table with a column TIMESTAMP with Unix Time values. I need to convert it to intervals of day, like night, morning, before_afternoon, afternoon, twilight, evening.

```<code>data$TIMESTAMP[1]
[1] 1372636858
time <- anytime(1372636858)
> time
[1] "2013-07-01 01:00:58 WEST"
</code>```

I am doing:

```<code>cut(time, breaks= as.POSIXct(paste("2001-01-01",c("00:00:00", "06:00:00", "09:00:00","12:00:00","15:00:00","18:00:00", "20:00:00")),format="%Y-%m-%d %H:%M:%S", tz ="Portugal"),labels=c('night','morning','before_afternoon','afternoon','twilight','evening'))
</code>```

The output is:

```<code>[1] <NA>
Levels: night morning before_afternoon afternoon twilight evening
</code>```

What I am doing wrong?

答: I'd try c('night','morning','before_afternoon','afternoon','twilight','evening')[findInterval(as.POSIXlt(time)$hour,c(0,6,9,15,18,20))]. – nicola Jun 1 at 11:06</p>

Body:
I have a table with a column TIMESTAMP with Unix Time values. I need to convert it to intervals of day, like night, morning, before_afternoon, afternoon, twilight, evening.

data$TIMESTAMP[1]
[1] 1372636858
time <- anytime(1372636858)
> time
[1] "2013-07-01 01:00:58 WEST"

I am doing:

cut(time, breaks= as.POSIXct(paste("2001-01-01",c("00:00:00", "06:00:00", "09:00:00","12:00:00","15:00:00","18:00:00", "20:00:00")),format="%Y-%m-%d %H:%M:%S", tz ="Portugal"),labels=c('night','morning','before_afternoon','afternoon','twilight','evening'))

The output is:

[1] <NA>
Levels: night morning before_afternoon afternoon twilight evening

What I am doing wrong?


问:
Cannot init both Twitter and Crashlytics with Fabric
After migrating to swift 3, the initialisation i used for both crashlytics and twitter (since only one call to fabric is permitted) is not working anymore.

The method given the documentation doesn't work either (it didn't work in swift 2 either by the way).
What is the proper way to initialize this?

I tried all the methods listed here :
How to init Fabric properly in Swift and the init i used before was this :

```<code>`        Fabric.with([Crashlytics.self, Twitter.self])`
</code>```

But none are working for swift 3.

Error message : Calling Twitter.start is not supported

答: FIY since twitter kit 3, it is separated from fabric so we now need to instantiate both separatly.</p>

Body:
After migrating to swift 3, the initialisation i used for both crashlytics and twitter (since only one call to fabric is permitted) is not working anymore.

The method given the documentation doesn't work either (it didn't work in swift 2 either by the way).
What is the proper way to initialize this?

I tried all the methods listed here :
How to init Fabric properly in Swift and the init i used before was this :

`        Fabric.with([Crashlytics.self, Twitter.self])`

But none are working for swift 3.

Error message : Calling Twitter.start is not supported


问:
DHTMLX grid header tool tip
How can i add tool tip for DHTMLX grid suppose i am having 1st column named MOP, which stands for Mode of payment how do i enable tool tip for this header on hover MOP it should display Mode of payment.

How do i achieve this.

答:
To enable/disable tooltips for specified columns in dhtmlx grid,
this function is used:

void enableTooltips(string list);

Example:

```<code>//disable first column's tooltips
myGrid.enableTooltips("false,true,true,true,true");
</code>```

For more details please visit https://docs.dhtmlx.com/api__dhtmlxgrid_enabletooltips.html.

Title: DHTMLX grid header tool tip

Body:
To enable/disable tooltips for specified columns in dhtmlx grid,
this function is used:

void enableTooltips(string list);

Example:

//disable first column's tooltips
myGrid.enableTooltips("false,true,true,true,true");

For more details please visit https://docs.dhtmlx.com/api__dhtmlxgrid_enabletooltips.html.


问:
JQuery Event Bubbling Issue
JSFiddle: https://jsfiddle.net/3v2qav58/

having an issue with a dropdown menu.

The issue my sub category list item has a ul/dropdown inside it, so I've grabbed the list item and used '.find()' to get the dropdown and then try slideToggle it.

The issue is I have 3 list items and when I click on the other ones they also open and close the other list items for e.g There is only the dropdown on the first list item but if you click the 2nd/3rd they also toggle.

I think it's to do with event bubbling because I thought '.find()' only traversed down and not up?

Could some explain why this is happening who the event bubbling occurs and how to resolve it?

Cheers

HTML

```<code><ul class="dropdown">
  <li class="dropdown-item">
    <a href="">Cat 1</a>
    <ul class="sub-dropdown">
      <li class="dropdown-sub-item">
        <a href="#">Sub Cat 1</a>
        <ul class="sub-dropdown-child">
          <li class="sub-dropdown-child-item"><a href="#">Sub Cat Child 1</a></li>
          <li class="sub-dropdown-child-item"><a href="#">Sub Cat Child 2</a></li>
          <li class="sub-dropdown-child-item"><a href="#">Sub Cat Child 3</a></li>
        </ul>
      </li>
</code>```

CSS

```<code>.sub-dropdown,
.sub-dropdown-child {
  display: none;
}
</code>```

JQuery

```<code>var dropdownItem = $(".dropdown-item");
var dropdownSubItem = $(".sub-dropdown");
var DropdownSubItem = $(".dropdown-sub-item");
var subDropdownChild = $(".sub-dropdown-child");

// Open
dropdownItem.on("click", function(e) {
  e.preventDefault();
  dropdownSubItem.show();

  // Open sub cat
  dropdownSubItem.on("click", function(e) {
    e.stopPropagation();
    $(this).find(subDropdownChild).slideToggle();
  });
});
</code>```

答:
2 things:

Keep click event for sub item outside of first event, separately.

You must have attached your click event to li.DropdownSubItem rather than ul.dropdownSubItem.

Here's the updated code and Fiddle

```<code>// Open
dropdownItem.on("click", function(e) {
  e.preventDefault();
  dropdownSubItem.show();
});

// Open sub cat
DropdownSubItem.on("click", function(e) {
  $(this).find(subDropdownChild).slideToggle();
  e.stopImmediatePropagation();
});
</code>```

Title: JQuery Event Bubbling Issue

Body:
JSFiddle: https://jsfiddle.net/3v2qav58/

having an issue with a dropdown menu.

The issue my sub category list item has a ul/dropdown inside it, so I've grabbed the list item and used '.find()' to get the dropdown and then try slideToggle it.

The issue is I have 3 list items and when I click on the other ones they also open and close the other list items for e.g There is only the dropdown on the first list item but if you click the 2nd/3rd they also toggle.

I think it's to do with event bubbling because I thought '.find()' only traversed down and not up?

Could some explain why this is happening who the event bubbling occurs and how to resolve it?

Cheers

HTML

    Cat 1

        Sub Cat 1

Sub Cat Child 1

Sub Cat Child 2

Sub Cat Child 3

CSS

.sub-dropdown,
.sub-dropdown-child {
  display: none;
}

JQuery

var dropdownItem = $(".dropdown-item");
var dropdownSubItem = $(".sub-dropdown");
var DropdownSubItem = $(".dropdown-sub-item");
var subDropdownChild = $(".sub-dropdown-child");

// Open
dropdownItem.on("click", function(e) {
  e.preventDefault();
  dropdownSubItem.show();

  // Open sub cat
  dropdownSubItem.on("click", function(e) {
    e.stopPropagation();
    $(this).find(subDropdownChild).slideToggle();
  });
});

Body:
2 things:

Keep click event for sub item outside of first event, separately.

You must have attached your click event to li.DropdownSubItem rather than ul.dropdownSubItem.

Here's the updated code and Fiddle

// Open
dropdownItem.on("click", function(e) {
  e.preventDefault();
  dropdownSubItem.show();
});

// Open sub cat
DropdownSubItem.on("click", function(e) {
  $(this).find(subDropdownChild).slideToggle();
  e.stopImmediatePropagation();
});


问:
SQL Error when trying to alter column
I add trying to add a method to be the defualt value of an existing SQL Table Column:

```<code> ALTER TABLE Category ALTER COLUMN category_course
   CONSTRAINT cat_other_course DEFAULT otherCourse();
</code>```

However I keep getting this error:

```<code>ERROR:  syntax error at or near "CONSTRAINT"
LINE 2: ALTER TABLE Category ALTER COLUMN category_course CONSTRAINT...
                                                      ^
********** Error **********

ERROR: syntax error at or near "CONSTRAINT"
SQL state: 42601
</code>```

NB: Yes, Category (table) category_course (column) and otherCourse() (function) all exist.

答:
You need to add SET before DEFAULT. Hope this helps.</p>

```<code>ALTER TABLE Category ALTER COLUMN category_course
CONSTRAINT cat_other_course SET DEFAULT otherCourse();
</code>```

Title: SQL Error when trying to alter column

Body:
I add trying to add a method to be the defualt value of an existing SQL Table Column:

 ALTER TABLE Category ALTER COLUMN category_course
   CONSTRAINT cat_other_course DEFAULT otherCourse();

However I keep getting this error:

ERROR:  syntax error at or near "CONSTRAINT"
LINE 2: ALTER TABLE Category ALTER COLUMN category_course CONSTRAINT...
                                                      ^
********** Error **********

ERROR: syntax error at or near "CONSTRAINT"
SQL state: 42601

NB: Yes, Category (table) category_course (column) and otherCourse() (function) all exist.

Body:
You need to add SET before DEFAULT. Hope this helps.

ALTER TABLE Category ALTER COLUMN category_course
CONSTRAINT cat_other_course SET DEFAULT otherCourse();


问:
Passing an array between pages in ionic 2
I'm new in Ionic 2 and I'm having troubles with passing data between pages. In my Home.ts file  I have a global array that contains some numbers I calculated and i want to pass it to my Table.ts file, to show it in a HTML table with the *ngFor method.

this is the Function in Home.ts where i fill the array and try to push (i will skip the calculations, becacause i know they are correct).

```<code>`import { Component } from '@angular/core';
 import { AlertController } from 'ionic-angular';
 import { IonicPage,NavController, NavParams} from 'ionic-angular';
 import {Table} from '../table/table';

 export class HomePage {

 averagesList: Array <number> =[];

 constructor(public alerCtrl: AlertController,
             public navCtrl: NavController,
             public navParams: NavParams)
             {}

 Calculate(){

 var Averages=[];

 //Calculations on the 'Averages' Array

 this.averagesList = Averages;

this.navCtrl.push(Table,this.averagesList);
 }

}
</code>```

So I try to print it in my Table.ts file but it gives me undefined result

```<code>import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {HomePage} from '../home/home';
@IonicPage()
@Component({
selector: 'page-table',
templateUrl: 'table.html',
})
export class Table{

constructor(public navCtrl: NavController, public navParams: NavParams) {

}

ionViewDidLoad() {

console.log(this.navParams.get('averagesList'));
}
}
</code>```

I've tried to pass a let variable and it worked, so why doesn't it work with arrays?

答:
Your mistake is using console.log(this.navParams.get('averagesList'));

Here 'averagesList' is the key.

To get it this way, you need to send as :

```<code>this.navCtrl.push(Table,{'averagesList' : this.averagesList});
</code>```

Else:

if you directly send as

```<code>this.navCtrl.push(Table,this.averagesList);
</code>```

You can retrieve value like so:

```<code>console.log(this.navParams.data);
</code>```

Body:
I'm new in Ionic 2 and I'm having troubles with passing data between pages. In my Home.ts file  I have a global array that contains some numbers I calculated and i want to pass it to my Table.ts file, to show it in a HTML table with the *ngFor method.

this is the Function in Home.ts where i fill the array and try to push (i will skip the calculations, becacause i know they are correct).

`import { Component } from '@angular/core';
 import { AlertController } from 'ionic-angular';
 import { IonicPage,NavController, NavParams} from 'ionic-angular';
 import {Table} from '../table/table';

 export class HomePage {

 averagesList: Array <number> =[];

 constructor(public alerCtrl: AlertController,
             public navCtrl: NavController,
             public navParams: NavParams)
             {}

 Calculate(){

 var Averages=[];

 //Calculations on the 'Averages' Array

 this.averagesList = Averages;

this.navCtrl.push(Table,this.averagesList);
 }

}

So I try to print it in my Table.ts file but it gives me undefined result

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {HomePage} from '../home/home';
@IonicPage()
@Component({
selector: 'page-table',
templateUrl: 'table.html',
})
export class Table{

constructor(public navCtrl: NavController, public navParams: NavParams) {

}

ionViewDidLoad() {

console.log(this.navParams.get('averagesList'));
}
}

I've tried to pass a let variable and it worked, so why doesn't it work with arrays?

Body:
Your mistake is using console.log(this.navParams.get('averagesList'));

Here 'averagesList' is the key.

To get it this way, you need to send as :

this.navCtrl.push(Table,{'averagesList' : this.averagesList});

Else:

if you directly send as

this.navCtrl.push(Table,this.averagesList);

You can retrieve value like so:

console.log(this.navParams.data);


问:
Python chat with Crypto module not decrypting
My python chat to learn about sockets is working and today I started to implement the Crypto module to make an encrypted chat. But I think I'm messing with public and private keys.

When a client connects to the server, they do a handshake to exchange their public keys. So client has their own keys to decrypt plus server public key to encrypt outgoing messages. And server side: each client it's a thread and after handshake stores its own public key to encrypt outgoing messages and server keys to decrypt.

Workflow is (from my POV): sender client encrypts a message, is send to server, server decrypts with its own privkey, server encrypts the message to all other clients with their own pubkey. Finally recipient client decrypts the message with server pubkey.

The problem I'm facing when sending messages to all, using send_all and send_all_no_room methods. Sometimes message is decrypted correctly but most of times is not decrypted correctly.

In which point I'm losing the correct key?

Here there are the server, client, and comms (send, receive methods)

Take into account that I only implemented custom send, receive, encrypt, decrypt methods to send_all and send_all_no_room functions. For example send_private_msg won't work.

答:
The problem is in the send_all function:

```<code>def send_all(self, message):
    """Send to all method, broadcast a message"""
    for sock in [client.sock for client in clients]:
        if sock != self.sock:
            message_encripted = self.encriptar(message,client)
            send(sock,message_encripted)
</code>```

Each iteration of the for loop uses the same client. The same problem exists in the send_all_no_room function.

Fixed code:

```<code>def send_all(self, message):
    """Send to all method, broadcast a message"""
    for client in clients:
        if client is not self:
            message_encripted = self.encriptar(message,client)
            send(client.sock,message_encripted)
</code>```

Body:
The problem is in the send_all function:

def send_all(self, message):
    """Send to all method, broadcast a message"""
    for sock in [client.sock for client in clients]:
        if sock != self.sock:
            message_encripted = self.encriptar(message,client)
            send(sock,message_encripted)

Each iteration of the for loop uses the same client. The same problem exists in the send_all_no_room function.

Fixed code:

def send_all(self, message):
    """Send to all method, broadcast a message"""
    for client in clients:
        if client is not self:
            message_encripted = self.encriptar(message,client)
            send(client.sock,message_encripted)


问:
Unexpected virtual host behavior of Drupal sites on Apache
I'm running an Apache server on a CentOS 7 machine.

A month ago I created a new Drupal site (let's call it site1) under /var/www/html/site1.
Visiting http://<server-ip>/site1 yielded site1 correctly.

Today, in order to provide a test environment for a new customer, I had to create a virtual host for a new Drupal site (let's call it site2).

So I created the following vhost rule:

```<code><VirtualHost *:80>
        ServerAdmin test@email.com
        ServerName site2.dev
        DocumentRoot /var/www/html/site2
        <Directory />
                Options FollowSymLinks
                AllowOverride All
        </Directory>
</VirtualHost>
</code>```

After that I created the site's folder /var/www/html/site2 and installed Drupal. Visiting http://site2.dev yields site2 correctly.

The problem is, if I now visit http://<server-ip>/site1, site2 is shown.

I can't figure out what might be the problem. The two sites are on completely different paths and different databases, so one shouldn't affect the other in my opinion.

Since I literally defined my first vhost today, I was wondering if someone might help me explain the issue. Thanks in advance!

答:
Ok I missunderstood your problem and thought you had 2 domains.

Was your site1 accessed by the IP with no sub directory? In this case :
Change the DocumentRoot to point to /var/www/html then both sites will be accessed by IP/site1 and IP/site2.

If you were allready accessing site1 by the url IP/site1 then you had nothing to change and could access IP/site2 without your new virtualhost wich point only to site2 directory... .

Body:
I'm running an Apache server on a CentOS 7 machine.

A month ago I created a new Drupal site (let's call it site1) under /var/www/html/site1.
Visiting http://<server-ip>/site1 yielded site1 correctly.

Today, in order to provide a test environment for a new customer, I had to create a virtual host for a new Drupal site (let's call it site2).

So I created the following vhost rule:

<VirtualHost *:80>
        ServerAdmin test@email.com
        ServerName site2.dev
        DocumentRoot /var/www/html/site2
        <Directory />
                Options FollowSymLinks
                AllowOverride All
        </Directory>
</VirtualHost>

After that I created the site's folder /var/www/html/site2 and installed Drupal. Visiting http://site2.dev yields site2 correctly.

The problem is, if I now visit http://<server-ip>/site1, site2 is shown.

I can't figure out what might be the problem. The two sites are on completely different paths and different databases, so one shouldn't affect the other in my opinion.

Since I literally defined my first vhost today, I was wondering if someone might help me explain the issue. Thanks in advance!


问:
Python: Regex help
```<code>str = "a\b\c\dsdf\matchthis\erwe.txt"
</code>```

The last folder name.

Match "matchthis"

答:
```<code>>>> import re
>>> print re.match(r".*\\(.*)\\[^\\]*", r"a\b\c\dsdf\matchthis\erwe.txt").groups()
('matchthis',)
</code>```

As @chrisaycock and @rafe-kettler pointed out.  Use the x.split(r'\') if you can.  It is way faster, readable and more pythonic.   If you really need a regex then use one.

EDIT:
Actually, os.path is best. Platform independent.  unix/windows etc.

Title: Python: Regex help

Body:
str = "a\b\c\dsdf\matchthis\erwe.txt"

The last folder name.

Match "matchthis"

Body:
>>> import re
>>> print re.match(r".*\\(.*)\\[^\\]*", r"a\b\c\dsdf\matchthis\erwe.txt").groups()
('matchthis',)

As @chrisaycock and @rafe-kettler pointed out.  Use the x.split(r'\') if you can.  It is way faster, readable and more pythonic.   If you really need a regex then use one.

EDIT:
Actually, os.path is best. Platform independent.  unix/windows etc.