问:
Why does FFMPEG work with 1080p but doesn't work with 720p size… (code included)
I've uploaded my fully compiled code with its Makefile here:

https://pastebin.com/xtCTj06F

If I set 1280x720 I get the segmentation fault:

```<code>[libx264 @ 0x7fdf4d25a600] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX FMA3 AVX2 LZCNT BMI2
[libx264 @ 0x7fdf4d25a600] profile High, level 3.1
[libx264 @ 0x7fdf4d25a600] 264 - core 148 r2748 97eaef2 - H.264/MPEG-4 AVC codec - Copyleft 2003-2016 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=6 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=12 keyint_min=1 scenecut=40 intra_refresh=0 rc_lookahead=12 rc=abr mbtree=1 bitrate=3400 ratetol=1.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
Output #0, mp4, to '1.mp4':
    Stream #0:0: Video: h264, yuv420p, 1280x720, q=2-31, 3400 kb/s, 20 tbn
    Stream #0:1: Audio: aac (LC), 44100 Hz, stereo, fltp, 64 kb/s
sws_scale BEGIN
./MakeVideo.sh: line 2: 26422 Segmentation fault: 11  ./MakeVideo 1.mp4
</code>```

There's some problem with this line:

```<code>std::cout << "sws_scale BEGIN\n";
sws_scale( sws_context, ( const uint8_t * const * ) &rgb, inLinesize, 0, frame->height, frame->data, frame->linesize );
std::cout << "sws_scale END\n";
</code>```

but if I set the size of a video to 1920x1080 or to 320x240 - all works fine.

Is that some sort of a magick?? Or a bug?

OS X 10.12.3
ffmpeg/3.2.4 --enable-shared --enable-pthreads --enable-gpl --enable-version3 --enable-hardcoded-tables --enable-avresample --cc=clang --host-cflags= --host-ldflags= --enable-libmp3lame --enable-libx264 --enable-libxvid --enable-opencl --disable-lzma --enable-vda

答:
Your code has numerous issues. For instance </p>

```<code>void ffmpeg_encoder_set_frame_yuv_from_rgb( AVFrame *frame ) {
// frame pointer may be NULL, but is later used without check

uint8_t *rgb = (uint8_t *) malloc( 3 * sizeof( uint8_t ) * frame->width * frame->height );
// malloc may return NULL, but rgb is later used without check
// also rgb is never freed so memory leaks

sws_context = sws_getCachedContext(...
// sws_getCachedContext may return NULL, but sws_context is later used without check
</code>```

Body:
I've uploaded my fully compiled code with its Makefile here:

https://pastebin.com/xtCTj06F

If I set 1280x720 I get the segmentation fault:

[libx264 @ 0x7fdf4d25a600] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX FMA3 AVX2 LZCNT BMI2
[libx264 @ 0x7fdf4d25a600] profile High, level 3.1
[libx264 @ 0x7fdf4d25a600] 264 - core 148 r2748 97eaef2 - H.264/MPEG-4 AVC codec - Copyleft 2003-2016 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=6 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=12 keyint_min=1 scenecut=40 intra_refresh=0 rc_lookahead=12 rc=abr mbtree=1 bitrate=3400 ratetol=1.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
Output #0, mp4, to '1.mp4':
    Stream #0:0: Video: h264, yuv420p, 1280x720, q=2-31, 3400 kb/s, 20 tbn
    Stream #0:1: Audio: aac (LC), 44100 Hz, stereo, fltp, 64 kb/s
sws_scale BEGIN
./MakeVideo.sh: line 2: 26422 Segmentation fault: 11  ./MakeVideo 1.mp4

There's some problem with this line:

std::cout << "sws_scale BEGIN\n";
sws_scale( sws_context, ( const uint8_t * const * ) &rgb, inLinesize, 0, frame->height, frame->data, frame->linesize );
std::cout << "sws_scale END\n";

but if I set the size of a video to 1920x1080 or to 320x240 - all works fine.

Is that some sort of a magick?? Or a bug?

OS X 10.12.3
ffmpeg/3.2.4 --enable-shared --enable-pthreads --enable-gpl --enable-version3 --enable-hardcoded-tables --enable-avresample --cc=clang --host-cflags= --host-ldflags= --enable-libmp3lame --enable-libx264 --enable-libxvid --enable-opencl --disable-lzma --enable-vda

Body:
Your code has numerous issues. For instance

