问:
How to invert a full matrix?
I have a matrix

```<code>            X1         X2        X3        X4        X5        X6           G1            G2
X1            5         0         0         0         0         0            5            0
X2            0         5         0         0         0         0            5            0
X3            0         0         5         0         0         0            5            0
X4            0         0         0         5         0         0            0            5
X5            0         0         0         0         5         0            0            5
X6            0         0         0         0         0         5            0            5
G1            5         5         5         0         0         0           15            0
G2            0         0         0         5         5         5            0           15
</code>```

There are dependence lineal in the two last rows and columns, I try to delete one row and one column (for example G1), but the resulting matrix still has a linear dependence, so I can't invert the matrix.

Can anyone help me please?

答:
The symmetric matrix m, shown reproducibly in the Note at the end, is singular which is implied by its having at least one zero eigenvalue (in fact, it has two):

```<code>eigen(m)$values
## [1]  2.000000e+01  2.000000e+01  5.000000e+00  5.000000e+00  5.000000e+00
## [6]  5.000000e+00 -4.671248e-24 -4.671248e-24
</code>```

Thus, it cannot be inverted; however, you can take the Moore Penrose generalized inverse using ginv from the MASS package. A generalized inverse does satisfy the relation shown in the last line of code below. Note that the MASS package comes with R so you don't need to install it.

```<code>library(MASS)

gm <- ginv(m)
all.equal(m %*% gm %*% m, m)
## [1] TRUE
</code>```

Note that there are two linear dependencies owing to the two zero eigenvalues. By inspection we note that the sum of the first 3 rows of m equals the 7th row and the sum of the 4th through 6th rows equals the 8th row so dropping rows 7 and 8 and the corresponding columns due to symmetry we see that the upper left 6x6 submatrix is invertible:

```<code>solve(m[-(7:8), -(7:8)])
</code>```

Alternately we can find constraints by inspection of the eigenvectors of m.

Note

```<code>Lines <- "X1         X2        X3        X4        X5        X6           G1            G2
X1            5         0         0         0         0         0            5            0
X2            0         5         0         0         0         0            5            0
X3            0         0         5         0         0         0            5            0
X4            0         0         0         5         0         0            0            5
X5            0         0         0         0         5         0            0            5
X6            0         0         0         0         0         5            0            5
G1            5         5         5         0         0         0           15            0
G2            0         0         0         5         5         5            0           15"
m <- as.matrix(read.table(text = Lines))
</code>```

Title: How to invert a full matrix?

Body:
I have a matrix

            X1         X2        X3        X4        X5        X6           G1            G2
X1            5         0         0         0         0         0            5            0
X2            0         5         0         0         0         0            5            0
X3            0         0         5         0         0         0            5            0
X4            0         0         0         5         0         0            0            5
X5            0         0         0         0         5         0            0            5
X6            0         0         0         0         0         5            0            5
G1            5         5         5         0         0         0           15            0
G2            0         0         0         5         5         5            0           15

There are dependence lineal in the two last rows and columns, I try to delete one row and one column (for example G1), but the resulting matrix still has a linear dependence, so I can't invert the matrix.

Can anyone help me please?

Body:
The symmetric matrix m, shown reproducibly in the Note at the end, is singular which is implied by its having at least one zero eigenvalue (in fact, it has two):

eigen(m)$values
## [1]  2.000000e+01  2.000000e+01  5.000000e+00  5.000000e+00  5.000000e+00
## [6]  5.000000e+00 -4.671248e-24 -4.671248e-24

Thus, it cannot be inverted; however, you can take the Moore Penrose generalized inverse using ginv from the MASS package. A generalized inverse does satisfy the relation shown in the last line of code below. Note that the MASS package comes with R so you don't need to install it.

library(MASS)

gm <- ginv(m)
all.equal(m %*% gm %*% m, m)
## [1] TRUE

Note that there are two linear dependencies owing to the two zero eigenvalues. By inspection we note that the sum of the first 3 rows of m equals the 7th row and the sum of the 4th through 6th rows equals the 8th row so dropping rows 7 and 8 and the corresponding columns due to symmetry we see that the upper left 6x6 submatrix is invertible:

solve(m[-(7:8), -(7:8)])

Alternately we can find constraints by inspection of the eigenvectors of m.

Note

Lines <- "X1         X2        X3        X4        X5        X6           G1            G2
X1            5         0         0         0         0         0            5            0
X2            0         5         0         0         0         0            5            0
X3            0         0         5         0         0         0            5            0
X4            0         0         0         5         0         0            0            5
X5            0         0         0         0         5         0            0            5
X6            0         0         0         0         0         5            0            5
G1            5         5         5         0         0         0           15            0
G2            0         0         0         5         5         5            0           15"
m <- as.matrix(read.table(text = Lines))


来源: stackexchange

问:
bad file descriptor while reading posix message queue
Similar threads exist but none of them helped. I am getting bad file descriptor error while reading with below code under linux.
I also specify queue attributes when cerating with O_CREAT flag.
Any idea? Thanks.</p>

```<code>#include <stdio.h>
#include <mqueue.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>

#define Log(...) printf(__VA_ARGS__); fflush(stdout)
int error;

void* producer(void* arg)   {
    Log("producer\n");

    mqd_t q = mq_open("/ytm", O_RDWR);
    mq_send(q, "kardeshians", sizeof("kardeshians"), 1);

}

void* consumer(void* arg)    {

    Log("consumer\n");
    char buff[32];
    mqd_t q = mq_open("/ytm", O_RDONLY);
    int prio;

    while(1)    {
        error =  mq_receive(q,buff,sizeof(buff), NULL);
        if(error)   {
            printf("read error %d  %s\n", errno, strerror(errno));
        }
    }

}

int main()  {

    struct mq_attr attr;
    attr.mq_maxmsg = 10;
    attr.mq_msgsize = 32;
    mqd_t queue = mq_open("/ytm", O_CREAT | O_RDWR, 0, &attr);

    pthread_t tid;
    pthread_create(&tid, 0 , producer, 0);
    pthread_create(&tid, 0 , consumer, 0);

    while(1);
}
</code>```

答:
Problem was both with the execute permission and message size. After running as a root and making read buffer size bigger than the mq_msgsize it worked.
Thanks for error checking suggestions. Here is the working code:</p>

```<code>#include <stdio.h>

#include <mqueue.h>
#include <pthread.h>

#include <errno.h>
#include <string.h>

#define Log(...) printf(__VA_ARGS__); fflush(stdout)
int error;

void* producer(void* arg)   {
    Log("producer\n");

    mqd_t q = mq_open("/ytm", O_RDWR);

    if(q == -1)  {
        printf("mq_open error %d  %s\n", errno, strerror(errno));
        exit(0);
    }

   while(1) {
        int retval = mq_send(q, "kardeshians\n", sizeof("kardeshians\n"), 1);

        if(retval == -1)    {
            printf("mq_open error %d  %s\n", errno, strerror(errno));
            exit(0);
        }
   }

}

void* consumer(void* arg)    {

    Log("consumer\n");
    char buff[64];
    mqd_t q = mq_open("/ytm", O_RDONLY);
    int prio;

    while(1)    {
        int retval =  mq_receive(q,buff,sizeof(buff), NULL);
        if(retval ==  -1)   {
            printf("read error %d  %s\n", errno, strerror(errno));
        } else {
            printf("got message : %s", buff);
        }
    }

}

int main()  {

    struct mq_attr attr;
    attr.mq_maxmsg = 10;
    attr.mq_msgsize = 32;
    mq_unlink ("/ytm");
    mqd_t queue = mq_open("/ytm", O_CREAT | O_RDWR, 0, &attr);

    pthread_t tid;
    pthread_create(&tid, 0 , producer, 0);
    pthread_create(&tid, 0 , consumer, 0);

    while(1);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Similar threads exist but none of them helped. I am getting bad file descriptor error while reading with below code under linux.
I also specify queue attributes when cerating with O_CREAT flag.
Any idea? Thanks.

#include <stdio.h>
#include <mqueue.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>

#define Log(...) printf(__VA_ARGS__); fflush(stdout)
int error;

void* producer(void* arg)   {
    Log("producer\n");

    mqd_t q = mq_open("/ytm", O_RDWR);
    mq_send(q, "kardeshians", sizeof("kardeshians"), 1);

}

void* consumer(void* arg)    {

    Log("consumer\n");
    char buff[32];
    mqd_t q = mq_open("/ytm", O_RDONLY);
    int prio;

    while(1)    {
        error =  mq_receive(q,buff,sizeof(buff), NULL);
        if(error)   {
            printf("read error %d  %s\n", errno, strerror(errno));
        }
    }

}

int main()  {

    struct mq_attr attr;
    attr.mq_maxmsg = 10;
    attr.mq_msgsize = 32;
    mqd_t queue = mq_open("/ytm", O_CREAT | O_RDWR, 0, &attr);

    pthread_t tid;
    pthread_create(&tid, 0 , producer, 0);
    pthread_create(&tid, 0 , consumer, 0);

    while(1);
}

Body:
Problem was both with the execute permission and message size. After running as a root and making read buffer size bigger than the mq_msgsize it worked.
Thanks for error checking suggestions. Here is the working code:

#include <stdio.h>

#include <mqueue.h>
#include <pthread.h>

#include <errno.h>
#include <string.h>

#define Log(...) printf(__VA_ARGS__); fflush(stdout)
int error;

void* producer(void* arg)   {
    Log("producer\n");

    mqd_t q = mq_open("/ytm", O_RDWR);

    if(q == -1)  {
        printf("mq_open error %d  %s\n", errno, strerror(errno));
        exit(0);
    }

   while(1) {
        int retval = mq_send(q, "kardeshians\n", sizeof("kardeshians\n"), 1);

        if(retval == -1)    {
            printf("mq_open error %d  %s\n", errno, strerror(errno));
            exit(0);
        }
   }

}

void* consumer(void* arg)    {

    Log("consumer\n");
    char buff[64];
    mqd_t q = mq_open("/ytm", O_RDONLY);
    int prio;

    while(1)    {
        int retval =  mq_receive(q,buff,sizeof(buff), NULL);
        if(retval ==  -1)   {
            printf("read error %d  %s\n", errno, strerror(errno));
        } else {
            printf("got message : %s", buff);
        }
    }

}

int main()  {

    struct mq_attr attr;
    attr.mq_maxmsg = 10;
    attr.mq_msgsize = 32;
    mq_unlink ("/ytm");
    mqd_t queue = mq_open("/ytm", O_CREAT | O_RDWR, 0, &attr);

    pthread_t tid;
    pthread_create(&tid, 0 , producer, 0);
    pthread_create(&tid, 0 , consumer, 0);

    while(1);
}


问:
Invoke JavaScript function with argument via pointer?
How can you invoke a function in JavaScript, while passing in arguments, using a function pointer?

Example:

```<code>function foo (a, callback) {
        jQuery.post('/soon/check.json', { var:a }, function(resp) {
             callback(resp);
    });
}