void ffmpeg_encoder_set_frame_yuv_from_rgb( AVFrame *frame ) {
// frame pointer may be NULL, but is later used without check

uint8_t *rgb = (uint8_t *) malloc( 3 * sizeof( uint8_t ) * frame->width * frame->height );
// malloc may return NULL, but rgb is later used without check
// also rgb is never freed so memory leaks

sws_context = sws_getCachedContext(...
// sws_getCachedContext may return NULL, but sws_context is later used without check


来源: stackexchange

问:
The header color wont change
i cant change the color here: http://prntscr.com/ergp4j

Can someone help me what to do? the url is: http://109.74.0.128/~assistans/

I did

```<code>´header.main-header .second-row .second-row-columns {
  background-color: #1c6a8b;
}`
</code>```

but it just change a small part of it

答:
It's only changing "a part" of the header because you are targeting a child of the header which does not span the whole width of the page.

Change your CSS to this:

```<code>header.main-header .second-row {
  background-color: #1c6a8b;
}
</code>```

See below screenshot:

ContentLicense: CC BY-SA 3.0

Title: The header color wont change

Body:
i cant change the color here: http://prntscr.com/ergp4j

Can someone help me what to do? the url is: http://109.74.0.128/~assistans/

I did

´header.main-header .second-row .second-row-columns {
  background-color: #1c6a8b;
}`

but it just change a small part of it

Body:
It's only changing "a part" of the header because you are targeting a child of the header which does not span the whole width of the page.

Change your CSS to this:

header.main-header .second-row {
  background-color: #1c6a8b;
}

See below screenshot:


问:
Jenkins pipeline doesn't print full log
I have a Makefile:

```<code>.PHONE: test
REMOVE_IMG_ON_FAIL=true
REMOVE_IMG_WHEN_DONE=true
DOCKER_OPTS = --rm -t
test: test-ubuntu14 test-ubuntu16 test-centos6 test-centos7

test-ubuntu14:
        $(eval ID:=$(shell docker build -f tests/Dockerfile-ubuntu14.04 . | tee /dev/stderr | awk 'END {print $$NF}'))
        docker run ${DOCKER_OPTS} -v ${PWD}/tests/hosts:/etc/hosts ${ID} \
                /ansible-role-this/tests/test.sh || { ${REMOVE_IMG_ON_FAIL} && docker rmi ${ID} && exit 1 ; }
        { ${REMOVE_IMG_WHEN_DONE} && docker rmi ${ID} ; } || true

test-ubuntu16:
        $(eval ID:=$(shell docker build -f tests/Dockerfile-ubuntu16.04 . | tee /dev/stderr | awk 'END {print $$NF}'))
        docker run ${DOCKER_OPTS} -v ${PWD}/tests/hosts:/etc/hosts ${ID} \
                /ansible-role-this/tests/test.sh || { ${REMOVE_IMG_ON_FAIL} && docker rmi ${ID} && exit 1 ; }
        { ${REMOVE_IMG_WHEN_DONE} && docker rmi ${ID} ; } || true

test-centos6:
        $(eval ID:=$(shell docker build -f tests/Dockerfile-centos6 . | tee /dev/stderr | awk 'END {print $$NF}'))
        docker run ${DOCKER_OPTS} -v ${PWD}/tests/hosts:/etc/hosts ${ID} \
                /ansible-role-this/tests/test.sh || { ${REMOVE_IMG_ON_FAIL} && docker rmi ${ID} && exit 1 ; }
        { ${REMOVE_IMG_WHEN_DONE} && docker rmi ${ID} ; } || true

test-centos7:
        $(eval ID:=$(shell docker build -f tests/Dockerfile-centos7 . | tee /dev/stderr | awk 'END {print $$NF}'))
        docker run ${DOCKER_OPTS} -v ${PWD}/tests/hosts:/etc/hosts ${ID} \
                /ansible-role-this/tests/test.sh || { ${REMOVE_IMG_ON_FAIL} && docker rmi ${ID} && exit 1 ; }
        { ${REMOVE_IMG_WHEN_DONE} && docker rmi ${ID} ; } || true
</code>```

along with Jenkinsfile

```<code>node {
  stage 'Checkout'
  checkout scm

  stage 'test'
  catchError {
    wrap([$class: 'AnsiColorBuildWrapper', 'colorMapName': 'XTerm']) {
      sh 'make test'
    }
  }
  step([$class: 'Mailer',
       notifyEveryUnstableBuild: true,
       recipients: emailextrecipients([[$class: 'CulpritsRecipientProvider'],
                                       [$class: 'RequesterRecipientProvider']])])
}
</code>```

It works fine, but for some reason pipeline prints only the first test-ubuntu14 output, but doesn't print the rest. Though they are definitely executed. unfortunately this complicates the debugging process.

UPDATE: As a workaround I used this Jenkinsfile:

```<code>node {
  stage 'Checkout'
  checkout scm

  stage 'test'
  catchError {
    wrap([$class: 'AnsiColorBuildWrapper', 'colorMapName': 'XTerm']) {
      sh 'make test-ubuntu14'
      sh 'make test-ubuntu16'
      sh 'make test-centos6'
      sh 'make test-centos7'
    }
  }
  step([$class: 'Mailer',
       notifyEveryUnstableBuild: true,
       recipients: emailextrecipients([[$class: 'CulpritsRecipientProvider'],
                                       [$class: 'RequesterRecipientProvider']])])
}
</code>```

Anyway, I still want to know how to print output of the single make test.

答:
try getting the output into a variable:
result = sh script: 'make test-ubuntu14', returnStdout: true

the just print the variable
print result

Title: Jenkins pipeline doesn't print full log

Body:
I have a Makefile:

.PHONE: test
REMOVE_IMG_ON_FAIL=true
REMOVE_IMG_WHEN_DONE=true
DOCKER_OPTS = --rm -t
test: test-ubuntu14 test-ubuntu16 test-centos6 test-centos7

test-ubuntu14:
        $(eval ID:=$(shell docker build -f tests/Dockerfile-ubuntu14.04 . | tee /dev/stderr | awk 'END {print $$NF}'))
        docker run ${DOCKER_OPTS} -v ${PWD}/tests/hosts:/etc/hosts ${ID} \
                /ansible-role-this/tests/test.sh || { ${REMOVE_IMG_ON_FAIL} && docker rmi ${ID} && exit 1 ; }
        { ${REMOVE_IMG_WHEN_DONE} && docker rmi ${ID} ; } || true

test-ubuntu16:
        $(eval ID:=$(shell docker build -f tests/Dockerfile-ubuntu16.04 . | tee /dev/stderr | awk 'END {print $$NF}'))
        docker run ${DOCKER_OPTS} -v ${PWD}/tests/hosts:/etc/hosts ${ID} \
                /ansible-role-this/tests/test.sh || { ${REMOVE_IMG_ON_FAIL} && docker rmi ${ID} && exit 1 ; }
        { ${REMOVE_IMG_WHEN_DONE} && docker rmi ${ID} ; } || true

test-centos6:
        $(eval ID:=$(shell docker build -f tests/Dockerfile-centos6 . | tee /dev/stderr | awk 'END {print $$NF}'))
        docker run ${DOCKER_OPTS} -v ${PWD}/tests/hosts:/etc/hosts ${ID} \
                /ansible-role-this/tests/test.sh || { ${REMOVE_IMG_ON_FAIL} && docker rmi ${ID} && exit 1 ; }
        { ${REMOVE_IMG_WHEN_DONE} && docker rmi ${ID} ; } || true

test-centos7:
        $(eval ID:=$(shell docker build -f tests/Dockerfile-centos7 . | tee /dev/stderr | awk 'END {print $$NF}'))
        docker run ${DOCKER_OPTS} -v ${PWD}/tests/hosts:/etc/hosts ${ID} \
                /ansible-role-this/tests/test.sh || { ${REMOVE_IMG_ON_FAIL} && docker rmi ${ID} && exit 1 ; }
        { ${REMOVE_IMG_WHEN_DONE} && docker rmi ${ID} ; } || true

along with Jenkinsfile

node {
  stage 'Checkout'
  checkout scm

  stage 'test'
  catchError {
    wrap([$class: 'AnsiColorBuildWrapper', 'colorMapName': 'XTerm']) {
      sh 'make test'
    }
  }
  step([$class: 'Mailer',
       notifyEveryUnstableBuild: true,
       recipients: emailextrecipients([[$class: 'CulpritsRecipientProvider'],
                                       [$class: 'RequesterRecipientProvider']])])
}

It works fine, but for some reason pipeline prints only the first test-ubuntu14 output, but doesn't print the rest. Though they are definitely executed. unfortunately this complicates the debugging process.

UPDATE: As a workaround I used this Jenkinsfile:

node {
  stage 'Checkout'
  checkout scm

  stage 'test'
  catchError {
    wrap([$class: 'AnsiColorBuildWrapper', 'colorMapName': 'XTerm']) {
      sh 'make test-ubuntu14'
      sh 'make test-ubuntu16'
      sh 'make test-centos6'
      sh 'make test-centos7'
    }
  }
  step([$class: 'Mailer',
       notifyEveryUnstableBuild: true,
       recipients: emailextrecipients([[$class: 'CulpritsRecipientProvider'],
                                       [$class: 'RequesterRecipientProvider']])])
}

Anyway, I still want to know how to print output of the single make test.


问:
Full panel break for highly skewed ggplot2 histogram
I have highly skewed histogram generated using ggplot2.

I would like split the x-axis of the histogram into two panels. One with x<50 and another x=>50 in order to detect any underlying pattern if any. So the first panel will have y-axis from 0 to around 500000 and x-axis from 0 to 50. The second panel with y-axis from 0 to around 100  and x-axis 50 to 350.

Thank you

答:
Just facet on the condition:

```<code>ggplot(diamonds, aes(carat)) + geom_histogram() + facet_wrap(~(carat > 3), scale = 'free')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Just facet on the condition:

ggplot(diamonds, aes(carat)) + geom_histogram() + facet_wrap(~(carat > 3), scale = 'free')


问:
Difference in uses between malloc and calloc
```<code>gcc 4.5.1 c89
</code>```

I have written this source code for my better understanding of malloc and calloc.

I understand, but just have a few questions.

```<code>dev = malloc(number * sizeof *devices);
</code>```

is equal to this calloc. I am not concerned about clearing the memory.

```<code>dev = calloc(number, sizeof *devices);
</code>```

What is that exactly, compared to doing this 5 times in a while loop:

```<code>dev = malloc(sizeof *devices);
</code>```

I guess the first one and the second is creating a pointer to 5 struct device. And the third is creating a single pointer to a struct device?

My program illustrates this 3 different methods compiled and ran with valgrind --leak-check=full.

Many thanks for any advice.

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

struct Devices {
#define MAX_NAME_SIZE 80
    size_t id;
    char name[MAX_NAME_SIZE];
};

struct Devices* create_device(struct Devices *dev);
void destroy_device(struct Devices *dev);

int main(void)
{
    size_t num_devices = 5;
    size_t i = 0;
    struct Devices *device = NULL;
    struct Devices *dev_malloc = NULL;
    struct Devices *dev_calloc = NULL;

    for(i = 0; i < num_devices; i++) {
        device = create_device(device);
        /* Assign values */
        device->id = i + 1;
        sprintf(device->name, "Device%zu", device->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", device->id);
        printf("Name --- [ %s ]\n", device->name);
        /* Test free */
        destroy_device(device);
    }

    printf("\n");
    dev_malloc = malloc(num_devices * sizeof *dev_malloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_malloc->id = i + 1;
        sprintf(dev_malloc->name, "dev_malloc%zu", dev_malloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_malloc->id);
        printf("Name --- [ %s ]\n", dev_malloc->name);
    }
    /* Test free */
    destroy_device(dev_malloc);

    printf("\n");
    dev_calloc = calloc(num_devices, sizeof *dev_calloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_calloc->id = i + 1;
        sprintf(dev_calloc->name, "dev_calloc%zu", dev_calloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_calloc->id);
        printf("Name --- [ %s ]\n", dev_calloc->name);
    }
    /* Test free */
    destroy_device(dev_calloc);

    return 0;
}

struct Devices* create_device(struct Devices *dev)
{
    /* Not checking for memory error - just simple test */
    return dev = malloc(sizeof *dev);
}

void destroy_device(struct Devices *dev)
{
    if(dev != NULL) {
        free(dev);
    }
}
</code>```

答:
edited for clarity

I guess the first one and the second is creating a pointer to 5 struct device. And the third is creating a single pointer to a struct device?

The first one malloc(number * sizeof(*devices)) would allocate enough memory to store number of Devices. As others have mentioned, you can treat this block like an array of Device. The pointer you get back will point to the beginning of the block.

```<code>int number = 5;
Device *ptr = malloc(number * sizeof(*ptr));
/* stuff */
free(ptr);
</code>```

The second one that uses calloc does the same thing, while also initializing the memory to 0. Again, you can use treat the block like an array of Device.

```<code>int number = 5;
Device *ptr = calloc(number, sizeof(*ptr));
/* stuff */
free(ptr);
</code>```

The third one, looping 5 times, would result in 5 different pointers to 5 different blocks large enough to store one Device each. This also means each of the 5 pointers has to be free'ed individually.

```<code>Device *ptrs[5];
for(int i = 0; i < 5; ++i)
{
    ptrs[i] = malloc(sizeof(*ptrs[i]));
}
/* stuff */
for(int i = 0; i < 5; ++i)
{
    free(ptrs[i]);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
gcc 4.5.1 c89

I have written this source code for my better understanding of malloc and calloc.

I understand, but just have a few questions.

dev = malloc(number * sizeof *devices);

is equal to this calloc. I am not concerned about clearing the memory.

dev = calloc(number, sizeof *devices);

What is that exactly, compared to doing this 5 times in a while loop:

dev = malloc(sizeof *devices);

I guess the first one and the second is creating a pointer to 5 struct device. And the third is creating a single pointer to a struct device?

My program illustrates this 3 different methods compiled and ran with valgrind --leak-check=full.

Many thanks for any advice.

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

struct Devices {
#define MAX_NAME_SIZE 80
    size_t id;
    char name[MAX_NAME_SIZE];
};

struct Devices* create_device(struct Devices *dev);
void destroy_device(struct Devices *dev);

int main(void)
{
    size_t num_devices = 5;
    size_t i = 0;
    struct Devices *device = NULL;
    struct Devices *dev_malloc = NULL;
    struct Devices *dev_calloc = NULL;

    for(i = 0; i < num_devices; i++) {
        device = create_device(device);
        /* Assign values */
        device->id = i + 1;
        sprintf(device->name, "Device%zu", device->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", device->id);
        printf("Name --- [ %s ]\n", device->name);
        /* Test free */
        destroy_device(device);
    }

    printf("\n");
    dev_malloc = malloc(num_devices * sizeof *dev_malloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_malloc->id = i + 1;
        sprintf(dev_malloc->name, "dev_malloc%zu", dev_malloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_malloc->id);
        printf("Name --- [ %s ]\n", dev_malloc->name);
    }
    /* Test free */
    destroy_device(dev_malloc);

    printf("\n");
    dev_calloc = calloc(num_devices, sizeof *dev_calloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_calloc->id = i + 1;
        sprintf(dev_calloc->name, "dev_calloc%zu", dev_calloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_calloc->id);
        printf("Name --- [ %s ]\n", dev_calloc->name);
    }
    /* Test free */
    destroy_device(dev_calloc);

    return 0;
}

struct Devices* create_device(struct Devices *dev)
{
    /* Not checking for memory error - just simple test */
    return dev = malloc(sizeof *dev);
}

void destroy_device(struct Devices *dev)
{
    if(dev != NULL) {
        free(dev);
    }
}

Body:
edited for clarity

I guess the first one and the second is creating a pointer to 5 struct device. And the third is creating a single pointer to a struct device?

The first one malloc(number * sizeof(*devices)) would allocate enough memory to store number of Devices. As others have mentioned, you can treat this block like an array of Device. The pointer you get back will point to the beginning of the block.

int number = 5;
Device *ptr = malloc(number * sizeof(*ptr));
/* stuff */
free(ptr);

The second one that uses calloc does the same thing, while also initializing the memory to 0. Again, you can use treat the block like an array of Device.

int number = 5;
Device *ptr = calloc(number, sizeof(*ptr));
/* stuff */
free(ptr);

The third one, looping 5 times, would result in 5 different pointers to 5 different blocks large enough to store one Device each. This also means each of the 5 pointers has to be free'ed individually.

Device *ptrs[5];
for(int i = 0; i < 5; ++i)
{
    ptrs[i] = malloc(sizeof(*ptrs[i]));
}
/* stuff */
for(int i = 0; i < 5; ++i)
{
    free(ptrs[i]);
}


问:
Xamarin- Rtl Support in Xamarin.android
I need to support Rtl in my app here is what I did

Replace all the occurrences of layout attributes that contains ‘left’ and ‘right’ to ‘start’ and ‘end’ respectively. For example, android:paddingLeft should become android:paddingStart

Reference

Here is how android studio render my xml layout

my xml code

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layout"
    android:orientation="vertical"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginLeft="22.3dp"
        android:layout_marginStart="22.3dp"
        android:layout_marginRight="15.3dp"
        android:layout_marginEnd="15.3dp"
        android:layout_marginTop="19dp">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="13.3sp"
            android:textColor="@color/bluey_grey"
            android:textAllCaps="true"
            android:text="@string/language" />
        <TextView
            android:id="@+id/languageText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="13.3sp"
            android:textColor="@color/orange_two"
            android:text="English" />
    </LinearLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="15dp"
        android:background="@color/silver_two" />
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="18dp">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@+id/notificationChk"
            android:layout_toStartOf="@+id/notificationChk"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:orientation="vertical">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="13.3sp"
                android:textColor="@color/bluey_grey"
                android:textAllCaps="true"
                android:text="@string/push_notifications" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="11.7sp"
                android:textColor="@color/cool_grey"
                android:text="@string/pushNotificationDetails" />
        </LinearLayout>
        <android.support.v7.widget.AppCompatCheckBox
            android:id="@+id/notificationChk"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            app:buttonTint="@color/colorPrimary"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
    </RelativeLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="15dp"
        android:background="@color/silver_two" />
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="18dp">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@+id/newsLatterChk"
            android:layout_toStartOf="@+id/newsLatterChk"

            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:orientation="vertical">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="13.3sp"
                android:textAllCaps="true"
                android:textColor="@color/bluey_grey"
                android:text="@string/newsletter" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="11.7sp"
                android:textColor="@color/cool_grey"

                android:text="@string/newsLetterDetails" />
        </LinearLayout>
        <CheckBox
            android:id="@+id/newsLatterChk"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
    </RelativeLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="15dp"
        android:background="@color/silver_two" />
    <TextView
        android:text="Save"
        android:layout_marginTop="20dp"
        android:padding="10dp"
        android:textSize="14.7dp"
        android:textAllCaps="true"
        android:layout_gravity="center"
        android:gravity="center"
        android:textColor="@color/orange_three"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/saveBtn" />
    <TextView
        android:id="@+id/logoutBtn"
        android:text="@string/logout"
        android:textAllCaps="true"
        android:layout_marginTop="15dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@color/tomato" />
    <Space
        android:layout_width="wrap_content"
        android:layout_height="20dp" />
    </LinearLayout>
</LinearLayout>
</code>```

but when I run in xamarin here is what I get

what I miss to full support Rtl ??

here is my post in Xamarin Forums  for more detail about my issue

答:
You still using hardCoded directions(right,left) in some views, i know that for < 17 API support but try to compile without it.

also you could use the param "layoutDirection" in views

```<code>   android:layoutDirection = "locale"
   android:layoutDirection = "inherit"
   android:layoutDirection = "rtl"
   android:layoutDirection = "ltr"
</code>```

Reference: Native RTL support in Android 4.2

Title: Xamarin- Rtl Support in Xamarin.android

Body:
I need to support Rtl in my app here is what I did

Replace all the occurrences of layout attributes that contains ‘left’ and ‘right’ to ‘start’ and ‘end’ respectively. For example, android:paddingLeft should become android:paddingStart

Reference

Here is how android studio render my xml layout

my xml code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layout"
    android:orientation="vertical"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginLeft="22.3dp"
        android:layout_marginStart="22.3dp"
        android:layout_marginRight="15.3dp"
        android:layout_marginEnd="15.3dp"
        android:layout_marginTop="19dp">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="13.3sp"
            android:textColor="@color/bluey_grey"
            android:textAllCaps="true"
            android:text="@string/language" />
        <TextView
            android:id="@+id/languageText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="13.3sp"
            android:textColor="@color/orange_two"
            android:text="English" />
    </LinearLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="15dp"
        android:background="@color/silver_two" />
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="18dp">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@+id/notificationChk"
            android:layout_toStartOf="@+id/notificationChk"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:orientation="vertical">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="13.3sp"
                android:textColor="@color/bluey_grey"
                android:textAllCaps="true"
                android:text="@string/push_notifications" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="11.7sp"
                android:textColor="@color/cool_grey"
                android:text="@string/pushNotificationDetails" />
        </LinearLayout>
        <android.support.v7.widget.AppCompatCheckBox
            android:id="@+id/notificationChk"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            app:buttonTint="@color/colorPrimary"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
    </RelativeLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="15dp"
        android:background="@color/silver_two" />
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="18dp">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@+id/newsLatterChk"
            android:layout_toStartOf="@+id/newsLatterChk"

            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:orientation="vertical">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="13.3sp"
                android:textAllCaps="true"
                android:textColor="@color/bluey_grey"
                android:text="@string/newsletter" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="11.7sp"
                android:textColor="@color/cool_grey"

                android:text="@string/newsLetterDetails" />
        </LinearLayout>
        <CheckBox
            android:id="@+id/newsLatterChk"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
    </RelativeLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="15dp"
        android:background="@color/silver_two" />
    <TextView
        android:text="Save"
        android:layout_marginTop="20dp"
        android:padding="10dp"
        android:textSize="14.7dp"
        android:textAllCaps="true"
        android:layout_gravity="center"
        android:gravity="center"
        android:textColor="@color/orange_three"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/saveBtn" />
    <TextView
        android:id="@+id/logoutBtn"
        android:text="@string/logout"
        android:textAllCaps="true"
        android:layout_marginTop="15dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@color/tomato" />
    <Space
        android:layout_width="wrap_content"
        android:layout_height="20dp" />
    </LinearLayout>
</LinearLayout>

but when I run in xamarin here is what I get

what I miss to full support Rtl ??

here is my post in Xamarin Forums  for more detail about my issue

Body:
You still using hardCoded directions(right,left) in some views, i know that for < 17 API support but try to compile without it.

also you could use the param "layoutDirection" in views

   android:layoutDirection = "locale"
   android:layoutDirection = "inherit"
   android:layoutDirection = "rtl"
   android:layoutDirection = "ltr"

Reference: Native RTL support in Android 4.2


问:
How to debug 'detected unhandled Python exception in' /var/log/messages
I have a python script checking status of my web service schedules for let's say 2000 times. One check takes like 5 minutes so the script execution takes like 2000x5 minutes.

I have application logs set up by logger and my system logs just to log information what is going on while script is running. However, script stops from some reasons. There is no single entry in my customized logs. The only thing I can find is

```<code>less /var/log/messages

 cat /var/log/messages | grep --color "pycharm.py"
Mar 27 08:48:48 hostname python: detected unhandled Python exception in 'pycharm.py'
Mar 30 13:58:16 hostname python: detected unhandled Python exception in 'pycharm.py'
Mar 31 08:22:01 hostname python: detected unhandled Python exception in 'pycharm.py'
Apr  1 05:42:09 hostname python: detected unhandled Python exception in 'pycharm.py'
Apr  2 03:04:16 hostname python: detected unhandled Python exception in 'pycharm.py'
</code>```

The environment is Red Hat 7.2

Can anyone suggest to add some lines to script to chatch errors.

Things like do not give me anything.

```<code>try:
   command
except:
   smth
</code>```

答:
You should log the unhandled exception as well as its stack trace, so you know what when wrong and where.

Use logger.exception() to log the exception content and stack trace.

Body:
I have a python script checking status of my web service schedules for let's say 2000 times. One check takes like 5 minutes so the script execution takes like 2000x5 minutes.

I have application logs set up by logger and my system logs just to log information what is going on while script is running. However, script stops from some reasons. There is no single entry in my customized logs. The only thing I can find is

less /var/log/messages

 cat /var/log/messages | grep --color "pycharm.py"
Mar 27 08:48:48 hostname python: detected unhandled Python exception in 'pycharm.py'
Mar 30 13:58:16 hostname python: detected unhandled Python exception in 'pycharm.py'
Mar 31 08:22:01 hostname python: detected unhandled Python exception in 'pycharm.py'
Apr  1 05:42:09 hostname python: detected unhandled Python exception in 'pycharm.py'
Apr  2 03:04:16 hostname python: detected unhandled Python exception in 'pycharm.py'

The environment is Red Hat 7.2

Can anyone suggest to add some lines to script to chatch errors.

Things like do not give me anything.

try:
   command
except:
   smth


问:
SQL Server : adding more than 1 where clause for a single column on the same table
I have a Project table and each project has multiple employees connected to it with different roles. I want to be able to filter the projects with more than one employee for example I want to get all the projects where "Janet" is the Sales Rep and "Mark" is the Project manager... This is what I tried so far and it doesn't show the expected results:

```<code>SELECT
    p_Empl.First_Name,
    p_Resources.cRole, p_Resources.Project_ID,
    p_Resources.Resources_ID, p_Resources.Empl_ID,
    p_Project.Project_ID AS Expr1,
    p_Project.ProjectNum,
    p_Empl.Last_Name
FROM
    p_Project
LEFT OUTER JOIN
    p_Resources ON p_Project.Project_ID = p_Resources.Project_ID
LEFT OUTER JOIN
    p_Empl ON p_Resources.Empl_ID = p_Empl.ID
WHERE
    p_Project.Project_ID IN (SELECT p_Project.Project_ID
                             FROM p_Project
                             LEFT OUTER JOIN p_Client ON p_Project.Client_ID = p_Client.Client_ID
                             WHERE p_Project.Project_ID IN (SELECT p_Project.Project_ID
                                                            FROM p_Project
                                                            INNER JOIN p_Resources ON p_Resources.Project_ID = p_Project.Project_ID
                                                            INNER JOIN p_Empl ON p_Resources.Empl_ID = p_Empl.ID
                                                            WHERE p_Empl.First_Name = 'Mark'
                                                              AND p_Resources.cRole = 'Sales Manager'
                                                            ORDER BY p_Project.Project_ID)
                              AND p_Project.Project_ID IN (SELECT p_Project.Project_ID
                                                           FROM p_Project
                                                           INNER JOIN p_Resources ON p_Resources.Project_ID = p_Project.Project_ID
                                                           INNER JOIN p_Empl ON p_Resources.Empl_ID = p_Empl.ID
                                                           WHERE p_Empl.First_Name = 'Janet'
                                                             AND p_Resources.cRole = 'Project Manager'
                                                          ORDER BY p_Project.Project_ID)
                             GROUP BY
                                 p_Project.Project_ID, p_Client.ClientName, p_Project.ProjectName, p_Project.ProjectNum
                             ORDER BY
                                 p_Client.ClientName, p_Project.ProjectName, p_Project.ProjectNum
                             OFFSET (25 * (1)) ROWS FETCH NEXT (25) ROWS ONLY)
</code>```

I'm very new to SQL and to programming altogether. I would really appreciate if someone can help me with this. Thanks.

答:
You don't need two subqueries. Use only one with OR between the different group of filters and use aggregation on projectId to use having clause to make sure both are present in for that projectId.

```<code>select p_Empl.First_Name,
    p_Resources.cRole,
    p_Resources.Project_ID,
    p_Resources.Resources_ID,
    p_Resources.Empl_ID,
    p_Project.Project_ID as Expr1,
    p_Project.ProjectNum,
    p_Empl.Last_Name
from p_Project
left outer join p_Resources on p_Project.Project_ID = p_Resources.Project_ID
left outer join p_Empl on p_Resources.Empl_ID = p_Empl.ID
where p_Project.Project_ID in (
        select p_Project.Project_ID
        from p_Project
        left outer join p_Client on p_Project.Client_ID = p_Client.Client_ID
        where p_Project.Project_ID in (
                select p_Project.Project_ID
                from p_Project
                inner join p_Resources on p_Resources.Project_ID = p_Project.Project_ID
                inner join p_Empl on p_Resources.Empl_ID = p_Empl.ID
                where (p_Empl.First_Name = 'Mark'
                    and p_Resources.cRole = 'Sales Manager')
                    or (p_Empl.First_Name = 'Janet'
                    and p_Resources.cRole = 'Project Manager')
                group by p_Project.Project_ID
                having count(distinct p_Empl.First_Name + p_Resources.cRole) = 2
                )
        group by p_Project.Project_ID,
            p_Client.ClientName,
            p_Project.ProjectName,
            p_Project.ProjectNum
        order by p_Client.ClientName,
            p_Project.ProjectName,
            p_Project.ProjectNum OFFSET(25 * (1)) ROWS fetch next (25) ROWS only
        )
</code>```

Body:
I have a Project table and each project has multiple employees connected to it with different roles. I want to be able to filter the projects with more than one employee for example I want to get all the projects where "Janet" is the Sales Rep and "Mark" is the Project manager... This is what I tried so far and it doesn't show the expected results:

SELECT
    p_Empl.First_Name,
    p_Resources.cRole, p_Resources.Project_ID,
    p_Resources.Resources_ID, p_Resources.Empl_ID,
    p_Project.Project_ID AS Expr1,
    p_Project.ProjectNum,
    p_Empl.Last_Name
FROM
    p_Project
LEFT OUTER JOIN
    p_Resources ON p_Project.Project_ID = p_Resources.Project_ID
LEFT OUTER JOIN
    p_Empl ON p_Resources.Empl_ID = p_Empl.ID
WHERE
    p_Project.Project_ID IN (SELECT p_Project.Project_ID
                             FROM p_Project
                             LEFT OUTER JOIN p_Client ON p_Project.Client_ID = p_Client.Client_ID
                             WHERE p_Project.Project_ID IN (SELECT p_Project.Project_ID
                                                            FROM p_Project
                                                            INNER JOIN p_Resources ON p_Resources.Project_ID = p_Project.Project_ID
                                                            INNER JOIN p_Empl ON p_Resources.Empl_ID = p_Empl.ID
                                                            WHERE p_Empl.First_Name = 'Mark'
                                                              AND p_Resources.cRole = 'Sales Manager'
                                                            ORDER BY p_Project.Project_ID)
                              AND p_Project.Project_ID IN (SELECT p_Project.Project_ID
                                                           FROM p_Project
                                                           INNER JOIN p_Resources ON p_Resources.Project_ID = p_Project.Project_ID
                                                           INNER JOIN p_Empl ON p_Resources.Empl_ID = p_Empl.ID
                                                           WHERE p_Empl.First_Name = 'Janet'
                                                             AND p_Resources.cRole = 'Project Manager'
                                                          ORDER BY p_Project.Project_ID)
                             GROUP BY
                                 p_Project.Project_ID, p_Client.ClientName, p_Project.ProjectName, p_Project.ProjectNum
                             ORDER BY
                                 p_Client.ClientName, p_Project.ProjectName, p_Project.ProjectNum
                             OFFSET (25 * (1)) ROWS FETCH NEXT (25) ROWS ONLY)

I'm very new to SQL and to programming altogether. I would really appreciate if someone can help me with this. Thanks.

Body:
You don't need two subqueries. Use only one with OR between the different group of filters and use aggregation on projectId to use having clause to make sure both are present in for that projectId.

select p_Empl.First_Name,
    p_Resources.cRole,
    p_Resources.Project_ID,
    p_Resources.Resources_ID,
    p_Resources.Empl_ID,
    p_Project.Project_ID as Expr1,
    p_Project.ProjectNum,
    p_Empl.Last_Name
from p_Project
left outer join p_Resources on p_Project.Project_ID = p_Resources.Project_ID
left outer join p_Empl on p_Resources.Empl_ID = p_Empl.ID
where p_Project.Project_ID in (
        select p_Project.Project_ID
        from p_Project
        left outer join p_Client on p_Project.Client_ID = p_Client.Client_ID
        where p_Project.Project_ID in (
                select p_Project.Project_ID
                from p_Project
                inner join p_Resources on p_Resources.Project_ID = p_Project.Project_ID
                inner join p_Empl on p_Resources.Empl_ID = p_Empl.ID
                where (p_Empl.First_Name = 'Mark'
                    and p_Resources.cRole = 'Sales Manager')
                    or (p_Empl.First_Name = 'Janet'
                    and p_Resources.cRole = 'Project Manager')
                group by p_Project.Project_ID
                having count(distinct p_Empl.First_Name + p_Resources.cRole) = 2
                )
        group by p_Project.Project_ID,
            p_Client.ClientName,
            p_Project.ProjectName,
            p_Project.ProjectNum
        order by p_Client.ClientName,
            p_Project.ProjectName,
            p_Project.ProjectNum OFFSET(25 * (1)) ROWS fetch next (25) ROWS only
        )


问:
Hiding user input on terminal in Linux script
I have bash script like the following:

```<code>#!/bin/bash

echo "Please enter your username";
read username;

echo "Please enter your password";
read password;
</code>```

I want that when the user types the password on the terminal, it should not be displayed (or something like  *******) should be displayed). How do I achieve this?

答:
Just supply -s to your read call like so:</p>

```<code>$ read -s PASSWORD
$ echo $PASSWORD
</code>```

Body:
I have bash script like the following:

#!/bin/bash

echo "Please enter your username";
read username;

echo "Please enter your password";
read password;

I want that when the user types the password on the terminal, it should not be displayed (or something like  *******) should be displayed). How do I achieve this?