function process_json(resp) {
  // Do something with resp
}

foo(bar, process_json);
</code>```

process_json never gets invoked. Looking in Firebug, the string process_json is getting passed into foo, but I assumed this represents a pointer to the function process_json.

In Javascript, is it not possible to invoke functions via pointers and pass in arguments?

答:
Try this: http://jsfiddle.net/26naf/

Function alert is passed to foo by reference:

```<code>function foo(fref)
{
   fref("hi world");
}

foo(alert);
</code>```

And it works as you see.

Body:
How can you invoke a function in JavaScript, while passing in arguments, using a function pointer?

Example:

function foo (a, callback) {
        jQuery.post('/soon/check.json', { var:a }, function(resp) {
             callback(resp);
    });
}

function process_json(resp) {
  // Do something with resp
}

foo(bar, process_json);

process_json never gets invoked. Looking in Firebug, the string process_json is getting passed into foo, but I assumed this represents a pointer to the function process_json.

In Javascript, is it not possible to invoke functions via pointers and pass in arguments?

Body:
Try this: http://jsfiddle.net/26naf/

Function alert is passed to foo by reference:

function foo(fref)
{
   fref("hi world");
}

foo(alert);

And it works as you see.

ContentLicense: CC BY-SA 3.0


问:
Array of Bitmaps into Video with ffmpeg
I'm Facing current porblem.
I have an Array of 100 Bitmaps. these are Screenshots i took from a view.
I used JCodec to make it to a video, buts its waay to slow. Im hoping to get better results with FFmpeg

Now i want to use the FFmpeg Library. Simillar questions were asked but i have no Idea how to use ffmpeg and how i have to use it in my specific case. All i see are weird Complex Commands See:

```<code> File dir = your directory where image stores;
    String filePrefix = "picture"; //imagename prefix
    String fileExtn = ".jpg";//image extention
    filePath = dir.getAbsolutePath();
    File src = new File(dir, filePrefix + "%03d" + fileExtn);// image name should ne picture001, picture002,picture003 soon  ffmpeg takes as input valid
</code>```

complexCommand = new String[]{"-i", src + "", "-c:v", "libx264", "-c:a", "aac", "-vf", "setpts=2*PTS", "-pix_fmt", "yuv420p", "-crf", "10", "-r", "15", "-shortest", "-y", "/storage/emulated/0/" + app_name + "/Video/" + app_name + "_Video" + number + ".mp4"};

The Problem is, that in this case he is using a Path. I need it to be from an Array. And i have no idea what to do with the String (ComplexCommands) :/
My Bitmaps are like this:

Bitmap[] bitmaps = new Bitmaps[100];

this is filled later on.

if anyone is searching on how to do it with JCodec:

```<code> try {
                    out = NIOUtils.writableFileChannel( Environment.getExternalStorageDirectory().getAbsolutePath()+"/***yourpath***/output"+System.currentTimeMillis()+".mp4");
                    // for Android use: AndroidSequenceEncoder

                    AndroidSequenceEncoder encoder = new AndroidSequenceEncoder(out, Rational.R(25, 1));
                    for (int i = 0 ; i < 100 ; i++) {
                        // Generate the image, for Android use Bitmap

                        // Encode the image
                        System.out.println("LOO2P"+i);
                        encoder.encodeImage(bitmaps[i]);
                    }
                    // Finalize the encoding, i.e. clear the buffers, write the header, etc.
                    encoder.finish();

                } catch (FileNotFoundException e) {
                    System.out.println("fNF");
                    e.printStackTrace();

                } catch (IOException e) {
                    System.out.println("IOE");
                    e.printStackTrace();
                } finally {
                    System.out.println("IOSSE");
                    NIOUtils.closeQuietly(out);
                }
</code>```

答:
According to the the ffmpeg wiki, the way you described is exactly how it is intended to be done. To implement this you should write each image from your array into a single file according to the described naming conventions. I don't know if this will help with your performance issues though.
Writing the images to files can be done following this answer:

```<code>for (int i = 0; i<bitmapArray.length(); i++){
    // Write to file while incrementing the file name
    writeToFile(bitmapArray[i], i);
}
</code>```

As far as I could find, ffmpeg does not support directly encoding from an array.

Title: Array of Bitmaps into Video with ffmpeg

Body:
I'm Facing current porblem.
I have an Array of 100 Bitmaps. these are Screenshots i took from a view.
I used JCodec to make it to a video, buts its waay to slow. Im hoping to get better results with FFmpeg

Now i want to use the FFmpeg Library. Simillar questions were asked but i have no Idea how to use ffmpeg and how i have to use it in my specific case. All i see are weird Complex Commands See:

 File dir = your directory where image stores;
    String filePrefix = "picture"; //imagename prefix
    String fileExtn = ".jpg";//image extention
    filePath = dir.getAbsolutePath();
    File src = new File(dir, filePrefix + "%03d" + fileExtn);// image name should ne picture001, picture002,picture003 soon  ffmpeg takes as input valid

complexCommand = new String[]{"-i", src + "", "-c:v", "libx264", "-c:a", "aac", "-vf", "setpts=2*PTS", "-pix_fmt", "yuv420p", "-crf", "10", "-r", "15", "-shortest", "-y", "/storage/emulated/0/" + app_name + "/Video/" + app_name + "_Video" + number + ".mp4"};

The Problem is, that in this case he is using a Path. I need it to be from an Array. And i have no idea what to do with the String (ComplexCommands) :/
My Bitmaps are like this:

Bitmap[] bitmaps = new Bitmaps[100];

this is filled later on.

if anyone is searching on how to do it with JCodec:

 try {
                    out = NIOUtils.writableFileChannel( Environment.getExternalStorageDirectory().getAbsolutePath()+"/***yourpath***/output"+System.currentTimeMillis()+".mp4");
                    // for Android use: AndroidSequenceEncoder

                    AndroidSequenceEncoder encoder = new AndroidSequenceEncoder(out, Rational.R(25, 1));
                    for (int i = 0 ; i < 100 ; i++) {
                        // Generate the image, for Android use Bitmap

                        // Encode the image
                        System.out.println("LOO2P"+i);
                        encoder.encodeImage(bitmaps[i]);
                    }
                    // Finalize the encoding, i.e. clear the buffers, write the header, etc.
                    encoder.finish();

                } catch (FileNotFoundException e) {
                    System.out.println("fNF");
                    e.printStackTrace();

                } catch (IOException e) {
                    System.out.println("IOE");
                    e.printStackTrace();
                } finally {
                    System.out.println("IOSSE");
                    NIOUtils.closeQuietly(out);
                }

Body:
According to the the ffmpeg wiki, the way you described is exactly how it is intended to be done. To implement this you should write each image from your array into a single file according to the described naming conventions. I don't know if this will help with your performance issues though.
Writing the images to files can be done following this answer:

for (int i = 0; i<bitmapArray.length(); i++){
    // Write to file while incrementing the file name
    writeToFile(bitmapArray[i], i);
}

As far as I could find, ffmpeg does not support directly encoding from an array.


问:
Android design support library for API 28 (P) not working
I've configured android-P SDK environment successfully. When I attempt to use the android design support library I face project build errors. Project configurations are:

IDE: 3.2 Canary 17 Target API: 28 Compile API: 28

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.app.navigationpoc"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.0-alpha3'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.1'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha3'

    implementation 'com.android.support:design:28.0.0-alpha3'
    implementation 'com.android.support:cardview-v7:28.0.0-alpha3'
}
</code>```

And build failed error is:

Manifest merger failed : Attribute application@appComponentFactory
  value=(androidx.core.app.CoreComponentFactory) from
  [androidx.core:core:1.0.0-alpha3] AndroidManifest.xml:22:18-86    is
  also present at [com.android.support:support-compat:28.0.0-alpha3]
  AndroidManifest.xml:22:18-91
  value=(android.support.v4.app.CoreComponentFactory).  Suggestion: add
  'tools:replace="android:appComponentFactory"' to  element
  at AndroidManifest.xml:6:5-40:19 to override.

答:
if you want to solve this problem without migrating to AndroidX (I don't recommend it)

this manifest merger issue is related to one of your dependency using androidX.

you need to decrease this dependency's release version.
for my case :

I was using google or firebase

```<code>api 'com.google.android.gms:play-services-base:17.1.0'
</code>```

I have to decrease it 15.0.1 to use in support library.

Body:
I've configured android-P SDK environment successfully. When I attempt to use the android design support library I face project build errors. Project configurations are:

IDE: 3.2 Canary 17 Target API: 28 Compile API: 28

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.app.navigationpoc"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.0-alpha3'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.1'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha3'

    implementation 'com.android.support:design:28.0.0-alpha3'
    implementation 'com.android.support:cardview-v7:28.0.0-alpha3'
}

And build failed error is:

Manifest merger failed : Attribute application@appComponentFactory
  value=(androidx.core.app.CoreComponentFactory) from
  [androidx.core:core:1.0.0-alpha3] AndroidManifest.xml:22:18-86    is
  also present at [com.android.support:support-compat:28.0.0-alpha3]
  AndroidManifest.xml:22:18-91
  value=(android.support.v4.app.CoreComponentFactory).  Suggestion: add
  'tools:replace="android:appComponentFactory"' to  element
  at AndroidManifest.xml:6:5-40:19 to override.

Body:
if you want to solve this problem without migrating to AndroidX (I don't recommend it)

this manifest merger issue is related to one of your dependency using androidX.

you need to decrease this dependency's release version.
for my case :

I was using google or firebase

api 'com.google.android.gms:play-services-base:17.1.0'

I have to decrease it 15.0.1 to use in support library.


问:
Summing over lists of arbitrary levels of nestedness in F#
I'm trying to create an F# function that will return the sum of a list of ints of arbitrary nestedness. Ie. it will work for a list<int>, a list<list<int>> and a list<list<list<list<list<list<int>>>>>>.

In Haskell I would write something like:

```<code>class HasSum a where
    getSum :: a -> Integer

instance HasSum Integer where
    getSum = id

instance HasSum a => HasSum [a] where
    getSum = sum . map getSum
</code>```

which would let me do:

```<code>list :: a -> [a]
list = replicate 6

nestedList :: [[[[[[[[[[Integer]]]]]]]]]]
nestedList =
    list $ list $ list $ list $ list $
    list $ list $ list $ list $ list (1 :: Integer)

sumNestedList :: Integer
sumNestedList = getSum nestedList
</code>```

Link to runnable code.

How can I achieve this in F#?

答:
UPDATE

I found a simpler version using an operator ($) instead of a member.
Inspired by https://stackoverflow.com/a/7224269/4550898 :

```<code>type SumOperations = SumOperations

let inline getSum b = SumOperations $ b // <-- puting this here avoids defaulting to int

type SumOperations with
    static member inline ($) (SumOperations, x  : int     ) = x
    static member inline ($) (SumOperations, xl : _   list) = xl |> List.sumBy getSum
</code>```

The rest of the explanation still applies and it is useful...

I found a way to make it possible:

```<code>let inline getSum0< ^t, ^a when (^t or ^a) : (static member Sum : ^a -> int)> a : int =
    ((^t or ^a) : (static member Sum : ^a -> int) a)

type SumOperations =
    static member inline Sum( x : float   ) = int x
    static member inline Sum( x : int     ) =  x
    static member inline Sum(lx : _   list) = lx |> List.sumBy getSum0<SumOperations, _>

let inline getSum x = getSum0<SumOperations, _> x

2                  |> getSum |> printfn "%d" // = 2
[ 2 ; 1 ]          |> getSum |> printfn "%d" // = 3
[[2; 3] ; [4; 5] ] |> getSum |> printfn "%d" // = 14
</code>```

Running your example:

```<code>let list v = List.replicate 6 v

1
|> list |> list |> list |> list |> list
|> list |> list |> list |> list |> list
|> getSum |> printfn "%d" // = 60466176
</code>```

This is based on using SRTPs with member constraints: static member Sum,
the constraint requires the type to have a member called Sum
that returns an int. When using SRTPs generic functions
need to be inline.

That is not the difficult part. The hard part is "adding" Sum member to
an existing type like int and List which is not allowed. But, we can add
it to a new type SumOperations and include in the constraint (^t or ^a)
where ^t is always going to be SumOperations.

getSum0 declares the Sum member constraint and invokes it.

getSum  passes SumOperations as the first type parameter to getSum0

The line static member inline Sum(x  : float   ) = int x was added
to convince the compiler to use a generic dynamic function call and
not just default to static member inline Sum(x  : int     ) when
calling List.sumBy

As you can see is a bit convoluted, the syntax is complex
and it was necessary to work around
some quirks on the compiler but in the end it was possible.

This method can be extended to work with Arrays, tuples, options, etc. or any combination of them by adding more definitions to SumOperations:

```<code>type SumOperations with
    static member inline ($) (SumOperations, lx : _   []  ) = lx |> Array.sumBy getSum
    static member inline ($) (SumOperations, a  : ^a * ^b ) = match a with a, b -> getSum a + getSum b
    static member inline ($) (SumOperations, ox : _ option) = ox |> Option.map getSum |> Option.defaultValue 0

(Some 3, [| 2 ; 1 |]) |> getSum |> printfn "%d" // = 6
</code>```

https://dotnetfiddle.net/03rVWT

Body:
I'm trying to create an F# function that will return the sum of a list of ints of arbitrary nestedness. Ie. it will work for a list<int>, a list<list<int>> and a list<list<list<list<list<list<int>>>>>>.

In Haskell I would write something like:

class HasSum a where
    getSum :: a -> Integer

instance HasSum Integer where
    getSum = id

instance HasSum a => HasSum [a] where
    getSum = sum . map getSum

which would let me do:

list :: a -> [a]
list = replicate 6

nestedList :: [[[[[[[[[[Integer]]]]]]]]]]
nestedList =
    list $ list $ list $ list $ list $
    list $ list $ list $ list $ list (1 :: Integer)

sumNestedList :: Integer
sumNestedList = getSum nestedList

Link to runnable code.

How can I achieve this in F#?

Body:
UPDATE

I found a simpler version using an operator ($) instead of a member.
Inspired by https://stackoverflow.com/a/7224269/4550898 :

type SumOperations = SumOperations

let inline getSum b = SumOperations $ b // <-- puting this here avoids defaulting to int

type SumOperations with
    static member inline ($) (SumOperations, x  : int     ) = x
    static member inline ($) (SumOperations, xl : _   list) = xl |> List.sumBy getSum

The rest of the explanation still applies and it is useful...

I found a way to make it possible:

let inline getSum0< ^t, ^a when (^t or ^a) : (static member Sum : ^a -> int)> a : int =
    ((^t or ^a) : (static member Sum : ^a -> int) a)

type SumOperations =
    static member inline Sum( x : float   ) = int x
    static member inline Sum( x : int     ) =  x
    static member inline Sum(lx : _   list) = lx |> List.sumBy getSum0<SumOperations, _>

let inline getSum x = getSum0<SumOperations, _> x

2                  |> getSum |> printfn "%d" // = 2
[ 2 ; 1 ]          |> getSum |> printfn "%d" // = 3
[[2; 3] ; [4; 5] ] |> getSum |> printfn "%d" // = 14

Running your example:

let list v = List.replicate 6 v

1
|> list |> list |> list |> list |> list
|> list |> list |> list |> list |> list
|> getSum |> printfn "%d" // = 60466176

This is based on using SRTPs with member constraints: static member Sum,
the constraint requires the type to have a member called Sum
that returns an int. When using SRTPs generic functions
need to be inline.

That is not the difficult part. The hard part is "adding" Sum member to
an existing type like int and List which is not allowed. But, we can add
it to a new type SumOperations and include in the constraint (^t or ^a)
where ^t is always going to be SumOperations.

getSum0 declares the Sum member constraint and invokes it.

getSum  passes SumOperations as the first type parameter to getSum0

The line static member inline Sum(x  : float   ) = int x was added
to convince the compiler to use a generic dynamic function call and
not just default to static member inline Sum(x  : int     ) when
calling List.sumBy

As you can see is a bit convoluted, the syntax is complex
and it was necessary to work around
some quirks on the compiler but in the end it was possible.

This method can be extended to work with Arrays, tuples, options, etc. or any combination of them by adding more definitions to SumOperations:

type SumOperations with
    static member inline ($) (SumOperations, lx : _   []  ) = lx |> Array.sumBy getSum
    static member inline ($) (SumOperations, a  : ^a * ^b ) = match a with a, b -> getSum a + getSum b
    static member inline ($) (SumOperations, ox : _ option) = ox |> Option.map getSum |> Option.defaultValue 0

(Some 3, [| 2 ; 1 |]) |> getSum |> printfn "%d" // = 6

https://dotnetfiddle.net/03rVWT


问:
RapidJSON - using wildcards to iterate through complex JSON structures with different member names
I have a complex JSON to load into a data structure in C++11 and I got high recommendations about RapidJSON. I need to iterate over a complex JSON and looked around for answers on how to do it. The best answer I found was in this thread.

However, there's a small glitch in matching this solution to mine, I have members in the JSON that have different names but identical content:

```<code>"responsibilities": {
  "starters_reciepe": {
    "name": "bok choi salad",
    "type": "veggie",
    "ingredients": {
      "leafyIng": "bok choi",
      "proteinIng": "tofu",
      "seasoning": [
        {
          "2 tsp": "salt",
          "1 tsp": "turmric"
        }
      ]
    }
  },
  "mainCourse_reciepe": {
    "name": "pad tai",
    "type": "yum yum",
    "ingredients": {
      "leafyIng": "chard",
      "proteinIng": "soylent green"
      "seasoning": [
        {
          "2 tsp": "black pepper",
          "1 tsp": "tears of the angels"
        }
      ]
    }
}
</code>```

}

Basically, I need to go over the content of the ingredients, but I can't get over the fact that starters_reciepe is not like mainCourse_reciepe.

EDITED:
Here's my code:

```<code>Document d;

ifstream in("TestingJSON.json", ios::binary);
if (!in)
    throw runtime_error("Failed to open file");

istreambuf_iterator<char> head(in);
istreambuf_iterator<char> tail;
string data(head, tail);

d.Parse(data.c_str());

const Value& prog = d["responsibilities"];
for (Value::ConstValueIterator p = prog.Begin(); p != prog.End(); ++p) {
cout << (*p)["iUniqueID"].GetString()<<endl;
    const Value& inFiles = (*p)["inFiles"];
    for (Value::ConstValueIterator inFile = inFiles.Begin(); inFile != prog.End(); ++inFile) {
        cout << (*inFile)["sFileType"].GetString() << endl;
        cout << (*inFile)["pos"]["x1"].GetInt() << endl;
    }
}
</code>```

Can I use wildcards and write *_reciepe?

I could find anything on RapidJSON and wildcards. Is this even a possibility?