Body:
Just supply -s to your read call like so:

$ read -s PASSWORD
$ echo $PASSWORD


问:
Spark with IntelliJ or Eclipse
I am trying to setup IntelliJ for spark 2.11 but it is very daunting and after days I have not been able to compile a simple instruction such as with "spark.read.format" which is not found in main core and sql spark libraries.

I have seen a few posts on the subject but with none resolved. Does anyone have some experience with perhaps a working sample program I can start with?

Could it be that it would be easier with Eclipse?

Many thanks in advance for your answers,
EZ

答:
build project in Intellij using with scala 2.11 and sbt 0.13: then ensure that your plugins.sbt contains as below:

```<code>logLevel := Level.Warn

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.13.0")
</code>```

then your build.sbt must contain as below:

```<code>scalaVersion := "2.11.8"

val sparkVersion = "2.1.0"

libraryDependencies += "org.apache.spark" %% "spark-core" % sparkVersion %"provided"

libraryDependencies +=  "org.apache.spark" %% "spark-sql" % sparkVersion %"provided"
</code>```

Then write your code, click Terminal in Intellij and type sbt assembly: you can ship that jar to remote cluster, otherwise run from Intelij locally, let me know how it goes

Title: Spark with IntelliJ or Eclipse

Body:
build project in Intellij using with scala 2.11 and sbt 0.13: then ensure that your plugins.sbt contains as below:

logLevel := Level.Warn

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.13.0")

then your build.sbt must contain as below:

scalaVersion := "2.11.8"

val sparkVersion = "2.1.0"

libraryDependencies += "org.apache.spark" %% "spark-core" % sparkVersion %"provided"

libraryDependencies +=  "org.apache.spark" %% "spark-sql" % sparkVersion %"provided"

Then write your code, click Terminal in Intellij and type sbt assembly: you can ship that jar to remote cluster, otherwise run from Intelij locally, let me know how it goes


问:
change multiple shell commands into one in groovy
Really new to groovy,I have very simple groovy code which run absolutely fine:

```<code>      sh """
          git checkout deploy
          git pull
          git branch
      """
      PREVIOS_VERSION = sh ( script: 'cat ' + VERSION_FILE + ' | grep current_version | awk -F\'[" "]\' \'{print $3}\'', returnStdout: true).trim()
      echo PREVIOS_VERSION
      sh "bumpversion ${SEMANTIC_VERSION_COMPONENT} --config-file ${VERSION_FILE} --verbose"
      NEW_VERSION = sh ( script: 'cat ' + VERSION_FILE + ' | grep current_version | awk -F\'[" "]\' \'{print $3}\'', returnStdout: true).trim()
      echo NEW_VERSION
      sh """
          git checkout ${GIT_BRANCH}
          git branch
      """
</code>```