答:
Always validate your raw JSON with linters (e.g. https://jsonlint.com/). This JSON in your question is not valid. You need to fix that.

The "responsibilites" object in your JSON contains recipes only. I'm not sure why you need to compare it with *_recipe. But, given the example below, you may easily implement that comparison if needed. This thread might be helpful in this regard.

You can use C++11's range-based for loop for these iterations. Just take care of the correct type you want to use/manipulate according to your use-case. If in doubt, consult rapidjson's tutorial and documentation.

Here's an example with raw literal string as JSON input:

```<code>#include <iostream>
#include <rapidjson/document.h>

int main()
{
    constexpr auto data = R"json(
    {
      "responsibilities": {
          "starters_recipe": {
              "name": "bok choi salad",
              "type": "veggie",
              "ingredients": {
                  "leafyIng": "bok choi",
                  "proteinIng": "tofu",
                  "seasoning": [{
                      "2 tsp": "salt",
                      "1 tsp": "turmric"
                  }]
              }
          },
          "mainCourse_recipe": {
              "name": "pad tai",
              "type": "yum yum",
              "ingredients": {
                  "leafyIng": "chard",
                  "proteinIng": "soylent green",
                  "seasoning": [{
                      "2 tsp": "black pepper",
                      "1 tsp": "tears of the angels"
                  }]
              }
          }
      }
    }
    )json";

    rapidjson::Document doc;
    doc.Parse( data );

    const auto& courses = doc["responsibilities"].GetObject();
    for ( const auto& course : courses )
    {
        const auto& course_name = course.name.GetString();
        const auto& recipe      = courses[course_name].GetObject();
        const auto& recipe_name = recipe["name"].GetString();
        const auto& ingredients = recipe["ingredients"].GetObject();
        const auto& leafyIng    = ingredients["leafyIng"].GetString();
        const auto& proteinIng  = ingredients["proteinIng"].GetString();
        const auto& seasoning   = ingredients["seasoning"].GetArray()[0].GetObject();

        std::cout << "Course: " << course_name << '\n'
                  << "Recipe: " << recipe_name << '\n'
                  << "Ingredients:\n"
                  << "- Leaf     : " << leafyIng << '\n'
                  << "- Protein  : " << proteinIng << '\n'
                  << "- Seasoning:\n";

        for ( const auto& s : seasoning )
        {
            const auto& k = s.name.GetString();
            const auto& v = s.value.GetString();
            std::cout << "  - " << k << ", " << v << '\n';
        }

        std::cout << '\n';
    }

    return 0;
}
</code>```

Output:

```<code>Course: starters_recipe
Recipe: bok choi salad
Ingredients:
- Leaf     : bok choi
- Protein  : tofu
- Seasoning:
  - 2 tsp, salt
  - 1 tsp, turmric

Course: mainCourse_recipe
Recipe: pad tai
Ingredients:
- Leaf     : chard
- Protein  : soylent green
- Seasoning:
  - 2 tsp, black pepper
  - 1 tsp, tears of the angels
</code>```

The "seasoning" array contains only one object that's why this line refers to the 0th index:

```<code>const auto& seasoning = ingredients["seasoning"].GetArray()[0].GetObject();
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^
</code>```

I guess that you intended to have an array of objects, not an array with a single object.

This:

```<code>"seasoning": [
     { "2 tsp": "black pepper" },
     {  "1 tsp": "tears of the angels" }
]
</code>```

and, not this:

```<code>"seasoning": [{
      "2 tsp": "black pepper",
      "1 tsp": "tears of the angels"
}]
</code>```

You have to manipulate this accordingly in code also.

Body:
I have a complex JSON to load into a data structure in C++11 and I got high recommendations about RapidJSON. I need to iterate over a complex JSON and looked around for answers on how to do it. The best answer I found was in this thread.

However, there's a small glitch in matching this solution to mine, I have members in the JSON that have different names but identical content:

"responsibilities": {
  "starters_reciepe": {
    "name": "bok choi salad",
    "type": "veggie",
    "ingredients": {
      "leafyIng": "bok choi",
      "proteinIng": "tofu",
      "seasoning": [
        {
          "2 tsp": "salt",
          "1 tsp": "turmric"
        }
      ]
    }
  },
  "mainCourse_reciepe": {
    "name": "pad tai",
    "type": "yum yum",
    "ingredients": {
      "leafyIng": "chard",
      "proteinIng": "soylent green"
      "seasoning": [
        {
          "2 tsp": "black pepper",
          "1 tsp": "tears of the angels"
        }
      ]
    }
}

}

Basically, I need to go over the content of the ingredients, but I can't get over the fact that starters_reciepe is not like mainCourse_reciepe.

EDITED:
Here's my code:

Document d;

ifstream in("TestingJSON.json", ios::binary);
if (!in)
    throw runtime_error("Failed to open file");

istreambuf_iterator<char> head(in);
istreambuf_iterator<char> tail;
string data(head, tail);

d.Parse(data.c_str());

const Value& prog = d["responsibilities"];
for (Value::ConstValueIterator p = prog.Begin(); p != prog.End(); ++p) {
cout << (*p)["iUniqueID"].GetString()<<endl;
    const Value& inFiles = (*p)["inFiles"];
    for (Value::ConstValueIterator inFile = inFiles.Begin(); inFile != prog.End(); ++inFile) {
        cout << (*inFile)["sFileType"].GetString() << endl;
        cout << (*inFile)["pos"]["x1"].GetInt() << endl;
    }
}

Can I use wildcards and write *_reciepe?

I could find anything on RapidJSON and wildcards. Is this even a possibility?

Body:
Always validate your raw JSON with linters (e.g. https://jsonlint.com/). This JSON in your question is not valid. You need to fix that.

The "responsibilites" object in your JSON contains recipes only. I'm not sure why you need to compare it with *_recipe. But, given the example below, you may easily implement that comparison if needed. This thread might be helpful in this regard.

You can use C++11's range-based for loop for these iterations. Just take care of the correct type you want to use/manipulate according to your use-case. If in doubt, consult rapidjson's tutorial and documentation.

Here's an example with raw literal string as JSON input:

#include <iostream>
#include <rapidjson/document.h>

int main()
{
    constexpr auto data = R"json(
    {
      "responsibilities": {
          "starters_recipe": {
              "name": "bok choi salad",
              "type": "veggie",
              "ingredients": {
                  "leafyIng": "bok choi",
                  "proteinIng": "tofu",
                  "seasoning": [{
                      "2 tsp": "salt",
                      "1 tsp": "turmric"
                  }]
              }
          },
          "mainCourse_recipe": {
              "name": "pad tai",
              "type": "yum yum",
              "ingredients": {
                  "leafyIng": "chard",
                  "proteinIng": "soylent green",
                  "seasoning": [{
                      "2 tsp": "black pepper",
                      "1 tsp": "tears of the angels"
                  }]
              }
          }
      }
    }
    )json";

    rapidjson::Document doc;
    doc.Parse( data );

    const auto& courses = doc["responsibilities"].GetObject();
    for ( const auto& course : courses )
    {
        const auto& course_name = course.name.GetString();
        const auto& recipe      = courses[course_name].GetObject();
        const auto& recipe_name = recipe["name"].GetString();
        const auto& ingredients = recipe["ingredients"].GetObject();
        const auto& leafyIng    = ingredients["leafyIng"].GetString();
        const auto& proteinIng  = ingredients["proteinIng"].GetString();
        const auto& seasoning   = ingredients["seasoning"].GetArray()[0].GetObject();

        std::cout << "Course: " << course_name << '\n'
                  << "Recipe: " << recipe_name << '\n'
                  << "Ingredients:\n"
                  << "- Leaf     : " << leafyIng << '\n'
                  << "- Protein  : " << proteinIng << '\n'
                  << "- Seasoning:\n";

        for ( const auto& s : seasoning )
        {
            const auto& k = s.name.GetString();
            const auto& v = s.value.GetString();
            std::cout << "  - " << k << ", " << v << '\n';
        }

        std::cout << '\n';
    }

    return 0;
}

Output:

Course: starters_recipe
Recipe: bok choi salad
Ingredients:
- Leaf     : bok choi
- Protein  : tofu
- Seasoning:
  - 2 tsp, salt
  - 1 tsp, turmric

Course: mainCourse_recipe
Recipe: pad tai
Ingredients:
- Leaf     : chard
- Protein  : soylent green
- Seasoning:
  - 2 tsp, black pepper
  - 1 tsp, tears of the angels

The "seasoning" array contains only one object that's why this line refers to the 0th index:

const auto& seasoning = ingredients["seasoning"].GetArray()[0].GetObject();
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^

I guess that you intended to have an array of objects, not an array with a single object.

This:

"seasoning": [
     { "2 tsp": "black pepper" },
     {  "1 tsp": "tears of the angels" }
]

and, not this:

"seasoning": [{
      "2 tsp": "black pepper",
      "1 tsp": "tears of the angels"
}]

You have to manipulate this accordingly in code also.


问:
6 Month Daily Survey Database with Identical Fields
I'm trying to create a database to manage my 50+ and growing excel tables
* I'm surveying employees over time
*I ask them a question and they can answer 1 of 8 responses
*The Employees have different work schedules, so it's not the exact same people everyday

The tables are..... in 4 columns  ( I have a table for each day) 50+ Days

Name of Worker   Morning-Question   11am-Question     2pm-Question

I put the tables into MySQL, I'm trying to pull up queries for name= "Tony James" so I can see all of his responses in the 50 days, any suggestions??  of if you have any better idea's to structure the information I would be most appreciative,

Thanks

Stacy

答:
You should create a users table like this:

```<code>ID    Name
1     Tony James
</code>```

Then in the other table reference that like so:

```<code>ID    UserID     Morning-Question     11am-Question     2pm-Question
1     1          blah blah            blah blah         blah blah
</code>```

You could then run this query:

```<code>Select * from Questions q
join Users u
on q.UserID = u.id
where u.name = 'Tony James'
</code>```

Body:
You should create a users table like this:

ID    Name
1     Tony James

Then in the other table reference that like so:

ID    UserID     Morning-Question     11am-Question     2pm-Question
1     1          blah blah            blah blah         blah blah

You could then run this query:

Select * from Questions q
join Users u
on q.UserID = u.id
where u.name = 'Tony James'


问:
Continuously sending data from Python Flask server to client through Websockets
I am setting up a dashboard which requires a Python Flask server to fetch public transport data once every few seconds or so and send this data to a client webpage through websockets. I am using FlaskSocketIO to achieve this.

I am able to send a message upon the 'connect' event, for example, but I've been unable to find a way to continuously update this message. This is my approach:

from flask import Flask, render_template, url_for, request
from flask_socketio import SocketIO, emit, send
import eventlet
eventlet.monkey_patch()

app = Flask(__name__)
socketio = SocketIO(app, logger=True, engineio_logger=True)

def listen():
    while True:
        message = # some updating message
        emit('message', message)
        socketio.sleep(1)

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('connect')
def handle_connect():
    listen()

if __name__ == "__main__":
    socketio.run(app, debug=True)
```

<p>The logger says it sends the message. However, on the client side, no message is recieved. The client side JavaScript is:</p>

<pre class="lang-js prettyprint-override"><code>var socket = io();

socket.on('message', function(msg) {
    console.log(msg);
});
</code>```

答:
i have the same problem with you, in my case i wanted to update sensor dashboard, so i study about Observer Pattern, this link is really good Observer Pattern.Implement a SocketEmitObservator, using the Observer you dont need to create a listener(infinite while loop) and make your code more clean:

```<code>class SensorObserver(Observer):
    sensor_id: int
    sid = ''

    def __init__(self, sid,sensor_id=None):
        Observer.__init__(self)
        self.sensor_id = sensor_id
        self.sid = sid
        SensorPublisher().attach(self)

    def update(self, sensorData: DataModel) -> None:
        socket.emit("info",
                        {'sensor': subject},
                        namespace='/api/sector/machine',
                        room=self.sid)

    def __del__(self):
        SensorPublisher().detach(self)

class SensorPublisher(Subject, Singleton):
    _observers: List[SensorObserver] = []
    _sensorData: Dict[str, DataModel] = {}

    def attach(self, observer: SensorObserver) -> None:
        if observer not in self._observers:
            self._observers.append(observer)

    def notify(self, sensorModel: DataModel) -> None:
        for observer in self._observers:
            if sensorModel.sensor_id == observer.sensor_id:
                observer.update(sensorModel)

    def detach(self, observer: SensorObserver) -> None:
        if observer in self._observers:
            ob = self._observers.pop(self._observers.index(observer))
            del ob

    def update(self, sensorModel: DataModel):
        sendorId: str = str(sensorModel.sensor_id)
        self._sensorData[sendorId] = sensorModel
        self.notify(sensorModel)

#### And in the place where i update sensor data i put
SensorPublisher().update(dataStructList)

#### To create a observr just do
@socketio.on('connect')
def handle_connect():
    SensorObserver(self.sid, item)

</code>```

In my case i use like this, but you can adapt for your problem

Body:
I am setting up a dashboard which requires a Python Flask server to fetch public transport data once every few seconds or so and send this data to a client webpage through websockets. I am using FlaskSocketIO to achieve this.

I am able to send a message upon the 'connect' event, for example, but I've been unable to find a way to continuously update this message. This is my approach:

from flask import Flask, render_template, url_for, request
from flask_socketio import SocketIO, emit, send
import eventlet
eventlet.monkey_patch()

app = Flask(__name__)
socketio = SocketIO(app, logger=True, engineio_logger=True)

def listen():
    while True:
        message = # some updating message
        emit('message', message)
        socketio.sleep(1)

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('connect')
def handle_connect():
    listen()

if __name__ == "__main__":
    socketio.run(app, debug=True)

The logger says it sends the message. However, on the client side, no message is recieved. The client side JavaScript is:

var socket = io();

socket.on('message', function(msg) {
    console.log(msg);
});

Body:
i have the same problem with you, in my case i wanted to update sensor dashboard, so i study about Observer Pattern, this link is really good Observer Pattern.Implement a SocketEmitObservator, using the Observer you dont need to create a listener(infinite while loop) and make your code more clean:

class SensorObserver(Observer):
    sensor_id: int
    sid = ''

    def __init__(self, sid,sensor_id=None):
        Observer.__init__(self)
        self.sensor_id = sensor_id
        self.sid = sid
        SensorPublisher().attach(self)

    def update(self, sensorData: DataModel) -> None:
        socket.emit("info",
                        {'sensor': subject},
                        namespace='/api/sector/machine',
                        room=self.sid)

    def __del__(self):
        SensorPublisher().detach(self)

class SensorPublisher(Subject, Singleton):
    _observers: List[SensorObserver] = []
    _sensorData: Dict[str, DataModel] = {}

    def attach(self, observer: SensorObserver) -> None:
        if observer not in self._observers:
            self._observers.append(observer)

    def notify(self, sensorModel: DataModel) -> None:
        for observer in self._observers:
            if sensorModel.sensor_id == observer.sensor_id:
                observer.update(sensorModel)

    def detach(self, observer: SensorObserver) -> None:
        if observer in self._observers:
            ob = self._observers.pop(self._observers.index(observer))
            del ob

    def update(self, sensorModel: DataModel):
        sendorId: str = str(sensorModel.sensor_id)
        self._sensorData[sendorId] = sensorModel
        self.notify(sensorModel)

#### And in the place where i update sensor data i put
SensorPublisher().update(dataStructList)

#### To create a observr just do
@socketio.on('connect')
def handle_connect():
    SensorObserver(self.sid, item)

In my case i use like this, but you can adapt for your problem


问:
ES6 Import Scenario
There are multiple way to import modules. What is the difference between import {House} and import House?

答:
The syntax import {House} is used to import specific, named imports like import {foo, bar} from '/modules/my-module.js';

while the syntax import House is used to import default exports like import myDefault from '/modules/my-module.js';

As one can see that we can mix these two. For example, this is also a valid import
  import myDefault, {foo, bar} from '/modules/my-module.js';

to read more checkout Mozilla developer guide.

Title: ES6 Import Scenario


问:
How do I send an e-mail in Java?
I need to send e-mails from a servlet running within Tomcat. I'll always send to the same recipient with the same subject, but with different contents.

What's a simple, easy way to send an e-mail in Java?

Related:

How do you send email from a Java app using GMail?

答:
Tested Code send Mail with attachment :

```<code>  public class SendMailNotificationWithAttachment {

            public static void mailToSendWithAttachment(String messageTosend, String snapShotFile) {

                String to = Constants.MailTo;
                String from = Constants.MailFrom;
                String host = Constants.smtpHost;// or IP address
                String subject = Constants.subject;
                // Get the session object
                Properties properties = System.getProperties();
                properties.setProperty("mail.smtp.host", host);
                Session session = Session.getDefaultInstance(properties);
                try {
                    MimeMessage message = new MimeMessage(session);
                    message.setFrom(new InternetAddress(from));
                    message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
                    message.setSubject(subject);
                    // message.setText(messageTosend);
                    BodyPart messageBodyPart = new MimeBodyPart();
                    messageBodyPart.setText(messageTosend);
                    Multipart multipart = new MimeMultipart();
                    multipart.addBodyPart(messageBodyPart);

                    messageBodyPart = new MimeBodyPart();
                    String filepath = snapShotFile;

                    DataSource source = new FileDataSource(filepath);
                    messageBodyPart.setDataHandler(new DataHandler(source));

                    Path p = Paths.get(filepath);
                    String NameOffile = p.getFileName().toString();

                    messageBodyPart.setFileName(NameOffile);
                    multipart.addBodyPart(messageBodyPart);

                    // Send the complete message parts
                    message.setContent(multipart);

                    // Send message
                    Transport.send(message);

        //          Log.info("Message is sent Successfully");
        //          System.out.println("Message is sent Successfully");
                    System.out.println("Message is sent Successfully");
    } catch (MessagingException e) {
    //          Log.error("Mail sending is Failed " + "due to" + e);
                SendMailNotificationWithAttachment smnwa = new SendMailNotificationWithAttachment();
                smnwa.mailSendFailed(e);
                throw new RuntimeException(e);
            }
        }
public void mailSendFailed(MessagingException e) {
        System.out.println("Mail sending is Failed " + "due to" + e);
        Log log = new Log();
        log.writeIntoLog("Mail sending is Failed " + "due to" + e.toString(), false);
    }

}
</code>```

ContentLicense: CC BY-SA 2.5

Title: How do I send an e-mail in Java?

Body:
Tested Code send Mail with attachment :

  public class SendMailNotificationWithAttachment {

            public static void mailToSendWithAttachment(String messageTosend, String snapShotFile) {

                String to = Constants.MailTo;
                String from = Constants.MailFrom;
                String host = Constants.smtpHost;// or IP address
                String subject = Constants.subject;
                // Get the session object
                Properties properties = System.getProperties();
                properties.setProperty("mail.smtp.host", host);
                Session session = Session.getDefaultInstance(properties);
                try {
                    MimeMessage message = new MimeMessage(session);
                    message.setFrom(new InternetAddress(from));
                    message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
                    message.setSubject(subject);
                    // message.setText(messageTosend);
                    BodyPart messageBodyPart = new MimeBodyPart();
                    messageBodyPart.setText(messageTosend);
                    Multipart multipart = new MimeMultipart();
                    multipart.addBodyPart(messageBodyPart);

                    messageBodyPart = new MimeBodyPart();
                    String filepath = snapShotFile;

                    DataSource source = new FileDataSource(filepath);
                    messageBodyPart.setDataHandler(new DataHandler(source));

                    Path p = Paths.get(filepath);
                    String NameOffile = p.getFileName().toString();

                    messageBodyPart.setFileName(NameOffile);
                    multipart.addBodyPart(messageBodyPart);

                    // Send the complete message parts
                    message.setContent(multipart);

                    // Send message
                    Transport.send(message);

        //          Log.info("Message is sent Successfully");
        //          System.out.println("Message is sent Successfully");
                    System.out.println("Message is sent Successfully");
    } catch (MessagingException e) {
    //          Log.error("Mail sending is Failed " + "due to" + e);
                SendMailNotificationWithAttachment smnwa = new SendMailNotificationWithAttachment();
                smnwa.mailSendFailed(e);
                throw new RuntimeException(e);
            }
        }
public void mailSendFailed(MessagingException e) {
        System.out.println("Mail sending is Failed " + "due to" + e);
        Log log = new Log();
        log.writeIntoLog("Mail sending is Failed " + "due to" + e.toString(), false);
    }

}


问:
503 error pushing to remote
I am encountering a 503 error pushing to Github:

```<code>$ git push github develop
Counting objects: 22, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (22/22), done.
Writing objects: 100% (22/22), 4.16 KiB | 0 bytes/s, done.
Total 22 (delta 16), reused 0 (delta 0)
error: RPC failed; HTTP 503 curl 22 The requested URL returned error: 503 Service Unavailable
fatal: The remote end hung up unexpectedly
fatal: The remote end hung up unexpectedly
Everything up-to-date
</code>```

I've checked their status page and "All systems operational" so I'm thinking it must be something with my configuration. My .gitconfig file just have my name and email:

```<code>[user]
    name = Bradley Wogsland
    email = <omitted>
</code>```

(I've omitted my real email here but in the actual file it's there).

答:
I faced the same issue. Tried setting my global email to my account's email as:

```<code>git config ---global user.email MY_GIT_EMAIL
</code>```

then tried

```<code>git push
</code>```

and it worked for me.

Title: 503 error pushing to remote

Body:
I am encountering a 503 error pushing to Github:

$ git push github develop
Counting objects: 22, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (22/22), done.
Writing objects: 100% (22/22), 4.16 KiB | 0 bytes/s, done.
Total 22 (delta 16), reused 0 (delta 0)
error: RPC failed; HTTP 503 curl 22 The requested URL returned error: 503 Service Unavailable
fatal: The remote end hung up unexpectedly
fatal: The remote end hung up unexpectedly
Everything up-to-date

I've checked their status page and "All systems operational" so I'm thinking it must be something with my configuration. My .gitconfig file just have my name and email:

[user]
    name = Bradley Wogsland
    email = <omitted>

(I've omitted my real email here but in the actual file it's there).

Body:
I faced the same issue. Tried setting my global email to my account's email as:

git config ---global user.email MY_GIT_EMAIL

then tried

git push

and it worked for me.


问:
Combining words from two lists
I'm experimenting and having a look at creating a randomizer from two lists.

```<code>$List = ’Red’,’Pink’,’Green’
$List1 = ’Warning’,’Election’,’Marriage’
</code>```

What I'm looking to do is pick a random word from $List and $List1. I'm aware that you can pick from a singular with :

Get-Random -InputObject $List

However, I'm not quite sure how I would be able to grab from both lists and combine them.

My expected output would be:

RedMarriage

PinkWarning

GreenElection

答:
Why not just continue your current logic and perform two Get-Random commands? Then you can just use your favorite way to combine two strings.

```<code>"{0}{1}" -f (Get-Random -InputObject $List),(Get-Random -InputObject $List1)
</code>```

If you are looking for a concise, single Get-Random command to do the job, I think you will need to add more complexity to the code.

Title: Combining words from two lists

Body:
I'm experimenting and having a look at creating a randomizer from two lists.

$List = ’Red’,’Pink’,’Green’
$List1 = ’Warning’,’Election’,’Marriage’

What I'm looking to do is pick a random word from $List and $List1. I'm aware that you can pick from a singular with :

Get-Random -InputObject $List

However, I'm not quite sure how I would be able to grab from both lists and combine them.

My expected output would be:

RedMarriage

PinkWarning

GreenElection

Body:
Why not just continue your current logic and perform two Get-Random commands? Then you can just use your favorite way to combine two strings.

"{0}{1}" -f (Get-Random -InputObject $List),(Get-Random -InputObject $List1)

If you are looking for a concise, single Get-Random command to do the job, I think you will need to add more complexity to the code.


问:
Chart.js display x axis labels ON ticks in bar chart, not between
I have this chart:

...which is displaying exactly how I want it to with one exception... The data in the bars is for between the two times in the x axis... so all the labels need shifting to lie on the grid lines, not between them as default for a bar chart. So the red and blue bar is data between 8:00 and 9:00. I hope I've explained that clearly enough.

I'm trawling through the Chart.js docs and it just doesn't seem like this is possible! I know I could change my labels to be, for example, 8pm - 9pm, but that seems a much more visually clunky way of doing it. Is there a way anyone know of achieving this? Ideally there would be another '12am' on the last vertical grid line too.

答:
You can draw the tick lables at the desired position directly on to the canvas using the Plugin Core API. It offers number of hooks that may be used for performing custom code. In below code snippet, I use the afterDraw hook to draw my own labels on the xAxis.

const hours = ['00', '01', '02', '03', '04', '05', '06'];
const values = [0, 0, 0, 0, 10, 6, 0];

const chart = new Chart(document.getElementById('myChart'), {
  type: 'bar',
  plugins: [{
    afterDraw: chart => {
      var xAxis = chart.scales['x-axis-0'];
      var tickDistance = xAxis.width / (xAxis.ticks.length - 1);
      xAxis.ticks.forEach((value, index) => {
        if (index > 0) {
          var x = -tickDistance + tickDistance * 0.66 + tickDistance * index;
          var y = chart.height - 10;
          chart.ctx.save();
          chart.ctx.fillText(value == '0am' ? '12am' : value, x, y);
          chart.ctx.restore();
        }
      });
    }
  }],
  data: {
    labels: hours,
    datasets: [{
      label: 'Dataset 1',
      data: values,
      categoryPercentage: 0.99,
      barPercentage: 0.99,
      backgroundColor: 'blue'
    }]
  },
  options: {
    responsive: true,
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          parser: 'HH',
          unit: 'hour',
          displayFormats: {
            hour: 'Ha'
          },
          tooltipFormat: 'Ha'
        },
        gridLines: {
          offsetGridLines: true
        },
        ticks: {
          min: moment(hours[0], 'HH').subtract(1, 'hours'),
          fontColor: 'white'
        }
      }]
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas></code>```

Body:
You can draw the tick lables at the desired position directly on to the canvas using the Plugin Core API. It offers number of hooks that may be used for performing custom code. In below code snippet, I use the afterDraw hook to draw my own labels on the xAxis.

const hours = ['00', '01', '02', '03', '04', '05', '06'];
const values = [0, 0, 0, 0, 10, 6, 0];

const chart = new Chart(document.getElementById('myChart'), {
  type: 'bar',
  plugins: [{
    afterDraw: chart => {
      var xAxis = chart.scales['x-axis-0'];
      var tickDistance = xAxis.width / (xAxis.ticks.length - 1);
      xAxis.ticks.forEach((value, index) => {
        if (index > 0) {
          var x = -tickDistance + tickDistance * 0.66 + tickDistance * index;
          var y = chart.height - 10;
          chart.ctx.save();
          chart.ctx.fillText(value == '0am' ? '12am' : value, x, y);
          chart.ctx.restore();
        }
      });
    }
  }],
  data: {
    labels: hours,
    datasets: [{
      label: 'Dataset 1',
      data: values,
      categoryPercentage: 0.99,
      barPercentage: 0.99,
      backgroundColor: 'blue'
    }]
  },
  options: {
    responsive: true,
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          parser: 'HH',
          unit: 'hour',
          displayFormats: {
            hour: 'Ha'
          },
          tooltipFormat: 'Ha'
        },
        gridLines: {
          offsetGridLines: true
        },
        ticks: {
          min: moment(hours[0], 'HH').subtract(1, 'hours'),
          fontColor: 'white'
        }
      }]
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>


问:
getting image name of image selected from gallery in android
I have browsed image from gallery and set it to ImageView now I need to get image name of image that have been set in ImageView. I have attached my code below.

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d("req","req"+requestCode);
    Log.d("res","res"+resultCode);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        imageView = (ImageView) findViewById(R.id.imgView);

        imageView1 = (ImageView) findViewById(R.id.imgView1);

        if(browse == 1){
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        }
        if(browse == 2){
            imageView1.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        }
        String resName = getResources().getResourceEntryName(R.id.imgView);
        Toast.makeText(getApplicationContext(), "BBB"+resName,Toast.LENGTH_LONG).show();

    }
</code>```

答:
As per android documentation:</p>

```<code>    /*
     * Get the file's content URI from the incoming Intent,
     * then query the server app to get the file's display name
     * and size.
     */
    Uri returnUri = returnIntent.getData();
    Cursor returnCursor =
            getContentResolver().query(returnUri, null, null, null, null);
    /*
     * Get the column indexes of the data in the Cursor,
     * move to the first row in the Cursor, get the data,
     * and display it.
     */
    int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
    int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
    returnCursor.moveToFirst();
    TextView nameView = (TextView) findViewById(R.id.filename_text);
    TextView sizeView = (TextView) findViewById(R.id.filesize_text);
    nameView.setText(returnCursor.getString(nameIndex));
    sizeView.setText(Long.toString(returnCursor.getLong(sizeIndex)));
</code>```

Body:
I have browsed image from gallery and set it to ImageView now I need to get image name of image that have been set in ImageView. I have attached my code below.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d("req","req"+requestCode);
    Log.d("res","res"+resultCode);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        imageView = (ImageView) findViewById(R.id.imgView);

        imageView1 = (ImageView) findViewById(R.id.imgView1);

        if(browse == 1){
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        }
        if(browse == 2){
            imageView1.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        }
        String resName = getResources().getResourceEntryName(R.id.imgView);
        Toast.makeText(getApplicationContext(), "BBB"+resName,Toast.LENGTH_LONG).show();

    }

Body:
As per android documentation:

    /*
     * Get the file's content URI from the incoming Intent,
     * then query the server app to get the file's display name
     * and size.
     */
    Uri returnUri = returnIntent.getData();
    Cursor returnCursor =
            getContentResolver().query(returnUri, null, null, null, null);
    /*
     * Get the column indexes of the data in the Cursor,
     * move to the first row in the Cursor, get the data,
     * and display it.
     */
    int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
    int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
    returnCursor.moveToFirst();
    TextView nameView = (TextView) findViewById(R.id.filename_text);
    TextView sizeView = (TextView) findViewById(R.id.filesize_text);
    nameView.setText(returnCursor.getString(nameIndex));
    sizeView.setText(Long.toString(returnCursor.getLong(sizeIndex)));


问:
Save a excel file as gsheet
I want to automate a process and i have working with python, selenium and vba.
My process starts with a downloaded file from SQL server with python and selenium, later with vba, I transform the file and i apply a lot of formulas. When i finish, i save the file in xlsx format on a google drive folder with google File Stream. When the file is save on the folder, with google script i send a mail with the file's url. The final objetive of all this, it's that the users will put observations on de xlsx in the google drive folder, but on this format i don't have a way to change the file on collaborative way.
There's a method to save an excel file on gsheet format with MS excel or automate the transformation of the xlsx to gsheet and later send the email with the new file's url?
Greetings!</p>