When I combine this code into one sh command like this:

```<code>      sh """
          git checkout deploy
          git pull
          git branch
          PREVIOS_VERSION = ( script: 'cat ' + VERSION_FILE + ' | grep current_version | awk -F\'[" "]\' \'{print $3}\'', returnStdout: true).trim()
          echo PREVIOS_VERSION
          bumpversion \${SEMANTIC_VERSION_COMPONENT} --config-file \${VERSION_FILE} --verbose
          NEW_VERSION = ( script: 'cat ' + VERSION_FILE + ' | grep current_version | awk -F\'[" "]\' \'{print $3}\'', returnStdout: true).trim()
          echo NEW_VERSION
          git checkout ${GIT_BRANCH}
          git branch
      """
</code>```

Then I am getting this error:

```<code>WorkflowScript: 58: illegal string body character after dollar sign;
   solution: either escape a literal dollar sign "\$5" or bracket the value expression "${5}" @ line 58, column 7.
         sh """
</code>```

Even I try to use the \ character but still no luck. Can somebody tell me how I can achieve the end result.

答:
you need to add \n at the end of each line:

sh "git checkout deploy\n " +
   "git pull\n" +
   "git branch\n"

sorry for my  mistake , I just understood the question.

you can't do it in the way you wanted.
when you use the line :
PREVIOS_VERSION = sh ( script: 'cat ' + VERSION_FILE + ' | grep current_version | awk -F\'[" "]\' \'{print $3}\'', returnStdout: true).trim()

it is a groovy syntax calling a shell command.
you can't insert it in the shell since shell will not understand the syntax

Body:
Really new to groovy,I have very simple groovy code which run absolutely fine:

      sh """
          git checkout deploy
          git pull
          git branch
      """
      PREVIOS_VERSION = sh ( script: 'cat ' + VERSION_FILE + ' | grep current_version | awk -F\'[" "]\' \'{print $3}\'', returnStdout: true).trim()
      echo PREVIOS_VERSION
      sh "bumpversion ${SEMANTIC_VERSION_COMPONENT} --config-file ${VERSION_FILE} --verbose"
      NEW_VERSION = sh ( script: 'cat ' + VERSION_FILE + ' | grep current_version | awk -F\'[" "]\' \'{print $3}\'', returnStdout: true).trim()
      echo NEW_VERSION
      sh """
          git checkout ${GIT_BRANCH}
          git branch
      """

When I combine this code into one sh command like this:

      sh """
          git checkout deploy
          git pull
          git branch
          PREVIOS_VERSION = ( script: 'cat ' + VERSION_FILE + ' | grep current_version | awk -F\'[" "]\' \'{print $3}\'', returnStdout: true).trim()
          echo PREVIOS_VERSION
          bumpversion \${SEMANTIC_VERSION_COMPONENT} --config-file \${VERSION_FILE} --verbose
          NEW_VERSION = ( script: 'cat ' + VERSION_FILE + ' | grep current_version | awk -F\'[" "]\' \'{print $3}\'', returnStdout: true).trim()
          echo NEW_VERSION
          git checkout ${GIT_BRANCH}
          git branch
      """

Then I am getting this error:

WorkflowScript: 58: illegal string body character after dollar sign;
   solution: either escape a literal dollar sign "\$5" or bracket the value expression "${5}" @ line 58, column 7.
         sh """

Even I try to use the \ character but still no luck. Can somebody tell me how I can achieve the end result.


问:
Goroutines with sync.WaitGroup end before last wg.Done()
I have an example code (you can find it on Go Playground):

```<code>package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    messages := make(chan int)
    var wg sync.WaitGroup
    var result []int

    // you can also add these one at
    // a time if you need to

    wg.Add(1)
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 1)
        messages <- 1
    }()
    wg.Add(1)
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 1)
        messages <- 2
    }()
    wg.Add(1)
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 1)
        messages <- 3
    }()
    go func() {
        for i := range messages {
            fmt.Println(i)
        result = append(result, i)
        }

    }()

    wg.Wait()
    fmt.Println(result)
}
</code>```

I got this output:

```<code>2
1
[2 1]
</code>```

I think I know why is it happening, but I can't solve it. There is 3 item in the WaitGroup I mean the three goroutine, and the 4th groutine consume the data from the channel. When the last groutine say wg.Done() the program is over because of the wg.Wait() said every goroutine finished and the last goroutine result the 4th goroutine couldn't have consume, because the program ended. I tryed to add plus one with wg.Add(1) and the wg.Done() in the 4th function but in this case I got deadlock.

答:
Closing channels is an idiomatic Go pattern for signalling and if you close a buffered channel, the consumer can read all the queued data then stop.

This code works correctly:

```<code>func main() {
    messages := make(chan int)
    var wg sync.WaitGroup
    var result []int

    // you can also add these one at
    // a time if you need to

    wg.Add(1)
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 1)
        messages <- 1
    }()
    wg.Add(1)
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 1)
        messages <- 2
    }()
    wg.Add(1)
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 1)
        messages <- 3
    }()

    // this goroutine added to signal end of data stream
    // by closing messages channel
    go func() {
        wg.Wait()
        close(messages)
    }()

    // if you need this to happen inside a go routine,
    // this channel is used for signalling end of the work,
    // also another sync.WaitGroup could be used, but for just one
    // goroutine, a single channel as a signal makes sense (there is no
    // groups)
    done := make(chan struct{})
    go func() {
        defer close(done)
        for i := range messages {
            fmt.Println(i)
            result = append(result, i)
        }
    }()

    <-done
    fmt.Println(result)
}
</code>```

As you see we just added another goroutine that closes the messages channel, when all producers are done.

Body:
I have an example code (you can find it on Go Playground):

package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    messages := make(chan int)
    var wg sync.WaitGroup
    var result []int

    // you can also add these one at
    // a time if you need to

    wg.Add(1)
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 1)
        messages <- 1
    }()
    wg.Add(1)
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 1)
        messages <- 2
    }()
    wg.Add(1)
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 1)
        messages <- 3
    }()
    go func() {
        for i := range messages {
            fmt.Println(i)
        result = append(result, i)
        }

    }()

    wg.Wait()
    fmt.Println(result)
}

I got this output:

2
1
[2 1]

I think I know why is it happening, but I can't solve it. There is 3 item in the WaitGroup I mean the three goroutine, and the 4th groutine consume the data from the channel. When the last groutine say wg.Done() the program is over because of the wg.Wait() said every goroutine finished and the last goroutine result the 4th goroutine couldn't have consume, because the program ended. I tryed to add plus one with wg.Add(1) and the wg.Done() in the 4th function but in this case I got deadlock.

Body:
Closing channels is an idiomatic Go pattern for signalling and if you close a buffered channel, the consumer can read all the queued data then stop.

This code works correctly:

func main() {
    messages := make(chan int)
    var wg sync.WaitGroup
    var result []int

    // you can also add these one at
    // a time if you need to

    wg.Add(1)
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 1)
        messages <- 1
    }()
    wg.Add(1)
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 1)
        messages <- 2
    }()
    wg.Add(1)
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 1)
        messages <- 3
    }()

    // this goroutine added to signal end of data stream
    // by closing messages channel
    go func() {
        wg.Wait()
        close(messages)
    }()

    // if you need this to happen inside a go routine,
    // this channel is used for signalling end of the work,
    // also another sync.WaitGroup could be used, but for just one
    // goroutine, a single channel as a signal makes sense (there is no
    // groups)
    done := make(chan struct{})
    go func() {
        defer close(done)
        for i := range messages {
            fmt.Println(i)
            result = append(result, i)
        }
    }()

    <-done
    fmt.Println(result)
}

As you see we just added another goroutine that closes the messages channel, when all producers are done.


问:
IDeepCopy Interface java
i have some troubles with understanding the following:
I should implement an Interface called IDeepCopy.

Description "This Interface is needed since the Cloneable interface provided by Java does not redeclare the clone method of Object. We want to use it as bounded type for generic classes so this additional interface is needed.
We have chosen to use an IDeepCopy interface to make handling of copying/cloning objects simpler. Classes that implement this interface should construct a copy of object by either invoking a private copy constructor, or by creating a new object of the same class and setting its values accordingly. Keep in mind, that attributes of classes should also be copied (if they implement the IDeepCopy interface) in the same way, before they are set on the copied object.
IDeepCopy deepCopy()"

I declared the Interface but I don't really know how I have to implement the method accordingly.

My idea is the following (implementation of the method in a sub class):

```<code>public SimpleProduct deepCopy(){
    return new SimpleProduct(x,x);
}
</code>```

But how can I set set the attributes if I don't get an Object as parameter in deepCopy?

答:
From the description, it sounds like you're just supposed to pass in any the corresponding values from the original instance to the new one, calling .deepCopy() if applicable. e.g.

```<code>public class SimpleProduct implements IDeepCopy {

    private final int x;
    private final OtherClass y;

    public SimpleProduct(int x, OtherClass y) {
        this.x = x;
        this.y = y;
    }

    public SimpleProduct deepCopy() {
        return (y instanceof IDeepCopy) ? new SimpleProduct(x, ((IDeepCopy)y).deepCopy()) : new SimpleProduct(x, y);
    }
}
</code>```

Edit: updated deepCopy implementation with the suggestion from @c0der in comments

Title: IDeepCopy Interface java

Body:
i have some troubles with understanding the following:
I should implement an Interface called IDeepCopy.

Description "This Interface is needed since the Cloneable interface provided by Java does not redeclare the clone method of Object. We want to use it as bounded type for generic classes so this additional interface is needed.
We have chosen to use an IDeepCopy interface to make handling of copying/cloning objects simpler. Classes that implement this interface should construct a copy of object by either invoking a private copy constructor, or by creating a new object of the same class and setting its values accordingly. Keep in mind, that attributes of classes should also be copied (if they implement the IDeepCopy interface) in the same way, before they are set on the copied object.
IDeepCopy deepCopy()"

I declared the Interface but I don't really know how I have to implement the method accordingly.

My idea is the following (implementation of the method in a sub class):

public SimpleProduct deepCopy(){
    return new SimpleProduct(x,x);
}

But how can I set set the attributes if I don't get an Object as parameter in deepCopy?

Body:
From the description, it sounds like you're just supposed to pass in any the corresponding values from the original instance to the new one, calling .deepCopy() if applicable. e.g.

public class SimpleProduct implements IDeepCopy {

    private final int x;
    private final OtherClass y;

    public SimpleProduct(int x, OtherClass y) {
        this.x = x;
        this.y = y;
    }

    public SimpleProduct deepCopy() {
        return (y instanceof IDeepCopy) ? new SimpleProduct(x, ((IDeepCopy)y).deepCopy()) : new SimpleProduct(x, y);
    }
}

Edit: updated deepCopy implementation with the suggestion from @c0der in comments


问:
How to use async method in DelegateCommand
I want to link async method to a delegate command in prism framework in Xamarin.Forms and my question is how to do it?

Is below solution correct? Is there exist any pitfall? (deadlock, UI slow or freezing, bad practices, ...)

```<code>{      // My view model constructor
       ...
       MyCommand = new DelegateCommand(async () => await MyJobAsync());
       ...
}

private async Task MyJobAsync()
{
       ... // Some await calls
       ... // Some UI element changed such as binded Observable collections
}
</code>```

答:
```<code>public ICommand MyCommand{get;set;}

//constructor
public ctor()
{
    MyCommand = new Xamarin.Forms.Command(CmdDoTheJob);
}

public async void DoTheJob()
{
    await TheMethod();
}
</code>```

Body:
I want to link async method to a delegate command in prism framework in Xamarin.Forms and my question is how to do it?

Is below solution correct? Is there exist any pitfall? (deadlock, UI slow or freezing, bad practices, ...)

{      // My view model constructor
       ...
       MyCommand = new DelegateCommand(async () => await MyJobAsync());
       ...
}

private async Task MyJobAsync()
{
       ... // Some await calls
       ... // Some UI element changed such as binded Observable collections
}


问:
Count IF with Date and Time in single Cell (EXCEL)
I have a spreadsheet that lists the date and time of an event in the same cell (mm/dd/yy h:mm). I need to find a way to count how many events took place between a certain time range in a Hourly Basis.

I could sum if the cell contains dates only however the cell contains with date which i am unable to get the values.

Basically, all datas are in cell A, so i need to count how many events happened at 6am, 7am , and so on... as on hourly basis.

答:
Your column A looks like properly formatted date & time value, so its manipulation is easy. If it's not (ie, not date but text) you should first convert it to date value.

```<code>=DATE(MID(A2,7,4), MID(A2,4,2), LEFT(A2,2)) + TIME(MID(A2,12,2), MID(A2,15,2), RIGHT(A2,2))
</code>```

Say this was C2. Now that column C is date & time, set $D$2 to date to query(ex 2017-03-26), E2 to start time(ex 6:00), and F2 to end time(ex 7:00), then you can count events from 6:00 to 7:00 like this:

```<code>=COUNTIFS(C:C,">="&($D$2+E2), C:C,"<"&($D$2+F2))
</code>```

Sample file is here and its screenshot is below.

Body:
Your column A looks like properly formatted date & time value, so its manipulation is easy. If it's not (ie, not date but text) you should first convert it to date value.

=DATE(MID(A2,7,4), MID(A2,4,2), LEFT(A2,2)) + TIME(MID(A2,12,2), MID(A2,15,2), RIGHT(A2,2))

Say this was C2. Now that column C is date & time, set $D$2 to date to query(ex 2017-03-26), E2 to start time(ex 6:00), and F2 to end time(ex 7:00), then you can count events from 6:00 to 7:00 like this:

=COUNTIFS(C:C,">="&($D$2+E2), C:C,"<"&($D$2+F2))

Sample file is here and its screenshot is below.


问:
Java - Bit Manipulation Acting Strange
I currently have the simple function

```<code>public static void convert() {
     for (int i = 0; i < byteArray.length; i++) {
         byteArray[i] = (byte) (byteArray[i] & ~(1 << 0));

         String s = ("0000000" + Integer.toBinaryString(0xFF & byteArray[i])).replaceAll(".*(.{8})$", "$1");
         System.out.println(s);
     }
}
</code>```

which steps through an array of bytes and modifies each of the bits. This outputs the following:

```<code>11110110
11000010
11111010
</code>```

Where it gets strange however is when I add a simple if statement (that doesn't change anything) around the lines in the function, the output completely changes. For example, if I change the above function to

```<code>public static void convert() {
     for (int i = 0; i < byteArray.length; i++) {

        if (5 > 3) {
         byteArray[i] = (byte) (byteArray[i] & ~(1 << 0));

         String s = ("0000000" + Integer.toBinaryString(0xFF & byteArray[i])).replaceAll(".*(.{8})$", "$1");
         System.out.println(s);
        }
     }
}
</code>```

it outputs the following instead:

```<code>10100110
00011000
00010100
</code>```

I am really confused as to why this is happening. Thanks.

The whole class just for reference:

```<code>public class LIB {
static byte[] byteArray;
static ArrayList<String> bitArray = new ArrayList<String>();
static String messageToDecode = "001010110";
static char[] mtdChar = messageToDecode.toCharArray();
static ArrayList<String> FinalBitArray = new ArrayList<String>();

public static void main(String[] args) throws IOException  {
    // TODO Auto-generated method stub
    imageToBits();
    convert();

}

public static void imageToBits () throws IOException {
    //get image bytes
    byteArray = Files.readAllBytes(new File("/Users/2020shatgiskessell/Desktop/url.jpg").toPath());
     for (int i = 0; i < byteArray.length; i++) {

         String s = ("0000000" + Integer.toBinaryString(0xFF & byteArray[i])).replaceAll(".*(.{8})$", "$1");
         bitArray.add(s);

     }
}

public static void convert() {
     for (int i = 0; i < byteArray.length; i++) {

        if (5 > 3) {
         byteArray[i] = (byte) (byteArray[i] & ~(1 << 0));

         String s = ("0000000" + Integer.toBinaryString(0xFF & byteArray[i])).replaceAll(".*(.{8})$", "$1");
         System.out.println(s);
        }
     }
}
</code>```

答:
I'm beginning to wonder about the April Fool's Day joke that @LittleSanti mentioned. If so, it's mean.

I wrote the following; I eliminated the assignment back into the source array, and put the 'strange behavior' condition within the loop instead of making it two separate runs so that we could see the results more easily. There isn't any such strange behavior in the (admittedly strange) expressions you have here.

```<code>package bitplay;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;

public class Bitplay
{
//    public class LIB {
    static byte[] byteArray;
    static ArrayList<String> bitArray = new ArrayList<String>();
    static String messageToDecode = "001010110";
    static char[] mtdChar = messageToDecode.toCharArray();
    static ArrayList<String> FinalBitArray = new ArrayList<String>();

    public static void main(String[] args) throws IOException  {
      fakeRoutine();
    }

    private static void fakeRoutine()
    {
      byte[] array = new byte[] { (byte)0b11110111,
                                  (byte)0b11000011,
                                  (byte)0b11111010
                                };
      for (int i=0; i<3; i++)
      {
        String s = ("0000000" + Integer.toBinaryString(0xFF & array[i])).replaceAll(".*(.{8})$", "$1");
        System.out.println("1: " + s);

        byte clearedOne = (byte) (array[i] & ~(1 << 0));
        s = ("0000000" + Integer.toBinaryString(0xFF & clearedOne)).replaceAll(".*(.{8})$", "$1");
        System.out.println("2: " + s);

        if (5 > 3)
        {
          clearedOne = (byte) (array[i] & ~(1 << 0));
          s = ("0000000" + Integer.toBinaryString(0xFF & clearedOne)).replaceAll(".*(.{8})$", "$1");
          System.out.println("3: " + s);
        }
      }

    }
}
</code>```

Absent any simultaneous alteration of the array somewhere else, the only other explanation that comes to my mind for the difference in output is a difference in input, and I cannot help you there.

The output I get from the above is:

```<code>1: 11110111
2: 11110110
3: 11110110
1: 11000011
2: 11000010
3: 11000010
1: 11111010
2: 11111010
3: 11111010
</code>```

as expected. If you ever come up with a more specific question, go ahead and ask it, but I'm done with this question.

Title: Java - Bit Manipulation Acting Strange

Body:
I currently have the simple function

public static void convert() {
     for (int i = 0; i < byteArray.length; i++) {
         byteArray[i] = (byte) (byteArray[i] & ~(1 << 0));

         String s = ("0000000" + Integer.toBinaryString(0xFF & byteArray[i])).replaceAll(".*(.{8})$", "$1");
         System.out.println(s);
     }
}

which steps through an array of bytes and modifies each of the bits. This outputs the following:

11110110
11000010
11111010

Where it gets strange however is when I add a simple if statement (that doesn't change anything) around the lines in the function, the output completely changes. For example, if I change the above function to

public static void convert() {
     for (int i = 0; i < byteArray.length; i++) {

        if (5 > 3) {
         byteArray[i] = (byte) (byteArray[i] & ~(1 << 0));

         String s = ("0000000" + Integer.toBinaryString(0xFF & byteArray[i])).replaceAll(".*(.{8})$", "$1");
         System.out.println(s);
        }
     }
}

it outputs the following instead:

10100110
00011000
00010100

I am really confused as to why this is happening. Thanks.

The whole class just for reference:

public class LIB {
static byte[] byteArray;
static ArrayList<String> bitArray = new ArrayList<String>();
static String messageToDecode = "001010110";
static char[] mtdChar = messageToDecode.toCharArray();
static ArrayList<String> FinalBitArray = new ArrayList<String>();

public static void main(String[] args) throws IOException  {
    // TODO Auto-generated method stub
    imageToBits();
    convert();

}

public static void imageToBits () throws IOException {
    //get image bytes
    byteArray = Files.readAllBytes(new File("/Users/2020shatgiskessell/Desktop/url.jpg").toPath());
     for (int i = 0; i < byteArray.length; i++) {

         String s = ("0000000" + Integer.toBinaryString(0xFF & byteArray[i])).replaceAll(".*(.{8})$", "$1");
         bitArray.add(s);

     }
}

public static void convert() {
     for (int i = 0; i < byteArray.length; i++) {

        if (5 > 3) {
         byteArray[i] = (byte) (byteArray[i] & ~(1 << 0));

         String s = ("0000000" + Integer.toBinaryString(0xFF & byteArray[i])).replaceAll(".*(.{8})$", "$1");
         System.out.println(s);
        }
     }
}

Body:
I'm beginning to wonder about the April Fool's Day joke that @LittleSanti mentioned. If so, it's mean.

I wrote the following; I eliminated the assignment back into the source array, and put the 'strange behavior' condition within the loop instead of making it two separate runs so that we could see the results more easily. There isn't any such strange behavior in the (admittedly strange) expressions you have here.

package bitplay;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;

public class Bitplay
{
//    public class LIB {
    static byte[] byteArray;
    static ArrayList<String> bitArray = new ArrayList<String>();
    static String messageToDecode = "001010110";
    static char[] mtdChar = messageToDecode.toCharArray();
    static ArrayList<String> FinalBitArray = new ArrayList<String>();

    public static void main(String[] args) throws IOException  {
      fakeRoutine();
    }

    private static void fakeRoutine()
    {
      byte[] array = new byte[] { (byte)0b11110111,
                                  (byte)0b11000011,
                                  (byte)0b11111010
                                };
      for (int i=0; i<3; i++)
      {
        String s = ("0000000" + Integer.toBinaryString(0xFF & array[i])).replaceAll(".*(.{8})$", "$1");
        System.out.println("1: " + s);

        byte clearedOne = (byte) (array[i] & ~(1 << 0));
        s = ("0000000" + Integer.toBinaryString(0xFF & clearedOne)).replaceAll(".*(.{8})$", "$1");
        System.out.println("2: " + s);

        if (5 > 3)
        {
          clearedOne = (byte) (array[i] & ~(1 << 0));
          s = ("0000000" + Integer.toBinaryString(0xFF & clearedOne)).replaceAll(".*(.{8})$", "$1");
          System.out.println("3: " + s);
        }
      }

    }
}

Absent any simultaneous alteration of the array somewhere else, the only other explanation that comes to my mind for the difference in output is a difference in input, and I cannot help you there.

The output I get from the above is:

1: 11110111
2: 11110110
3: 11110110
1: 11000011
2: 11000010
3: 11000010
1: 11111010
2: 11111010
3: 11111010

as expected. If you ever come up with a more specific question, go ahead and ask it, but I'm done with this question.


问:
Configuration for create-react-app after ejecting to build a component library
I started to build a component library that I want to publish on NPM (and reuse in other apps) by creating a React app using create-react-app. Unfortunately the create-react-app default configuration doesn't seem to support building such component libraries (see these issues). So it seems I have to eject.

Do you have some instructions what to configure after ejecting to make this a component library I can reuse in other apps (I guess some Webpack stuff)?

答:
create-react-app is meant for quick setting up and development of apps, not really for development of libraries. For one thing, create-react-app creates an index.html file when building, which is usually not needed by libraries. Libraries require a different set of configuration (much less).

I faced this problem myself and have written a React component boilerplate for writing and publishing React components: https://github.com/yangshun/react-component-starter, after referencing how popular ES6 libraries were written, such as Redux.

Pros:

Similar to create-react-app, batteries are included

It has got all the important areas covered: development, linting, testing, and distributing

Minimal configuration

Babel for transpilation to ES5 and CommonJS format

ESLint included and configured

Jest tests examples

Webpack configuration that compiles to UMD

React Storybook for quick development of the components

Support for stylesheet distribution alongside your component

Cons:

Highly opinionated in terms of choice of tooling; they follow the choices set by create-react-app.

Have to manually update each package dependencies in future (you'll face this issue if you did eject anyways)

There is minimal configuration included and setup is easy. The various webpack, Babel and ESLint configurations should be quite understandable.

Hope this will be helpful to you. Feel free to give suggestions and comments on how it can be improved.


问:
Making view only available to registered users with registration redux?
I'm making a simple Django application, I've implemented django registration redux with two step email verification, using the standard default templates.

I know want to add a simple HTML page that is only accessible to registered users:

```<code> my_project
    /settings.py
    /urls.py
templates
   /only_accessible_to_users.html
   /registration
manage.py
my_application
   /models.py
   /admin.py
   /views.py
   /urls.py
</code>```

In /my_project/urls.py I have the following:

```<code>from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings

urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^accounts/', include('registration.backends.default.urls')),
  url(r'^finance/', include('my_application.urls'))
]
</code>```

In my_application/urls.py:

```<code>from django.conf.urls import url
from . import views

urlpatterns = [
  url(r'^$', views.testing, name='testing')]
</code>```

Finally in my_application/view.py:

```<code>def testing(request):
   return HttpResponse("<h2>Hey!</h2>")
</code>```

How can I render a HTML page here after validating that it's being requested by a registered user?

答:
You can use render function and pass the html template</p>

```<code>from django.shortcuts import render
from django.contrib.auth.decorators import login_required

@login_required
def testing(request):
    return render(request, template_name="test_template.html")
</code>```

Body:
I'm making a simple Django application, I've implemented django registration redux with two step email verification, using the standard default templates.

I know want to add a simple HTML page that is only accessible to registered users:

 my_project
    /settings.py
    /urls.py
templates
   /only_accessible_to_users.html
   /registration
manage.py
my_application
   /models.py
   /admin.py
   /views.py
   /urls.py

In /my_project/urls.py I have the following:

from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings

urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^accounts/', include('registration.backends.default.urls')),
  url(r'^finance/', include('my_application.urls'))
]

In my_application/urls.py:

from django.conf.urls import url
from . import views

urlpatterns = [
  url(r'^$', views.testing, name='testing')]

Finally in my_application/view.py:

def testing(request):
   return HttpResponse("
Hey!
")

How can I render a HTML page here after validating that it's being requested by a registered user?

Body:
You can use render function and pass the html template

from django.shortcuts import render
from django.contrib.auth.decorators import login_required

@login_required
def testing(request):
    return render(request, template_name="test_template.html")


问:
Using numpy.unique on multiple columns of a pandas.DataFrame
I am looking to use numpy.unique to obtain the reverse unique indexes of two columns of a pandas.DataFrame.

I know how to use it on one column:

```<code>u, rev = numpy.unique(df[col], return_inverse=True)
</code>```

But I want to use it on multiple columns. For example, if the df looks like:

```<code>    0   1
0   1   1
1   1   2
2   2   1
3   2   1
4   3   1
</code>```

then I would like to get the reverse indexes:

```<code>[0,1,2,2,3]
</code>```

答:
Approach #1

Here's one NumPy approach converting each row to a scalar each thinking of each row as one indexing tuple on a two-dimensional (for 2 columns of data) grid -

```<code>def unique_return_inverse_2D(a): # a is array
    a1D = a.dot(np.append((a.max(0)+1)[:0:-1].cumprod()[::-1],1))
    return np.unique(a1D, return_inverse=1)[1]
</code>```

If you have negative numbers in the data, we need to use min too to get those scalars. So, in that case, use a.max(0) - a.min(0) + 1 in place of a.max(0) + 1.

Approach #2

Here's another NumPy's views based solution with focus on performance inspired by this smart solution by @Eric -

```<code>def unique_return_inverse_2D_viewbased(a): # a is array
    a = np.ascontiguousarray(a)
    void_dt = np.dtype((np.void, a.dtype.itemsize * np.prod(a.shape[1:])))
    return np.unique(a.view(void_dt).ravel(), return_inverse=1)[1]
</code>```

Sample runs -

```<code>In [209]: df
Out[209]:
    0   1   2   3
0  21   7  31  69
1  62  75  22  62  # ----|
2  16  46   9  31  #     |==> Identical rows, so must have same IDs
3  62  75  22  62  # ----|
4  24  12  88  15

In [210]: unique_return_inverse_2D(df.values)
Out[210]: array([1, 3, 0, 3, 2])

In [211]: unique_return_inverse_2D_viewbased(df.values)
Out[211]: array([1, 3, 0, 3, 2])
</code>```

Body:
I am looking to use numpy.unique to obtain the reverse unique indexes of two columns of a pandas.DataFrame.

I know how to use it on one column:

u, rev = numpy.unique(df[col], return_inverse=True)

But I want to use it on multiple columns. For example, if the df looks like:

    0   1
0   1   1
1   1   2
2   2   1
3   2   1
4   3   1

then I would like to get the reverse indexes:

[0,1,2,2,3]

Body:
Approach #1

Here's one NumPy approach converting each row to a scalar each thinking of each row as one indexing tuple on a two-dimensional (for 2 columns of data) grid -

def unique_return_inverse_2D(a): # a is array
    a1D = a.dot(np.append((a.max(0)+1)[:0:-1].cumprod()[::-1],1))
    return np.unique(a1D, return_inverse=1)[1]

If you have negative numbers in the data, we need to use min too to get those scalars. So, in that case, use a.max(0) - a.min(0) + 1 in place of a.max(0) + 1.

Approach #2

Here's another NumPy's views based solution with focus on performance inspired by this smart solution by @Eric -

def unique_return_inverse_2D_viewbased(a): # a is array
    a = np.ascontiguousarray(a)
    void_dt = np.dtype((np.void, a.dtype.itemsize * np.prod(a.shape[1:])))
    return np.unique(a.view(void_dt).ravel(), return_inverse=1)[1]

Sample runs -

In [209]: df
Out[209]:
    0   1   2   3
0  21   7  31  69
1  62  75  22  62  # ----|
2  16  46   9  31  #     |==> Identical rows, so must have same IDs
3  62  75  22  62  # ----|
4  24  12  88  15

In [210]: unique_return_inverse_2D(df.values)
Out[210]: array([1, 3, 0, 3, 2])

In [211]: unique_return_inverse_2D_viewbased(df.values)
Out[211]: array([1, 3, 0, 3, 2])


问:
Deploying to heroku successful but application not appearing
I created a simple Java (maven) web application (WAR). On local Tomcat all works fine, however when I try to deploy to HEROKU the application does not show up (I get error instead on the home page of the app.
I run this command

```<code>heroku war:deploy myapp-ws-0.0.1-SNAPSHOT.war --app myapp-ws
</code>```

and all actions are successful

the only parameter that I need on Heroku for my app to run is spring profile and I added it this way.

```<code>heroku config:set -Dspring.profiles.active="true"
</code>```

I'm very new to heroku, but did anyone in the past deploy a war to heroku successfuly? I cannot find the problem, no error appears apart from the home page saying application Application Error. Any other information I should include here?

答:
Ok, I got it working, first I was able to check logs:

```<code>heroku logs --tail --app myapp-ws
</code>```

then I found out that you have to add one instance because at start there are zero

```<code>heroku ps:scale web=1
</code>```

and finally I added my arguments in this way

```<code>heroku config:set WEBAPP_RUNNER_OPTS="-Dspring.profiles.active=test" --app myapp-ws
</code>```

Body:
I created a simple Java (maven) web application (WAR). On local Tomcat all works fine, however when I try to deploy to HEROKU the application does not show up (I get error instead on the home page of the app.
I run this command

heroku war:deploy myapp-ws-0.0.1-SNAPSHOT.war --app myapp-ws

and all actions are successful

the only parameter that I need on Heroku for my app to run is spring profile and I added it this way.

heroku config:set -Dspring.profiles.active="true"

I'm very new to heroku, but did anyone in the past deploy a war to heroku successfuly? I cannot find the problem, no error appears apart from the home page saying application Application Error. Any other information I should include here?

Body:
Ok, I got it working, first I was able to check logs:

heroku logs --tail --app myapp-ws

then I found out that you have to add one instance because at start there are zero

heroku ps:scale web=1

and finally I added my arguments in this way

heroku config:set WEBAPP_RUNNER_OPTS="-Dspring.profiles.active=test" --app myapp-ws