答:
Here's the code with the solution:

```<code>function convertExceltoGoogleSpreadsheet() {

var folder = DriveApp.getFolderById('put the id's folder here')
var excelFile = folder.getFilesByType(MimeType.MICROSOFT_EXCEL).next();
var fileId = excelFile.getId();
var folderId = Drive.Files.get(fileId).parents[0].id;
var blob = excelFile.getBlob();
var resource = {
  title: excelFile.getName(),
  mimeType: MimeType.GOOGLE_SHEETS,
  parents: [{id: folderId}],
};

Drive.Files.insert(resource, blob);
}
</code>```

Later, you need remove the excel files with this script:

```<code>   function remove(){
   var folder = DriveApp.getFolderById('put you folder's id here');
   var files = folder.getFilesByType(MimeType.MICROSOFT_EXCEL);;
   while (files.hasNext()){
   var file = files.next();
   folder.removeFile(file);
   }
</code>```

The third step is put the notification:

```<code>     function checkForChangedFiles() {

     // folder
     var folderID = '"' + "folder's id" + '"';

     // email configuration
     var emailFromName ="emailname";
     var emailSubject = "emailsubject";
     var emailBody = "<b><br>bodyemail:<br></b>" +
     "line1<br>" +
     "line2<br>"+
     "line3<br>"+
     "line4<br>";
      var emailFooter = "footer";

      var folderSearch = folderID + " " + "in parents";
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getActiveSheet();
      var email = sheet.getRange("put the cell with the email's values").getValue();
      var timezone = ss.getSpreadsheetTimeZone();
      var today     = new Date();
      var time = new Date(today.getTime() - 1 * 30 * 1000);  // 30 seconds
      var startTime = time.toISOString();
      var search = '(trashed = true or trashed = false) and '+ folderSearch +' and (modifiedDate > "' + startTime + '")';

      var files  = DriveApp.searchFiles(search);
      var row = "", count=0;

      while( files.hasNext() ) {

      var file = files.next();
      var fileName = file.getName();
      var fileURL  = file.getUrl();
      var lastUpdated =  Utilities.formatDate(file.getLastUpdated(), timezone, "dd-MM-yyyy HH:mm");
      var dateCreated =  Utilities.formatDate(file.getDateCreated(), timezone, "dd-MM-yyyy HH:mm")

      row += "<li>" + lastUpdated + " <a href='" + fileURL + "'>" + fileName + "</a></li>";

      sheet.appendRow([dateCreated, lastUpdated, fileName, fileURL]);

      count++;
      }

      if (row !== "") {

      row = "<p>" + count + "  New File:</p><ol>" + row + "</ol>";
      row +=  emailBody+"<br>" + "<br><small> "+emailFooter+" </a>.</small>";
      MailApp.sendEmail(email, emailSubject, "", {name: emailFromName, htmlBody: row});
      }
</code>```

And finally we put all together:

```<code>      function doall(){
      convertExceltoGoogleSpreadsheet();
      Utilities.sleep(10000);
      remove();
      Utilities.sleep(10000);
      checkForChangedFiles();

      }
</code>```

Title: Save a excel file as gsheet

Body:
Here's the code with the solution:

function convertExceltoGoogleSpreadsheet() {

var folder = DriveApp.getFolderById('put the id's folder here')
var excelFile = folder.getFilesByType(MimeType.MICROSOFT_EXCEL).next();
var fileId = excelFile.getId();
var folderId = Drive.Files.get(fileId).parents[0].id;
var blob = excelFile.getBlob();
var resource = {
  title: excelFile.getName(),
  mimeType: MimeType.GOOGLE_SHEETS,
  parents: [{id: folderId}],
};

Drive.Files.insert(resource, blob);
}

Later, you need remove the excel files with this script:

   function remove(){
   var folder = DriveApp.getFolderById('put you folder's id here');
   var files = folder.getFilesByType(MimeType.MICROSOFT_EXCEL);;
   while (files.hasNext()){
   var file = files.next();
   folder.removeFile(file);
   }

The third step is put the notification:

     function checkForChangedFiles() {

     // folder
     var folderID = '"' + "folder's id" + '"';

     // email configuration
     var emailFromName ="emailname";
     var emailSubject = "emailsubject";
     var emailBody = "<b><br>bodyemail:<br></b>" +
     "line1<br>" +
     "line2<br>"+
     "line3<br>"+
     "line4<br>";
      var emailFooter = "footer";

      var folderSearch = folderID + " " + "in parents";
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getActiveSheet();
      var email = sheet.getRange("put the cell with the email's values").getValue();
      var timezone = ss.getSpreadsheetTimeZone();
      var today     = new Date();
      var time = new Date(today.getTime() - 1 * 30 * 1000);  // 30 seconds
      var startTime = time.toISOString();
      var search = '(trashed = true or trashed = false) and '+ folderSearch +' and (modifiedDate > "' + startTime + '")';

      var files  = DriveApp.searchFiles(search);
      var row = "", count=0;

      while( files.hasNext() ) {

      var file = files.next();
      var fileName = file.getName();
      var fileURL  = file.getUrl();
      var lastUpdated =  Utilities.formatDate(file.getLastUpdated(), timezone, "dd-MM-yyyy HH:mm");
      var dateCreated =  Utilities.formatDate(file.getDateCreated(), timezone, "dd-MM-yyyy HH:mm")

      row += "<li>" + lastUpdated + " <a href='" + fileURL + "'>" + fileName + "</a></li>";

      sheet.appendRow([dateCreated, lastUpdated, fileName, fileURL]);

      count++;
      }

      if (row !== "") {

      row = "<p>" + count + "  New File:</p><ol>" + row + "</ol>";
      row +=  emailBody+"<br>" + "<br><small> "+emailFooter+" </a>.</small>";
      MailApp.sendEmail(email, emailSubject, "", {name: emailFromName, htmlBody: row});
      }

And finally we put all together:

      function doall(){
      convertExceltoGoogleSpreadsheet();
      Utilities.sleep(10000);
      remove();
      Utilities.sleep(10000);
      checkForChangedFiles();

      }


问:
1D heatmap with double squares on y axis
I use this code to generate a 1D heatmap:

```<code>from matplotlib.pyplot import figure
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.style.use('seaborn')

data = np.array([0.8373871, 0.48286343, 0.11166477, 0., 0.07306099, 1.,
                     0.8604202, 0.59167194, 0.60088444, 0.32089615]).reshape(1, 10)
plt.imshow(data, cmap='Reds')
plt.xlabel('Timesteps', weight='bold', fontsize=14)
plt.show()
</code>```

The output graph:

if you can notice, if though I have 1 d array, the graph generates double squares on Y axis instead of one. How can I keep only one of them?

答:
The white lines you see are the grid lines. You can just turn them off (both x and y-axis) using

```<code>plt.grid(False)
</code>```

If you want to show selectively, you can use

```<code>plt.grid(axis='x')
</code>```

or

```<code>plt.grid(axis='y')
</code>```

Body:
I use this code to generate a 1D heatmap:

from matplotlib.pyplot import figure
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.style.use('seaborn')

data = np.array([0.8373871, 0.48286343, 0.11166477, 0., 0.07306099, 1.,
                     0.8604202, 0.59167194, 0.60088444, 0.32089615]).reshape(1, 10)
plt.imshow(data, cmap='Reds')
plt.xlabel('Timesteps', weight='bold', fontsize=14)
plt.show()

The output graph:

if you can notice, if though I have 1 d array, the graph generates double squares on Y axis instead of one. How can I keep only one of them?

Body:
The white lines you see are the grid lines. You can just turn them off (both x and y-axis) using

plt.grid(False)

If you want to show selectively, you can use

plt.grid(axis='x')

or

plt.grid(axis='y')


问:
Multiprocessing pool.map does not return from function call
I have a short snippet making the pool.map call to hang up. It does not return in any reasonable amount of time. The idea is to have a couple of point lists and find a measure for the correspondence to another point list.

```<code>    import numpy as np
    import multiprocessing
    import scipy.spatial as ss

    def dist(args): # returns the sum of distances of the nearest neighbors.
        kdSet, points = args
        dist, _ = kdSet.query(points)
        return np.sum(dist)

    #just define some points to play with
    points = np.array([[13.27, 25.49], [13.18, 25.39], [13.08, 25.39],
                       [12.99, 25.39], [12.89, 25.39], [12.80, 25.39],
                       [12.71, 25.39], [12.61, 25.30], [12.52, 25.30]])
    pointList = [points + idx for idx in range(3)] #creates a list of points

    #create a list of KDTrees for fast lookup. Add some number to make them a little different from pointList
    kdTreeList = [ss.KDTree(pointsLocal + idx/10) for idx, pointsLocal in enumerate(pointList)]

    #this part works fine: serial execution
    distances = list(map(dist, zip(kdTreeList, pointList)))
    print(distances)

    #this part hangs, if called as multiprocess, expected the same result as above
    with multiprocessing.Pool() as pool:
        print('Calling pool.map')
        distancesMultiprocess = pool.map(dist, zip(kdTreeList, pointList)) #<-This call does not return, but uses the CPU 100%
    print(distancesMultiprocess)
</code>```

Calling the function sequentially it works fine. But if called in the pool.map function it neither gives an error nor it is returning anything. It just hangs there. The CPU load goes to 100%, so something is happening.

Removing the KDTree class for testing purposes did not show a different result.

Since there is no error thrown, I have no idea whats going wrong here. Any hint?

答:
Thanks a lot to juanpa.arrivillaga
adding </p>

```<code>    if __name__ == "__main__":
</code>```

<p>did the trick. </p>

Body:
I have a short snippet making the pool.map call to hang up. It does not return in any reasonable amount of time. The idea is to have a couple of point lists and find a measure for the correspondence to another point list.

    import numpy as np
    import multiprocessing
    import scipy.spatial as ss

    def dist(args): # returns the sum of distances of the nearest neighbors.
        kdSet, points = args
        dist, _ = kdSet.query(points)
        return np.sum(dist)

    #just define some points to play with
    points = np.array([[13.27, 25.49], [13.18, 25.39], [13.08, 25.39],
                       [12.99, 25.39], [12.89, 25.39], [12.80, 25.39],
                       [12.71, 25.39], [12.61, 25.30], [12.52, 25.30]])
    pointList = [points + idx for idx in range(3)] #creates a list of points

    #create a list of KDTrees for fast lookup. Add some number to make them a little different from pointList
    kdTreeList = [ss.KDTree(pointsLocal + idx/10) for idx, pointsLocal in enumerate(pointList)]

    #this part works fine: serial execution
    distances = list(map(dist, zip(kdTreeList, pointList)))
    print(distances)

    #this part hangs, if called as multiprocess, expected the same result as above
    with multiprocessing.Pool() as pool:
        print('Calling pool.map')
        distancesMultiprocess = pool.map(dist, zip(kdTreeList, pointList)) #<-This call does not return, but uses the CPU 100%
    print(distancesMultiprocess)

Calling the function sequentially it works fine. But if called in the pool.map function it neither gives an error nor it is returning anything. It just hangs there. The CPU load goes to 100%, so something is happening.

Removing the KDTree class for testing purposes did not show a different result.

Since there is no error thrown, I have no idea whats going wrong here. Any hint?

Body:
Thanks a lot to juanpa.arrivillaga
adding

    if __name__ == "__main__":

did the trick.


问:
how to avoid form from submitting if both these values are valid
Hi Below is the code that i am using for my form to validate id's entered in two input fields.All code is working fine.Only thing is that how to stop form from submitting if both the fields are not valid as i am disabling and enabling submit button if record return is true.but if any one field is valid then submit button is enabling and allowing user to submit form.</p>

```<code><form>
<input type="text" id="1" value=""/>
<input type="text" id="2" value=""/>
<input type="submit" value="submit"  id="submitbutton" >
</form>
<script type="text/javascript">
            $$(document).ready(function() {
            $$('#1').blur(function() {
            var id = $$('#1').val();
            $$.getJSON("user.cfc?method=getRequests&returnformat=json&queryFormat=column",{"status":id}, function(res1,code) {

                if(res1.ROWCOUNT > 0){

                  for(var i=0; i<res1.ROWCOUNT; i++) {
                    s = "<span class='dPostTxt'>" + res1.DATA.ID[i] + " " + res1.DATA.FIRST_NAME[i] + " " + res1.DATA.LAST_NAME[i] + " " + "is valid." + "</span>";
                  };
                 $$('#submitbutton').removeAttr('disabled');//now id is valid so enabling submit button
                }
                else {
                  $$('#submitbutton').attr('disabled', 'disabled'); //error with id so disabling button
                  alert(" ID Is Not Valid.Please Enter Valid ID");
                  var s = "Entered  ID Is Not Valid.";
                }

                $$("#results").html(s);
                },"json");
           });  });
    </script>

<script type="text/javascript">
            $$(document).ready(function() {
            $$('#2').blur(function() {
            var id = $$('#2').val();
            $$.getJSON("user.cfc?method=getRequests&returnformat=json&queryFormat=column",{"status":id}, function(res,code) {

                if(res.ROWCOUNT > 0){

                  for(var i=0; i<res.ROWCOUNT; i++) {
                    s = "<span class='dPostTxt'>" + res.DATA.ID[i] + " " + res.DATA.FIRST_NAME[i] + " " + res.DATA.LAST_NAME[i] + " " + "is valid." + "</span>";
                  };
                 $$('#submitbutton').removeAttr('disabled');//now id is valid so enabling submit button
                }
                else {
                  $$('#submitbutton').attr('disabled', 'disabled'); //error with id so disabling button
                  alert(" ID Is Not Valid.Please Enter Valid ID");
                  var s = "Entered  ID Is Not Valid.";
                }

                $$("#results1").html(s);
                },"json");
           });  });
    </script>
</code>```

答: assign your checks to fire on $("form").submit() instead of onBlur of the fields. that way you can check both states at the same time, maybe fire a alert to the page if your form values are wrong &etc.

Body:
Hi Below is the code that i am using for my form to validate id's entered in two input fields.All code is working fine.Only thing is that how to stop form from submitting if both the fields are not valid as i am disabling and enabling submit button if record return is true.but if any one field is valid then submit button is enabling and allowing user to submit form.

<form>
<input type="text" id="1" value=""/>
<input type="text" id="2" value=""/>
<input type="submit" value="submit"  id="submitbutton" >
</form>


问:
Django says name 'form' not defined, but import exists
I have a user form and a profile form as below:

```<code>from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django_countries.fields import CountryField
from .models import Profile

class RegisterUserForm(UserCreationForm):
    email = forms.EmailField()
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=100)

    class Meta:
        model = User
        fields = ['username','first_name','last_name','email','password1','password2']

class RegisterProfileForm(UserCreationForm):
    address = forms.CharField(max_length=120)
    postcode = forms.CharField(max_length=30)
    countrycode = forms.CharField(max_length=3)

    class Meta:
        model = User
        fields = ['address','postcode','countrycode']
</code>```

These are imported into views.py in the code below and if valid...

```<code>from django.shortcuts import render,redirect
from django.contrib import messages
from .forms import RegisterUserForm,RegisterProfileForm,UserUpdateForm,ProfileUpdateForm
from django.contrib.auth.decorators import login_required

def register(request):
    if request.method == "POST":
        u_form = RegisterUserForm(request.POST)
        p_form = RegisterProfileForm(request.POST)

        if u_form.is_valid and p_form.is_valid:
            from django import forms
            username = form.cleaned_data.get('username')
            first_name = form.cleaned_data.get('first_name')
</code>```

However, when I post the form I get "Name Error at register... name 'form' is not defined" and the offending line of code is: username = form.cleaned_data.get('username'), in other words as soon as I reference form.cleaned_data, django objects.

This used to work. In desperation I imported django.forms just before referencing forms.cleaned_data (it wasn't there before) but unsurprisingly I still get "Name Error at register... name 'form' is not defined".

Can anyone tell me what I might be doing wrong, or point out things to check?

答:
Your implementation of form's cleaned_data is not correct. Try like this(check the code comments for explanation):

```<code>def register(request):
    if request.method == "POST":
        u_form = RegisterUserForm(request.POST)
        p_form = RegisterProfileForm(request.POST)

        if u_form<b>.is_valid()</b> and p_form<b>.is_valid()</b>:  <b># is_valid is a method, not property</b>
            username = <b>u_form</b>.cleaned_data.get('username')  <b># get cleaned data form a form instance, like 'u_form' or 'p_form'</b>
            first_name = <b>u_form</b>.cleaned_data.get('first_name')</code>```

More information can be found in is_valid() documentation and cleaned_data documentation.

Body:
I have a user form and a profile form as below:

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django_countries.fields import CountryField
from .models import Profile

class RegisterUserForm(UserCreationForm):
    email = forms.EmailField()
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=100)

    class Meta:
        model = User
        fields = ['username','first_name','last_name','email','password1','password2']

class RegisterProfileForm(UserCreationForm):
    address = forms.CharField(max_length=120)
    postcode = forms.CharField(max_length=30)
    countrycode = forms.CharField(max_length=3)

    class Meta:
        model = User
        fields = ['address','postcode','countrycode']

These are imported into views.py in the code below and if valid...

from django.shortcuts import render,redirect
from django.contrib import messages
from .forms import RegisterUserForm,RegisterProfileForm,UserUpdateForm,ProfileUpdateForm
from django.contrib.auth.decorators import login_required

def register(request):
    if request.method == "POST":
        u_form = RegisterUserForm(request.POST)
        p_form = RegisterProfileForm(request.POST)

        if u_form.is_valid and p_form.is_valid:
            from django import forms
            username = form.cleaned_data.get('username')
            first_name = form.cleaned_data.get('first_name')

However, when I post the form I get "Name Error at register... name 'form' is not defined" and the offending line of code is: username = form.cleaned_data.get('username'), in other words as soon as I reference form.cleaned_data, django objects.

This used to work. In desperation I imported django.forms just before referencing forms.cleaned_data (it wasn't there before) but unsurprisingly I still get "Name Error at register... name 'form' is not defined".

Can anyone tell me what I might be doing wrong, or point out things to check?

Body:
Your implementation of form's cleaned_data is not correct. Try like this(check the code comments for explanation):

def register(request):
    if request.method == "POST":
        u_form = RegisterUserForm(request.POST)
        p_form = RegisterProfileForm(request.POST)

        if u_form.is_valid() and p_form.is_valid():  # is_valid is a method, not property
            username = u_form.cleaned_data.get('username')  # get cleaned data form a form instance, like 'u_form' or 'p_form'
            first_name = u_form.cleaned_data.get('first_name')

More information can be found in is_valid() documentation and cleaned_data documentation.


问:
Rating star is cutting from the end
i have implemented android native rating bar but when i set number of star to 10 it will cut from the end of the screen its happening in some devices can anybody help me how can i manage to display 10 star consistently on all mobile devices?</p>

```<code> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_marginBottom="@dimen/_15sdp"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
    android:id="@+id/tValueLabel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="@dimen/_5sdp"
    android:textSize="@dimen/_11ssp" />

<RatingBar
    android:id="@+id/ratingBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="?android:attr/ratingBarStyleIndicator"
    android:isIndicator="false"
    android:layout_marginTop="@dimen/_5sdp"
    android:stepSize="1.0" />

</LinearLayout>
</code>```

答:
your RatingBar is cutting from end due to no space in screen to fit 10 star.
Solution for it is to reduce the size of star. there is no direct method by which we can reduce size of star. In your case scaleX and scaleY will works. Pls use below code for RatingBar  </p>

```<code><RatingBar
    android:id="@+id/ratingBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="?android:attr/ratingBarStyleIndicator"
    android:isIndicator="false"
    android:scaleX=".8"
    android:scaleY=".8"
    android:translationX="-10dp"
    android:layout_marginTop="5dp"
    android:stepSize="1.0" />
</code>```

Title: Rating star is cutting from the end

Body:
i have implemented android native rating bar but when i set number of star to 10 it will cut from the end of the screen its happening in some devices can anybody help me how can i manage to display 10 star consistently on all mobile devices?

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_marginBottom="@dimen/_15sdp"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
    android:id="@+id/tValueLabel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="@dimen/_5sdp"
    android:textSize="@dimen/_11ssp" />

<RatingBar
    android:id="@+id/ratingBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="?android:attr/ratingBarStyleIndicator"
    android:isIndicator="false"
    android:layout_marginTop="@dimen/_5sdp"
    android:stepSize="1.0" />

</LinearLayout>

Body:
your RatingBar is cutting from end due to no space in screen to fit 10 star.
Solution for it is to reduce the size of star. there is no direct method by which we can reduce size of star. In your case scaleX and scaleY will works. Pls use below code for RatingBar

<RatingBar
    android:id="@+id/ratingBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="?android:attr/ratingBarStyleIndicator"
    android:isIndicator="false"
    android:scaleX=".8"
    android:scaleY=".8"
    android:translationX="-10dp"
    android:layout_marginTop="5dp"
    android:stepSize="1.0" />