问:
C++ callback functions in class Referention to non-static funct
I have that code and want to modify it and put it in class for example MergeSort

after I convert it to class I get an error in that line in initMergeSort:

error: no matches converting function ‘merge_sort’ to type ‘void* ()(void)’
           if (pthread_create(&thread, NULL, merge_sort, (void *) NULL) != 0) {

Referention to non-static function must be called (possible target for call

{Clion recognize it *merge_sort})

```<code>pthread_create(&thread, NULL, merge_sort,(void *) NULL);
</code>```

The way I want to make it:

New header

```<code>and the new header:
</code>```

```<code>    class MergeSort {
       private:
       //int *notSortedData;
       int *sortedData{};
       int part = 0;
       void merge(int low, int mid, int high);

       void merge_sort(int low, int high);
       //Problem is here: --v
       void *merge_sort(void *arg);

       public:
       MergeSort(int* notSortedData){
           this->sortedData = notSortedData;
       }
       static const int MAX = 20;
       static const int HALF_OF_MAX = MAX / 2;
       int initMergeSort(/*int *notSortedData*/);
};
</code>```

old header:

```<code>    static const int MAX = 20 ;
    static const int HALF_OF_MAX = MAX / 2;

    void merge(int low, int mid, int high);
    void merge_sort(int low, int high);
    void *merge_sort(void *arg);
    int initMergeSort(int *notSortedData);
</code>```

old implementation:

```<code>    // array of size MAX
    int *a;
    int part;
    void merge(int low, int mid, int high) {(...)}

// merge sort function

    void merge_sort(int low, int high) {
        // calculating mid point of array
        (...)
          // calling first half
          merge_sort(low, mid);
          // calling second half
          merge_sort(mid + 1, high);
          // merging the two halves
          merge(low, mid, high);
    }
}
</code>```

// thread function for multi-threading Problem is here

----------------------v

```<code>    void *merge_sort(void *arg) {
    // which part out of 4 parts
    int thread_part = part++;

    // calculating low and high
    int low = thread_part * (MAX / 4);
    int high = (thread_part + 1) * (MAX / 4) - 1;

    // evaluating mid point
    int mid = low + (high - low) / 2;
    if (low < high) {
        merge_sort(low, mid);
        merge_sort(mid + 1, high);
        merge(low, mid, high);
    }
}

// merge function for merging two parts

    int initMergeSort(int *notSortedData) {
    a = notSortedData;
    (...)
    pthread_t threads[THREAD_MAX];

    // creating 4 threads Here I have to invoke function call merge_sort
    for (unsigned long &thread : threads) {
        pthread_create(&thread, NULL, merge_sort,
                       (void *) NULL);
    }
    // joining all 4 threads
    (...)
    // merging the final 4 parts
    merge(0, (HALF_OF_MAX - 1) / 2, HALF_OF_MAX - 1);
    (...)
}
</code>```

Thank you for in advance

Full old code is here, and Full code after my unsuccesful refactor is here:

答:
You can't use a non-static class method for a pthread callback.  A non-static method has a hidden this parameter that pthread won't be able to account for when calling the method.

You need to use a static method instead (or a non-member function), eg:

```<code>class MergeSort {
   private:
   ...
   static void* static_merge_sort(void *arg);
   void* merge_sort();
};
</code>```

```<code>void* MergeSort::static_merge_sort(void *arg)
{
    return ((MergeSort*)arg)->merge_sort();
}

void* MergeSort::merge_sort()
{
    ...
    return ...;
}
</code>```

```<code>pthread_create(&thread, NULL, &MergeSort::static_merge_sort, this);
</code>```

Body:
I have that code and want to modify it and put it in class for example MergeSort

after I convert it to class I get an error in that line in initMergeSort:

error: no matches converting function ‘merge_sort’ to type ‘void* ()(void)’
           if (pthread_create(&thread, NULL, merge_sort, (void *) NULL) != 0) {

Referention to non-static function must be called (possible target for call

{Clion recognize it *merge_sort})

pthread_create(&thread, NULL, merge_sort,(void *) NULL);

The way I want to make it:

New header

and the new header:

    class MergeSort {
       private:
       //int *notSortedData;
       int *sortedData{};
       int part = 0;
       void merge(int low, int mid, int high);

       void merge_sort(int low, int high);
       //Problem is here: --v
       void *merge_sort(void *arg);

       public:
       MergeSort(int* notSortedData){
           this->sortedData = notSortedData;
       }
       static const int MAX = 20;
       static const int HALF_OF_MAX = MAX / 2;
       int initMergeSort(/*int *notSortedData*/);
};

old header:

    static const int MAX = 20 ;
    static const int HALF_OF_MAX = MAX / 2;

    void merge(int low, int mid, int high);
    void merge_sort(int low, int high);
    void *merge_sort(void *arg);
    int initMergeSort(int *notSortedData);

old implementation:

    // array of size MAX
    int *a;
    int part;
    void merge(int low, int mid, int high) {(...)}

// merge sort function

    void merge_sort(int low, int high) {
        // calculating mid point of array
        (...)
          // calling first half
          merge_sort(low, mid);
          // calling second half
          merge_sort(mid + 1, high);
          // merging the two halves
          merge(low, mid, high);
    }
}

// thread function for multi-threading Problem is here

----------------------v

    void *merge_sort(void *arg) {
    // which part out of 4 parts
    int thread_part = part++;

    // calculating low and high
    int low = thread_part * (MAX / 4);
    int high = (thread_part + 1) * (MAX / 4) - 1;

    // evaluating mid point
    int mid = low + (high - low) / 2;
    if (low < high) {
        merge_sort(low, mid);
        merge_sort(mid + 1, high);
        merge(low, mid, high);
    }
}

// merge function for merging two parts

    int initMergeSort(int *notSortedData) {
    a = notSortedData;
    (...)
    pthread_t threads[THREAD_MAX];

    // creating 4 threads Here I have to invoke function call merge_sort
    for (unsigned long &thread : threads) {
        pthread_create(&thread, NULL, merge_sort,
                       (void *) NULL);
    }
    // joining all 4 threads
    (...)
    // merging the final 4 parts
    merge(0, (HALF_OF_MAX - 1) / 2, HALF_OF_MAX - 1);
    (...)
}

Thank you for in advance

Full old code is here, and Full code after my unsuccesful refactor is here:

Body:
You can't use a non-static class method for a pthread callback.  A non-static method has a hidden this parameter that pthread won't be able to account for when calling the method.

You need to use a static method instead (or a non-member function), eg:

class MergeSort {
   private:
   ...
   static void* static_merge_sort(void *arg);
   void* merge_sort();
};

void* MergeSort::static_merge_sort(void *arg)
{
    return ((MergeSort*)arg)->merge_sort();
}

void* MergeSort::merge_sort()
{
    ...
    return ...;
}

pthread_create(&thread, NULL, &MergeSort::static_merge_sort, this);


来源: stackexchange

问:
Why are messages in DLT using DeadLetterPublishingRecoverer base64 encoded
I have configured a errorHandler which sends records to a DLT using

```<code>@Bean
    public DeadLetterPublishingRecoverer recoverer(KafkaTemplate<String, List<T>> template) {
        return new DeadLetterPublishingRecoverer(template);
    }

    @Bean
    public ErrorHandler errorHandler(DeadLetterPublishingRecoverer recoverer) {
        return new SeekToCurrentErrorHandler(recoverer, new FixedBackOff(0L, 2L));
    }
</code>```

I am using this DLT to capture serialization errors handled by ErrorHandlingDeserializer2

Problem I am facing is the messages in DLT are in base64 encoded format instead of plain string.

Producer

DLT consumer

test message goes in DLT as dGVzdCBtZXNzYWdl

Another problem which is hapenning is request size increases because of base64 encoding.

I want the message to go as is in the DLT.

Could you please provide pointers.

答:
Show your producer factory configuration.

Perhaps you are using a common producer factory?

Best guess is you are using a JsonSerializer there instead of a ByteArraySerializer.

With version 2.5, you can override producer factory configuration in each KafkaTemplate.

ContentLicense: CC BY-SA 4.0

Body:
I have configured a errorHandler which sends records to a DLT using

@Bean
    public DeadLetterPublishingRecoverer recoverer(KafkaTemplate<String, List<T>> template) {
        return new DeadLetterPublishingRecoverer(template);
    }

    @Bean
    public ErrorHandler errorHandler(DeadLetterPublishingRecoverer recoverer) {
        return new SeekToCurrentErrorHandler(recoverer, new FixedBackOff(0L, 2L));
    }

I am using this DLT to capture serialization errors handled by ErrorHandlingDeserializer2

Problem I am facing is the messages in DLT are in base64 encoded format instead of plain string.

Producer

DLT consumer

test message goes in DLT as dGVzdCBtZXNzYWdl

Another problem which is hapenning is request size increases because of base64 encoding.

I want the message to go as is in the DLT.

Could you please provide pointers.


问:
jQuery UI dialog box not positioned center screen
I have a jQuery dialog box that is meant to position in the middle of the screen. However, it seems slightly off-center vertically.

Here is the code:

```<code>$('#add_box').dialog({
    autoOpen: true,
    width: 300,
    modal: true,
    resizable: false,
    bgiframe:true
});
</code>```

Any ideas why this won't center?

答: Just solved the same problem, the issue was that i did not imported some js files, like widget.js :)</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a jQuery dialog box that is meant to position in the middle of the screen. However, it seems slightly off-center vertically.

Here is the code:

$('#add_box').dialog({
    autoOpen: true,
    width: 300,
    modal: true,
    resizable: false,
    bgiframe:true
});

Any ideas why this won't center?


问:
Snowflake Credit Calculation during scale up when clusters running in parallel for overlapping period
How does credit consumed gets calculated during scale up and scale down when queries running on old size cluster as well new queries on new size cluster during the change over.
e.g.  There were 4 queries running on X-Small size taking 12 mins to execute. While these queries running in their 2nd minute, I scaled up warehouse to Small Size and new 2 queries running on Small size for 4 mins and I scale down warehouse again for X-Small size. I have setup 5 mins as auto suspend time. Will the idle time before Auto suspend, charged for X-Small size or Small size ?  How the idle time before auto suspend get charged ? </p>

答:
A simpler framing might help.

You are billed for what you run.

You are billed for leaving it running idle, so it's ready to run when work arrives.

So if we change instance size, the old instance should shutdown when the last query running on it completes.

So if you where x-small, then small, and then x-small..

If the 3rd instance size (which is the same as the first), and the warehouse is changed to x-small while the original 4 x 12m queries where running. I would assume Snowflake would reallocate the 1st instance as the 3rd instance. But I am open to maybe it not assigning it, just as a "strange edge case". But then the 5 minute idle time should be of the x-small instance.

But if you had picked a third distinct size at the third time, (or if the 3rd instance was not reusing a the first instance), it would also depend if no queries where run on the 3rd instance, I would expect it to have not been started, unless you started it via a resume command. Thus in S3 (the size of the third instance) you could in theory be billed (12m * S1) + (4m * S2) + (5m * S3)

But each instance should not charged "idle time" if there is concern, as they are not the "current instance" being held for future queries.


问:
how to debug macro?
having this code:

```<code>#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>

#define check(x) ({int _val = (x); (_val ==-1? \
    ({fprintf(stderr, "Error (" __FILE__ ":%d) -- " \
    "%s\n",__LINE__,strerror(errno)); \
    exit(-1);-1;}) : _val); })

int main (int argc, char **argv) {

    if (argc!=2){
        fprintf(stderr, "usage: %s <filename>\n", argv[0]);
        exit(-1);
    }

    int fd;
    fd=open(argv[1], O_RDONLY);

    if(fd<0){
        perror("open");
        fprintf(stderr,"errno = %s\n",strerror(errno));
        exit(-1);
    }

    for(char c;check(read(fd,&c,1))>0;) //macro "check(x)" HERE
        fputc(c,stdout);

    return 0;
}
</code>```

It compiles without an error, but I can see the macro does not output error messeges (__FILE__, neither __LINE__), as define it the macro. How to fix that? (And for general, how to debug macro, how at least output some error for it)?

$cc -pedantic a.c

```<code>a.c: In function ‘main’:
a.c:10:2: warning: ISO C forbids braced-groups within expressions [-Wpedantic]
  ({fprintf(stderr, "Error (" __FILE__ ":%d) -- " \
  ^
a.c:30:13: note: in expansion of macro ‘check’
  for(char c;check(read(fd,&c,1))>0;)
             ^~~~~
a.c:9:18: warning: ISO C forbids braced-groups within expressions [-Wpedantic]
 #define check(x) ({int _val = (x); (_val ==-1? \
                  ^
a.c:30:13: note: in expansion of macro ‘check’
  for(char c;check(read(fd,&c,1))>0;)
</code>```

not single mention about for loop (only its location, because the macro is in there, but that is not error) statment. Only about macro. So please focus on macro problem and not about the for loop.

EDIT1:
the macro actually comes from this guy:
youtube tutorial (at the end of the video), well he uses clang, so I do not know what clang uses as a preprocessor (and therefor it works for him).

EDIT2 (output from a.i - preprocessed output):

```<code># 304 "/usr/include/fcntl.h" 3 4

# 8 "a.c" 2

# 14 "a.c"
int main (int argc, char **argv) {
</code>```

I have deleted all the noise. But you can see between #include <fcntl.h> and int main, there is nothing. But there should be the #define check(x).... So it does not tell me WHY is it missing.

答:
Generally speaking you can't debug a macro as macro is not something which is executed.

But there should be the #define check(x).... So it does not tell me
  WHY is it missing.

Your macro was preprocessed - ie textually replaced by the preprocessor.

After the preprocessing it is expanded to:

```<code>    for(char c;({int _val = (read(fd,&c,1)); (_val ==-1? ({fprintf(
              stderr
              , "Error (" "./example.c" ":%d) -- " "%s\n",30,strerror(
              (*__errno_location ())
              )); exit(-1);-1;}) : _val); })>0;)
        fputc(c,
               stdout
                     );
</code>```

Title: how to debug macro?

Body:
having this code:

#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>

#define check(x) ({int _val = (x); (_val ==-1? \
    ({fprintf(stderr, "Error (" __FILE__ ":%d) -- " \
    "%s\n",__LINE__,strerror(errno)); \
    exit(-1);-1;}) : _val); })

int main (int argc, char **argv) {

    if (argc!=2){
        fprintf(stderr, "usage: %s <filename>\n", argv[0]);
        exit(-1);
    }

    int fd;
    fd=open(argv[1], O_RDONLY);

    if(fd<0){
        perror("open");
        fprintf(stderr,"errno = %s\n",strerror(errno));
        exit(-1);
    }

    for(char c;check(read(fd,&c,1))>0;) //macro "check(x)" HERE
        fputc(c,stdout);

    return 0;
}

It compiles without an error, but I can see the macro does not output error messeges (__FILE__, neither __LINE__), as define it the macro. How to fix that? (And for general, how to debug macro, how at least output some error for it)?

$cc -pedantic a.c

a.c: In function ‘main’:
a.c:10:2: warning: ISO C forbids braced-groups within expressions [-Wpedantic]
  ({fprintf(stderr, "Error (" __FILE__ ":%d) -- " \
  ^
a.c:30:13: note: in expansion of macro ‘check’
  for(char c;check(read(fd,&c,1))>0;)
             ^~~~~
a.c:9:18: warning: ISO C forbids braced-groups within expressions [-Wpedantic]
 #define check(x) ({int _val = (x); (_val ==-1? \
                  ^
a.c:30:13: note: in expansion of macro ‘check’
  for(char c;check(read(fd,&c,1))>0;)

not single mention about for loop (only its location, because the macro is in there, but that is not error) statment. Only about macro. So please focus on macro problem and not about the for loop.

EDIT1:
the macro actually comes from this guy:
youtube tutorial (at the end of the video), well he uses clang, so I do not know what clang uses as a preprocessor (and therefor it works for him).

EDIT2 (output from a.i - preprocessed output):

# 304 "/usr/include/fcntl.h" 3 4

# 8 "a.c" 2

# 14 "a.c"
int main (int argc, char **argv) {

I have deleted all the noise. But you can see between #include <fcntl.h> and int main, there is nothing. But there should be the #define check(x).... So it does not tell me WHY is it missing.

Body:
Generally speaking you can't debug a macro as macro is not something which is executed.

But there should be the #define check(x).... So it does not tell me
  WHY is it missing.

Your macro was preprocessed - ie textually replaced by the preprocessor.

After the preprocessing it is expanded to:

    for(char c;({int _val = (read(fd,&c,1)); (_val ==-1? ({fprintf(
              stderr
              , "Error (" "./example.c" ":%d) -- " "%s\n",30,strerror(
              (*__errno_location ())
              )); exit(-1);-1;}) : _val); })>0;)
        fputc(c,
               stdout
                     );


问:
CSS width of a  tag
I use  tags in my module titles,
e.g.

Categories.

I specify the span's background color/image, width and height in css.

But the span's width depends on its content/text.

So, if I do , with just a background image/color in css, nothing appears.

Of course, I want something to appear.

How can I resolve this?

答:
spans default to inline style, which you can't specify the width of.

```<code>display: inline-block;
</code>```

would be a good way, except IE doesn't support it

you can, however, hack a multiple browser solution

ContentLicense: CC BY-SA 2.5

Title: CSS width of a <span> tag

Body:
spans default to inline style, which you can't specify the width of.

display: inline-block;

would be a good way, except IE doesn't support it

you can, however, hack a multiple browser solution


问:
Weekly Time schedule range between days
I have a weekly schedule set from Friday evening 2011-05-27 18:00 to Monday morning
2011-05-30 06:00. This schedule executed on every week starts from 2011-05-27. How we can identify an event time (2011-06-06 19:00) falls between this weekly schedule ?

UPDATE

```<code>ID    StartTime         EndTime            Recurrence  TimeDifferenceInSeconds
1     2011-05-27 18:00  2011-05-30 06:00   1           216000
</code>```

Here recurrence is every one week.

Regards,

Greepty

答:
If I understand you correctly you want to check if a date will fall between a Wed & Mon.

In that case you can simply do a SELECT DATENAME(WEEKDAY, '6-Jun-2011') and if that falls on one of the days you have the answer, you will just have to check the time component then.

Title: Weekly Time schedule range between days

Body:
I have a weekly schedule set from Friday evening 2011-05-27 18:00 to Monday morning
2011-05-30 06:00. This schedule executed on every week starts from 2011-05-27. How we can identify an event time (2011-06-06 19:00) falls between this weekly schedule ?

UPDATE

ID    StartTime         EndTime            Recurrence  TimeDifferenceInSeconds
1     2011-05-27 18:00  2011-05-30 06:00   1           216000

Here recurrence is every one week.

Regards,

Greepty


问:
The ordered and unordered sequence
I would like to write a program that reads a sequence of integer numbers and outputs true if the sequence is ordered (in asc or desc order), otherwise, false.

The sequence ends with 0. Do not consider this number as a part of the sequence. The sequence always has at least one number (excluding 0).

my code:

```<code>import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        Scanner read = new Scanner(System.in);
        int a;
        int b;
        boolean asc = true;
        boolean dsc = true;
        a = read.nextInt();
        while (a == 0) {
            a = read.nextInt();
        }
        while (true) {
            b = read.nextInt();
            if (b == 0) {
                break;
            }
            dsc = dsc && a >= b;
            asc = asc && a <= b;
            if (asc || dsc == false) {
                break;
            }
            a = b;
        }
        System.out.println(asc || dsc);
    }
}
</code>```

Test input: 1 2 5 5 2 3 0

Correct output: false

My code output: true

What is wrong with my code?

答:
Your if condition before the break statement is wrong. When you write

```<code>if (asc || dsc == false)
</code>```

it will check if asc is true or if dsc is false, which means that if the first number's ascending, it will immediately break, and if it isn't, it will break the first time the sequence isn't descending.

What you should put there is !asc && !dsc, which will get you the output you want. It will only break if both asc and dsc are false, and your sequence has no order.

Title: The ordered and unordered sequence

Body:
I would like to write a program that reads a sequence of integer numbers and outputs true if the sequence is ordered (in asc or desc order), otherwise, false.

The sequence ends with 0. Do not consider this number as a part of the sequence. The sequence always has at least one number (excluding 0).

my code:

import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        Scanner read = new Scanner(System.in);
        int a;
        int b;
        boolean asc = true;
        boolean dsc = true;
        a = read.nextInt();
        while (a == 0) {
            a = read.nextInt();
        }
        while (true) {
            b = read.nextInt();
            if (b == 0) {
                break;
            }
            dsc = dsc && a >= b;
            asc = asc && a <= b;
            if (asc || dsc == false) {
                break;
            }
            a = b;
        }
        System.out.println(asc || dsc);
    }
}

Test input: 1 2 5 5 2 3 0

Correct output: false

My code output: true

What is wrong with my code?

Body:
Your if condition before the break statement is wrong. When you write

if (asc || dsc == false)

it will check if asc is true or if dsc is false, which means that if the first number's ascending, it will immediately break, and if it isn't, it will break the first time the sequence isn't descending.

What you should put there is !asc && !dsc, which will get you the output you want. It will only break if both asc and dsc are false, and your sequence has no order.


问:
How does one move a std::unique_ptr between windows without risking a memory leak?
I want to do this project in C++ and be done with it once and for all:
select a movie from a list in one window and display the movie's details in another window.

I'd already arrived at Remy Lebeau's solution here and found his post because I'd realized the same limitation he did: it exposes the raw pointer to memory leakage.

(Please excuse my coding style).

```<code>MoviesWindow::MovieSelected( const unsigned int uint__MovieKey )
{   ...
    std::unique_ptr<MovieBean> uptr__MovieBean = std::make_unique...
    ...
    uptr__MovieBean->SetMovieTitle(   row["MovieTitle"]   );
    uptr__MovieBean->SetYearReleased( row["YearReleased"] );
    ...
    SendMessage( hwnd__MovieWindow, UWM_SendMovieBean, 0, (LPARAM) uptr__MovieBean->get() );
    ...
}
</code>```

Fortunately, I have an advantage with SendMessage(): it won't end (releasing the std::unique_ptr) until the message handler returns, and the message handler's job is to clone the MovieBean.

```<code>MovieWindow::HandleUwmSendMovieBean( const HWND hwnd__MovieWindow, const UINT uint__WindowMessage, const WPARAM wParam, const LPARAM lParam )
{   UPTR__MovieBean = std::move( (*((MovieBean*) lParam).Clone() );
    ...
}
</code>```

It seems the right way to do it is leave ownership of the std::unique_ptr with MovieSelected() until the actual moment of transfer by sending a reference to the handler, and using std::move on the reference.

```<code>MoviesWindow::MovieSelected( const unsigned int uint__MovieKey )
{   ...
    SendMessage( hwnd__MovieWindow, UWM_SendMovieBean, 0, (LPARAM) &uptr__MovieBean );
    ...
}
</code>```

But I cannot figure out how to get the reference out of lParam and into std::move.  This would seem to be the one, but nope.

```<code>MovieWindow::HandleUwmSendMovieBean( const HWND hwnd__MovieWindow, const UINT uint__WindowMessage, const WPARAM wParam, const LPARAM lParam )
{ UPTR__NewMovieBean  = std::move( reinterpret_cast<std::unique_ptr<MovieBean>*>( lParam ) );
    ...
}
</code>```

I've tried every combination I can think of and ensured that the address sent is the address received and supplied to std::move.  All I get are constant compiler errors (including a now-much-hated one about std::remove_reference), and crashes.  Any insight would be appreciated.

答:
I got the answer in two more tries:

```<code>MovieWindow::HandleUwmSendMovieBean( const HWND hwnd__MovieWindow, const UINT uint__WindowMessage, const WPARAM wParam, const LPARAM lParam )
{ UPTR__NewMovieBean = std::move( *((std::unique_ptr<MovieBean>*) lParam) );
  ...
}
</code>```

Basically, sending the address of the std::unique_ptr<MovieBean> meant I was sending a pointer, so I needed to std::move(...) what the pointer was pointing to.  It works fine.

This still seems sound to me: I'm leaving the MovieBean protected by a smart pointer while it's "in flight".  It's effectively just a pass-by-reference that doesn't violate C++ Core Rule 33: Take a unique_ptr<widget>& parameter to express that a function reseats the widget.

The substantial problem in this usage is that my message handler is also the signal to read the MovieBean's copious information into the various CommonControls of the MovieWindow.  Message handlers are supposed to be quick.  The better approach is what @selbie suggested: the formal contract between the backing classes.

Body:
I want to do this project in C++ and be done with it once and for all:
select a movie from a list in one window and display the movie's details in another window.

I'd already arrived at Remy Lebeau's solution here and found his post because I'd realized the same limitation he did: it exposes the raw pointer to memory leakage.

(Please excuse my coding style).

MoviesWindow::MovieSelected( const unsigned int uint__MovieKey )
{   ...
    std::unique_ptr<MovieBean> uptr__MovieBean = std::make_unique...
    ...
    uptr__MovieBean->SetMovieTitle(   row["MovieTitle"]   );
    uptr__MovieBean->SetYearReleased( row["YearReleased"] );
    ...
    SendMessage( hwnd__MovieWindow, UWM_SendMovieBean, 0, (LPARAM) uptr__MovieBean->get() );
    ...
}

Fortunately, I have an advantage with SendMessage(): it won't end (releasing the std::unique_ptr) until the message handler returns, and the message handler's job is to clone the MovieBean.

MovieWindow::HandleUwmSendMovieBean( const HWND hwnd__MovieWindow, const UINT uint__WindowMessage, const WPARAM wParam, const LPARAM lParam )
{   UPTR__MovieBean = std::move( (*((MovieBean*) lParam).Clone() );
    ...
}

It seems the right way to do it is leave ownership of the std::unique_ptr with MovieSelected() until the actual moment of transfer by sending a reference to the handler, and using std::move on the reference.

MoviesWindow::MovieSelected( const unsigned int uint__MovieKey )
{   ...
    SendMessage( hwnd__MovieWindow, UWM_SendMovieBean, 0, (LPARAM) &uptr__MovieBean );
    ...
}

But I cannot figure out how to get the reference out of lParam and into std::move.  This would seem to be the one, but nope.

MovieWindow::HandleUwmSendMovieBean( const HWND hwnd__MovieWindow, const UINT uint__WindowMessage, const WPARAM wParam, const LPARAM lParam )
{ UPTR__NewMovieBean  = std::move( reinterpret_cast<std::unique_ptr<MovieBean>*>( lParam ) );
    ...
}

I've tried every combination I can think of and ensured that the address sent is the address received and supplied to std::move.  All I get are constant compiler errors (including a now-much-hated one about std::remove_reference), and crashes.  Any insight would be appreciated.

Body:
I got the answer in two more tries:

MovieWindow::HandleUwmSendMovieBean( const HWND hwnd__MovieWindow, const UINT uint__WindowMessage, const WPARAM wParam, const LPARAM lParam )
{ UPTR__NewMovieBean = std::move( *((std::unique_ptr<MovieBean>*) lParam) );
  ...
}

Basically, sending the address of the std::unique_ptr<MovieBean> meant I was sending a pointer, so I needed to std::move(...) what the pointer was pointing to.  It works fine.

This still seems sound to me: I'm leaving the MovieBean protected by a smart pointer while it's "in flight".  It's effectively just a pass-by-reference that doesn't violate C++ Core Rule 33: Take a unique_ptr<widget>& parameter to express that a function reseats the widget.

The substantial problem in this usage is that my message handler is also the signal to read the MovieBean's copious information into the various CommonControls of the MovieWindow.  Message handlers are supposed to be quick.  The better approach is what @selbie suggested: the formal contract between the backing classes.


问:
Grouping the factors in ggplot
I am trying to create a graph based on matrix similar to one below... I am trying to group the Erosion values based on "Slope"...

```<code>library(ggplot2)
new_mat<-matrix(,nrow = 135, ncol = 7)
colnames(new_mat)<-c("Scenario","Runoff (mm)","Erosion (t/ac)","Slope","Soil","Tillage","Rotation")
for ( i in 1:nrow(new_mat)){
  new_mat[i,2]<-sample(10:50, 1)
  new_mat[i,3]<-sample(0.1:20, 1)
  new_mat[i,4]<-sample(c("S2","S3","S4","S5","S1"),1)
  new_mat[i,5]<-sample(c("Deep","Moderate","Shallow"),1)
  new_mat[i,7]<-sample(c("WBP","WBF","WF"),1)
  new_mat[i,6]<-sample(c("Intense","Reduced","Notill"),1)
  new_mat[i,1]<-paste0(new_mat[i,4],"_",new_mat[i,5],"_",new_mat[i,6],"_",new_mat[i,7],"_")
  }

#### Graph part ########
grphs_mat<-as.data.frame(new_mat)
grphs_mat$`Runoff (mm)`<-as.numeric(as.character(grphs_mat$`Runoff (mm)`))
grphs_mat$`Erosion (t/ac)`<-as.numeric(as.character(grphs_mat$`Erosion (t/ac)`))
ggplot(grphs_mat, aes(Scenario, `Erosion (t/ac)`,group=Slope, colour = Slope))+
  scale_y_continuous(limits=c(0,max(as.numeric((grphs_mat$`Erosion (t/ac)`)))))+
  geom_point()+geom_line()
</code>```

But when i run this code.. The values are distributed in x-axis for all 135 scenarios. But what i want is grouping to be done in terms of slope but it also picks up the other common factors such as Soil+Rotation+Tillage and place it in x-axis. For example:
For these five scenarios:

S1_Deep_Intense_WBF_

S2_Deep_Intense_WBF_

S3_Deep_Intense_WBF_

S4_Deep_Intense_WBF_

S5_Deep_Intense_WBF_

It separates the S1, S2, S3,S4,S5 but also be able to know that other factors are same and put them in x-axis such that the slope lines are stacked on top of each other in 135/5 = 27 x-axis points. The final figure should look like this (Refer image). Apologies for not being able to explain it better.
I think i am making a mistake in grouping or assigning the x-axis values.
I will appreciate your suggestions.

答:
In the example you give, I didn't get every possible factor combination represented so the plots looked a bit weird. What I did instead was start with the following:

```<code>set.seed(42)
new_mat <- matrix(,nrow = 1000, ncol = 7)
</code>```

And then deduplicated this by summarising the values. A possible relevant step here for you analysis is that I made new variable with the interaction() function that is the combination of three other factors.

```<code>library(tidyverse)
df <- grphs_mat
df$x <- with(df, interaction(Rotation, Soil, Tillage))

# The simulation did not yield unique combinations
df <- df %>% group_by(x, Slope) %>%
  summarise(n = sum(`Erosion (t/ac)`))
</code>```

Next, I plotted this new x variable on the x-axis and used "stack" positions for the lines and points.

```<code>g <- ggplot(df, aes(x, y = n, colour = Slope, group = Slope)) +
  geom_line(position = "stack") +
  geom_point(position = "stack")
</code>```

To make the x-axis slightly more readable, you can replace the . that the interaction() function placed by newlines.

```<code>g + scale_x_discrete(labels = function(x){gsub("\\.", "\n", x)})
</code>```

Another option is to simply rotate the x axis labels:

```<code>g + theme(axis.text.x.bottom = element_text(angle = 90))
</code>```

There are a few additional options for the x-axis if you go into ggplot2 extension packages.

Title: Grouping the factors in ggplot

Body:
I am trying to create a graph based on matrix similar to one below... I am trying to group the Erosion values based on "Slope"...

library(ggplot2)
new_mat<-matrix(,nrow = 135, ncol = 7)
colnames(new_mat)<-c("Scenario","Runoff (mm)","Erosion (t/ac)","Slope","Soil","Tillage","Rotation")
for ( i in 1:nrow(new_mat)){
  new_mat[i,2]<-sample(10:50, 1)
  new_mat[i,3]<-sample(0.1:20, 1)
  new_mat[i,4]<-sample(c("S2","S3","S4","S5","S1"),1)
  new_mat[i,5]<-sample(c("Deep","Moderate","Shallow"),1)
  new_mat[i,7]<-sample(c("WBP","WBF","WF"),1)
  new_mat[i,6]<-sample(c("Intense","Reduced","Notill"),1)
  new_mat[i,1]<-paste0(new_mat[i,4],"_",new_mat[i,5],"_",new_mat[i,6],"_",new_mat[i,7],"_")
  }

#### Graph part ########
grphs_mat<-as.data.frame(new_mat)
grphs_mat$`Runoff (mm)`<-as.numeric(as.character(grphs_mat$`Runoff (mm)`))
grphs_mat$`Erosion (t/ac)`<-as.numeric(as.character(grphs_mat$`Erosion (t/ac)`))
ggplot(grphs_mat, aes(Scenario, `Erosion (t/ac)`,group=Slope, colour = Slope))+
  scale_y_continuous(limits=c(0,max(as.numeric((grphs_mat$`Erosion (t/ac)`)))))+
  geom_point()+geom_line()

But when i run this code.. The values are distributed in x-axis for all 135 scenarios. But what i want is grouping to be done in terms of slope but it also picks up the other common factors such as Soil+Rotation+Tillage and place it in x-axis. For example:
For these five scenarios:

S1_Deep_Intense_WBF_

S2_Deep_Intense_WBF_

S3_Deep_Intense_WBF_

S4_Deep_Intense_WBF_

S5_Deep_Intense_WBF_

It separates the S1, S2, S3,S4,S5 but also be able to know that other factors are same and put them in x-axis such that the slope lines are stacked on top of each other in 135/5 = 27 x-axis points. The final figure should look like this (Refer image). Apologies for not being able to explain it better.
I think i am making a mistake in grouping or assigning the x-axis values.
I will appreciate your suggestions.

Body:
In the example you give, I didn't get every possible factor combination represented so the plots looked a bit weird. What I did instead was start with the following:

set.seed(42)
new_mat <- matrix(,nrow = 1000, ncol = 7)

And then deduplicated this by summarising the values. A possible relevant step here for you analysis is that I made new variable with the interaction() function that is the combination of three other factors.

library(tidyverse)
df <- grphs_mat
df$x <- with(df, interaction(Rotation, Soil, Tillage))

# The simulation did not yield unique combinations
df <- df %>% group_by(x, Slope) %>%
  summarise(n = sum(`Erosion (t/ac)`))

Next, I plotted this new x variable on the x-axis and used "stack" positions for the lines and points.

g <- ggplot(df, aes(x, y = n, colour = Slope, group = Slope)) +
  geom_line(position = "stack") +
  geom_point(position = "stack")

To make the x-axis slightly more readable, you can replace the . that the interaction() function placed by newlines.

g + scale_x_discrete(labels = function(x){gsub("\\.", "\n", x)})

Another option is to simply rotate the x axis labels:

g + theme(axis.text.x.bottom = element_text(angle = 90))

There are a few additional options for the x-axis if you go into ggplot2 extension packages.


问:
Changing a flat image's color with jQuery
I have a flat white circular image (as in a seriously flat #ffffff image). Is there a way I can change it's color in the context of an HTML page (let's assume PNG, so we're working with an RGBA raster)?

My environment uses jQuery, so I'm inclined to think within the jQuery mindset, but if something else makes this possible, I'd like to hear about it as well.

I'm not well versed with the capabilities of Canvas so much, but maybe that can do something like this. With respect to browser support however, I'd really appreciate it if the solution can touch base with IE6 (yeah, I know it's dead, but bear with me on this one).

答:
You can 'emulate' a circle in browsers that support border radius. Try;

```<code><div class="circle"/>

.circle{
    background:blue;
    border: 1px solid red;
    border-radius: 50px 50px 50px 50px;
    height: 100px;
    width: 100px;
}
</code>```

Then change background-color accordingly.

Yeah, I know, no IE6 support but maybe you could fall back on the transparent image effect as mentioned above

Body:
You can 'emulate' a circle in browsers that support border radius. Try;

<div class="circle"/>

.circle{
    background:blue;
    border: 1px solid red;
    border-radius: 50px 50px 50px 50px;
    height: 100px;
    width: 100px;
}

Then change background-color accordingly.

Yeah, I know, no IE6 support but maybe you could fall back on the transparent image effect as mentioned above


问:
Overlapping/crowded labels on y-axis python
I'am kind of in a rush to finish this for tomorrows presentation towards the project owner. We are a small group of economic students in germany trying to figure out machine learning with python. We set up a Random Forest Classifier and are desperate to show the estimators important features in a neat plot. By applying google search we came up with the following solution that kind of does the trick, but leaves us unsatisfied due to the overlapping of the labels on the y-axis. The code we used looks like this:

```<code>feature_importances = clf.best_estimator_.feature_importances_
feature_importances = 100 * (feature_importances / feature_importances.max())
sorted_idx = np.argsort(feature_importances)

pos = np.arange(sorted_idx.shape[0])
plt.barh(pos, feature_importances[sorted_idx], align='center', height=0.8)
plt.yticks(pos, df_year_four.columns[sorted_idx])
plt.show()
</code>```

Due to privacy let me say this: The feature names on the y-axis are overlapping (there are about 30 of them). I was looking into the documentation of matplotlib in order to get an understanding of how to do this by myself, unfortunately I couldn't find anything helpful. Seems like training and testing models is easier than understanding matplotlib and creating plots :D

Thank you so much for helping out and taking the time, I appreciate it.

答:
I see your solution, and I want to just add this link here to explain why: How to change spacing between ticks in matplotlib?

The spacing between ticklabels is exclusively determined by the space between ticks on the axes. Therefore the only way to obtain more space between given ticklabels is to make the axes larger.

The question I linked shows that by making the graph large enough, your axis labels would naturally be spaced better.

Body:
I'am kind of in a rush to finish this for tomorrows presentation towards the project owner. We are a small group of economic students in germany trying to figure out machine learning with python. We set up a Random Forest Classifier and are desperate to show the estimators important features in a neat plot. By applying google search we came up with the following solution that kind of does the trick, but leaves us unsatisfied due to the overlapping of the labels on the y-axis. The code we used looks like this:

feature_importances = clf.best_estimator_.feature_importances_
feature_importances = 100 * (feature_importances / feature_importances.max())
sorted_idx = np.argsort(feature_importances)

pos = np.arange(sorted_idx.shape[0])
plt.barh(pos, feature_importances[sorted_idx], align='center', height=0.8)
plt.yticks(pos, df_year_four.columns[sorted_idx])
plt.show()

Due to privacy let me say this: The feature names on the y-axis are overlapping (there are about 30 of them). I was looking into the documentation of matplotlib in order to get an understanding of how to do this by myself, unfortunately I couldn't find anything helpful. Seems like training and testing models is easier than understanding matplotlib and creating plots :D

Thank you so much for helping out and taking the time, I appreciate it.


问:
cannot import MatDialogModule in app.module
I am a beginner in angular,
I am using angular material dialog box. first I added material to my project and use it from @angular/material.

When I add ( import { MatDialogModule } from '@angular/material/dialog'; )) in app.module.ts, get below error on compiling project

```<code> ERROR in node_modules/@angular/cdk/coercion/array.d.ts(10,60): error
 TS1005: ',' expected.
 node_modules/@angular/cdk/coercion/array.d.ts(10,61): error TS1005:
 ',' expected. node_modules/@angular/cdk/coercion/array.d.ts(10,75):
 error TS1144: '{' or ';' expected.
 node_modules/@angular/cdk/coercion/array.d.ts(10,77): error TS1011: An
 element access expression should take an argument.
</code>```

why?

this is my package.json:

```<code>      {
      "name": "sales-maret",
      "version": "0.0.0",
      "scripts": {
        "ng": "ng",
        "start": "ng serve",
        "build": "ng build",
        "test": "ng test",
        "lint": "ng lint",
        "e2e": "ng e2e"
      },
      "private": true,
      "dependencies": {
        "@angular/animations": "^7.2.16",
        "@angular/cdk": "^9.2.0",
        "@angular/common": "~7.2.0",
        "@angular/compiler": "~7.2.0",
        "@angular/core": "~7.2.0",
        "@angular/forms": "~7.2.0",
        "@angular/material": "^9.2.0",
        "@angular/platform-browser": "~7.2.0",
        "@angular/platform-browser-dynamic": "~7.2.0",
        "@angular/router": "~7.2.0",
        "core-js": "^2.5.4",
        "hammerjs": "^2.0.8",
        "material-icons": "^0.3.1",
        "rxjs": "~6.3.3",
        "tslib": "^1.9.0",
        "zone.js": "~0.8.26"
      },
      "devDependencies": {
        "@angular-devkit/build-angular": "~0.13.0",
        "@angular/cli": "~7.3.6",
        "@angular/compiler-cli": "~7.2.0",
        "@angular/language-service": "~7.2.0",
        "@types/node": "~8.9.4",
        "@types/jasmine": "~2.8.8",
        "@types/jasminewd2": "~2.0.3",
        "codelyzer": "~4.5.0",
        "jasmine-core": "~2.99.1",
        "jasmine-spec-reporter": "~4.2.1",
        "karma": "~4.0.0",
        "karma-chrome-launcher": "~2.2.0",
        "karma-coverage-istanbul-reporter": "~2.0.1",
        "karma-jasmine": "~1.1.2",
        "karma-jasmine-html-reporter": "^0.2.2",
        "protractor": "~5.4.0",
        "ts-node": "~7.0.0",
        "tslint": "~5.11.0",
        "typescript": "~3.2.2"
      }
    }
</code>```

Body:
I am a beginner in angular,
I am using angular material dialog box. first I added material to my project and use it from @angular/material.

When I add ( import { MatDialogModule } from '@angular/material/dialog'; )) in app.module.ts, get below error on compiling project

 ERROR in node_modules/@angular/cdk/coercion/array.d.ts(10,60): error
 TS1005: ',' expected.
 node_modules/@angular/cdk/coercion/array.d.ts(10,61): error TS1005:
 ',' expected. node_modules/@angular/cdk/coercion/array.d.ts(10,75):
 error TS1144: '{' or ';' expected.
 node_modules/@angular/cdk/coercion/array.d.ts(10,77): error TS1011: An
 element access expression should take an argument.

why?

this is my package.json:

      {
      "name": "sales-maret",
      "version": "0.0.0",
      "scripts": {
        "ng": "ng",
        "start": "ng serve",
        "build": "ng build",
        "test": "ng test",
        "lint": "ng lint",
        "e2e": "ng e2e"
      },
      "private": true,
      "dependencies": {
        "@angular/animations": "^7.2.16",
        "@angular/cdk": "^9.2.0",
        "@angular/common": "~7.2.0",
        "@angular/compiler": "~7.2.0",
        "@angular/core": "~7.2.0",
        "@angular/forms": "~7.2.0",
        "@angular/material": "^9.2.0",
        "@angular/platform-browser": "~7.2.0",
        "@angular/platform-browser-dynamic": "~7.2.0",
        "@angular/router": "~7.2.0",
        "core-js": "^2.5.4",
        "hammerjs": "^2.0.8",
        "material-icons": "^0.3.1",
        "rxjs": "~6.3.3",
        "tslib": "^1.9.0",
        "zone.js": "~0.8.26"
      },
      "devDependencies": {
        "@angular-devkit/build-angular": "~0.13.0",
        "@angular/cli": "~7.3.6",
        "@angular/compiler-cli": "~7.2.0",
        "@angular/language-service": "~7.2.0",
        "@types/node": "~8.9.4",
        "@types/jasmine": "~2.8.8",
        "@types/jasminewd2": "~2.0.3",
        "codelyzer": "~4.5.0",
        "jasmine-core": "~2.99.1",
        "jasmine-spec-reporter": "~4.2.1",
        "karma": "~4.0.0",
        "karma-chrome-launcher": "~2.2.0",
        "karma-coverage-istanbul-reporter": "~2.0.1",
        "karma-jasmine": "~1.1.2",
        "karma-jasmine-html-reporter": "^0.2.2",
        "protractor": "~5.4.0",
        "ts-node": "~7.0.0",
        "tslint": "~5.11.0",
        "typescript": "~3.2.2"
      }
    }

Body:
Change

"@angular/cdk": "^9.2.0",
"@angular/material": "^9.2.0",

to

"@angular/cdk": "^7.2.0",
"@angular/material": "^7.2.0",


问:
Convert multiple columned dataframe to 3D matrix in R
I have a dataframe similar to the one below:

```<code>trial Card1_colour Card1_number Card1_shape Card2_colour Card2_number Card2_shape  ......
1        1                1           0           0           1            1
2        0                0           0           1           1            1
3        1                0           0           0           0            0
4        0                0           1           0           0            1
5        1                1           1           1           0            1
.
.
.
.

</code>```

Except my actual dataframe has 12 'Card' variables, Card1_colour : Card4_shape.

```<code>#Code for generating example data

data<-matrix(rbinom(20*12, 1, .5), ncol=12)
trial<-seq(from = 1, to = 20)

data<-cbind(trial,data)
data<-as.data.frame(data)

colnames(data)[2] <- "Card1_colour"
colnames(data)[3] <- "Card1_number"
colnames(data)[4] <- "Card1_shape"
colnames(data)[5] <- "Card2_colour"
colnames(data)[6] <- "Card2_number"
colnames(data)[7] <- "Card2_shape"
colnames(data)[8] <- "Card3_colour"
colnames(data)[9] <- "Card3_number"
colnames(data)[10] <- "Card3_shape"
colnames(data)[11] <- "Card4_colour"
colnames(data)[12] <- "Card4_number"
colnames(data)[13] <- "Card4_shape"

</code>```

I want to reshape my data into an n(trial) x 4 x 3 matrix that would look something like this:

```<code>trial Card Colour Number Shape
1      1     1      1      0
1      2     0      1      1
1      3     0      1      0
1      4     1      1      1
2      1     1      0      0
2      2     1      1      0
2      3     0      1      1
2      4     1      1      0

</code>```

In other words, card 1 - card 4 per trial would become row variables, while colour, shape, and number remain column variables.

Any help is appreciated! Thanks.

答:
We can use names_sep with names_prefix

```<code>library(tidyr)
pivot_longer(data, cols = -trial, names_to = c('Card', '.value'),
        names_prefix='Card', names_sep='_')
# A tibble: 80 x 5
#   trial Card  colour number shape
#   <int> <chr>  <int>  <int> <int>
# 1     1 1          0      0     1
# 2     1 2          0      0     0
# 3     1 3          1      0     1
# 4     1 4          1      0     1
# 5     2 1          0      1     1
# 6     2 2          0      0     1
# 7     2 3          0      1     0
# 8     2 4          1      0     1
# 9     3 1          1      1     1
#10     3 2          1      1     0
# … with 70 more rows
</code>```

Body:
I have a dataframe similar to the one below:

trial Card1_colour Card1_number Card1_shape Card2_colour Card2_number Card2_shape  ......
1        1                1           0           0           1            1
2        0                0           0           1           1            1
3        1                0           0           0           0            0
4        0                0           1           0           0            1
5        1                1           1           1           0            1
.
.
.
.

Except my actual dataframe has 12 'Card' variables, Card1_colour : Card4_shape.

#Code for generating example data

data<-matrix(rbinom(20*12, 1, .5), ncol=12)
trial<-seq(from = 1, to = 20)

data<-cbind(trial,data)
data<-as.data.frame(data)

colnames(data)[2] <- "Card1_colour"
colnames(data)[3] <- "Card1_number"
colnames(data)[4] <- "Card1_shape"
colnames(data)[5] <- "Card2_colour"
colnames(data)[6] <- "Card2_number"
colnames(data)[7] <- "Card2_shape"
colnames(data)[8] <- "Card3_colour"
colnames(data)[9] <- "Card3_number"
colnames(data)[10] <- "Card3_shape"
colnames(data)[11] <- "Card4_colour"
colnames(data)[12] <- "Card4_number"
colnames(data)[13] <- "Card4_shape"

I want to reshape my data into an n(trial) x 4 x 3 matrix that would look something like this:

trial Card Colour Number Shape
1      1     1      1      0
1      2     0      1      1
1      3     0      1      0
1      4     1      1      1
2      1     1      0      0
2      2     1      1      0
2      3     0      1      1
2      4     1      1      0

In other words, card 1 - card 4 per trial would become row variables, while colour, shape, and number remain column variables.

Any help is appreciated! Thanks.

Body:
We can use names_sep with names_prefix

library(tidyr)
pivot_longer(data, cols = -trial, names_to = c('Card', '.value'),
        names_prefix='Card', names_sep='_')
# A tibble: 80 x 5
#   trial Card  colour number shape
#   <int> <chr>  <int>  <int> <int>
# 1     1 1          0      0     1
# 2     1 2          0      0     0
# 3     1 3          1      0     1
# 4     1 4          1      0     1
# 5     2 1          0      1     1
# 6     2 2          0      0     1
# 7     2 3          0      1     0
# 8     2 4          1      0     1
# 9     3 1          1      1     1
#10     3 2          1      1     0
# … with 70 more rows


问:
How to save pdf file in node js with express and multer
I'm using a multer api, and I'm saving files in memory, because I need to upload images and pdf, and I need to process the images.

I can upload images, but I can't upload pdfs files.

Thanks

答:
well, this is my code... I really hope to help you.

```<code>const express = require('express');
const multer = require('multer');
const app = express();

const storage =
    multer.diskStorage({
    destination: path.join(__dirname, 'public/img/'), // destination folder
    filename: (req, file, cb) => {
        cb(null, uuid.v4() + path.extname(file.originalname));
    }
});

const upload =
multer({
storage,
dest: path.join(__dirname, 'public/img/'), // destination folder
limits: {fileSize: 3500000}, // size we will acept, not bigger
fileFilter: (req, file, cb) => {
    const filetypes = /jpeg|jpg|png|gif|pdf/; // filetypes you will accept
    const mimetype = filetypes.test(file.mimetype); // verify file is == filetypes you will accept
    const extname = filetypes.test(path.extname(file.originalname)); // extract the file extension
    // if mimetype && extname are true, then no error
    if(mimetype && extname){
        return cb(null, true);
    }
    // if mimetype or extname false, give an error of compatibilty
    return cb("The uploaded file, isn't compatible :( we're sorry");
}
}).single('image'); // This is the field where is the input type="file", we only accept 1 image
app.use(upload);
</code>```

and the view will looks like this

```<code>app.post('/add', async (req, res) => {
const { originalname, mimetype, destination, filename, path, size} = req.file;
const newImage = {
    originalname,
    mimetype,
    destination,
    filename,
    path,
    size
};
await pool.query('Insert Into imagen set ?', [newImage]);
res.send('image uploaded');
});
</code>```

Body:
well, this is my code... I really hope to help you.

const express = require('express');
const multer = require('multer');
const app = express();

const storage =
    multer.diskStorage({
    destination: path.join(__dirname, 'public/img/'), // destination folder
    filename: (req, file, cb) => {
        cb(null, uuid.v4() + path.extname(file.originalname));
    }
});

const upload =
multer({
storage,
dest: path.join(__dirname, 'public/img/'), // destination folder
limits: {fileSize: 3500000}, // size we will acept, not bigger
fileFilter: (req, file, cb) => {
    const filetypes = /jpeg|jpg|png|gif|pdf/; // filetypes you will accept
    const mimetype = filetypes.test(file.mimetype); // verify file is == filetypes you will accept
    const extname = filetypes.test(path.extname(file.originalname)); // extract the file extension
    // if mimetype && extname are true, then no error
    if(mimetype && extname){
        return cb(null, true);
    }
    // if mimetype or extname false, give an error of compatibilty
    return cb("The uploaded file, isn't compatible :( we're sorry");
}
}).single('image'); // This is the field where is the input type="file", we only accept 1 image
app.use(upload);

and the view will looks like this

app.post('/add', async (req, res) => {
const { originalname, mimetype, destination, filename, path, size} = req.file;
const newImage = {
    originalname,
    mimetype,
    destination,
    filename,
    path,
    size
};
await pool.query('Insert Into imagen set ?', [newImage]);
res.send('image uploaded');
});


问:
facebook facepile tip
I need fast&easy tip.

I'm tempted to 'socialize my website' a little,so I gave a look to facebook facepile social plugin definition:

```<code>"[..] If the user does not have friends who have liked your page or have connected to your site, no faces will be shown.[..]"
</code>```

I was wondering if "connected" meant just "browsing my website"?

Thanks

Luca

答: No connected means that they accepted to share their facebook data with you through your application by clicking on the "allow" button on the window promted by the FB-app</p>

Title: facebook facepile tip

Body:
I need fast&easy tip.

I'm tempted to 'socialize my website' a little,so I gave a look to facebook facepile social plugin definition:

"[..] If the user does not have friends who have liked your page or have connected to your site, no faces will be shown.[..]"

I was wondering if "connected" meant just "browsing my website"?

Thanks

Luca


问:
Python Web Scraping: Output to csv
I'm doing some progress with web scraping however I still need some help to perform some operations:

```<code>import requests
import pandas as pd
from bs4 import BeautifulSoup

url = 'http://fcf.cat/equip/1920/1i/sant-ildefons-ue-b'

# soup = BeautifulSoup(requests.get(converturl).content, 'html.parser')

soup = BeautifulSoup(requests.get(url).content, 'html.parser')

out = []

for tr in soup.select('.col-md-4 tbody tr'):
</code>```

On the class col-md-4 I know there are 3 tables I want to generate a csv which as an output has three values: first name, last name, and for the last value I want the header name of the table.

first name, last name, header table

Any help would be appreciated.

答:
You need to first iterate through each table you want to scrape, then for each table, get its header and rows of data.  For each row of data, you want to parse out the First Name and Last Name (along with the header of the table).

Here's a verbose working example:

```<code>import requests
import pandas as pd
from bs4 import BeautifulSoup

url = 'http://fcf.cat/equip/1920/1i/sant-ildefons-ue-b'

soup = BeautifulSoup(requests.get(url).content, 'html.parser')

out = []

# Iterate through each of the three tables
for table in soup.select(".col-md-4 table"):

    # Grab the header and rows from the table
    header = table.select("thead th")[0].text.strip()
    rows = [s.text.strip() for s in table.select("tbody tr")]

    t = []  # This list will contain the rows of data for this table

    # Iterate through rows in this table
    for row in rows:

        # Split by comma (last_name, first_name)
        split = row.split(",")

        last_name = split[0].strip()
        first_name = split[1].strip()

        # Create the row of data
        t.append([first_name, last_name, header])

    # Convert list of rows to a DataFrame
    df = pd.DataFrame(t, columns=["first_name", "last_name", "table_name"])

    # Append to list of DataFrames
    out.append(df)

# Write to CSVs...
out[0].to_csv("first_table.csv", index=None)  # etc...
</code>```

Whenever you're web scraping, I highly recommend using strip() on all of the text you parse to make sure you don't have superfluous spaces in your data.

I hope this helps!

Title: Python Web Scraping: Output to csv

Body:
I'm doing some progress with web scraping however I still need some help to perform some operations:

import requests
import pandas as pd
from bs4 import BeautifulSoup

url = 'http://fcf.cat/equip/1920/1i/sant-ildefons-ue-b'

# soup = BeautifulSoup(requests.get(converturl).content, 'html.parser')

soup = BeautifulSoup(requests.get(url).content, 'html.parser')

out = []

for tr in soup.select('.col-md-4 tbody tr'):

On the class col-md-4 I know there are 3 tables I want to generate a csv which as an output has three values: first name, last name, and for the last value I want the header name of the table.

first name, last name, header table

Any help would be appreciated.

Body:
You need to first iterate through each table you want to scrape, then for each table, get its header and rows of data.  For each row of data, you want to parse out the First Name and Last Name (along with the header of the table).

Here's a verbose working example:

import requests
import pandas as pd
from bs4 import BeautifulSoup

url = 'http://fcf.cat/equip/1920/1i/sant-ildefons-ue-b'

soup = BeautifulSoup(requests.get(url).content, 'html.parser')

out = []

# Iterate through each of the three tables
for table in soup.select(".col-md-4 table"):

    # Grab the header and rows from the table
    header = table.select("thead th")[0].text.strip()
    rows = [s.text.strip() for s in table.select("tbody tr")]

    t = []  # This list will contain the rows of data for this table

    # Iterate through rows in this table
    for row in rows:

        # Split by comma (last_name, first_name)
        split = row.split(",")

        last_name = split[0].strip()
        first_name = split[1].strip()

        # Create the row of data
        t.append([first_name, last_name, header])

    # Convert list of rows to a DataFrame
    df = pd.DataFrame(t, columns=["first_name", "last_name", "table_name"])

    # Append to list of DataFrames
    out.append(df)

# Write to CSVs...
out[0].to_csv("first_table.csv", index=None)  # etc...

Whenever you're web scraping, I highly recommend using strip() on all of the text you parse to make sure you don't have superfluous spaces in your data.

I hope this helps!


问:
Database enumeration fails on my Azure hosted SQL Server
I can connect to my database server (Azure hosted) with SQL Server Management Studio, however I am unable to enumerate its databases.

On the Azure portal, I am seeing a similar issue:

The fact is, these databases are up and running. My application continues to function. I am also able to issues queries via SSMS Query window. The main problem here is the inability to enumerate databases on the server. If you have any idea how I might solve this, thank you very much for any advice which you can provide!

答:
This was an issue with the Azure platform. Here is what we received from our hosting provider in response to our inquiry:

SQL and Open-Source Database Service Management Issues - East US - Mitigated (Tracking ID 8K76-LZ8)

Summary of impact: Between approximately 13:30 and 16:30 UTC on 19 May 2020, a subset of customers in East US may have intermittently experienced timeouts and latency issues when processing service management operations - such as create, update, delete - for SQL resources hosted in this region, including Azure SQL Database and open-source databases such as Azure Database for PostgreSQL, Azure Database for MySQL, and Azure Database for MariaDB. Some customers may have also encountered issues or experienced latency when loading database management tools or expanding database resources in SQL Server Management Studio (SSMS). Retries may have been successful.

Preliminary root cause: After an initial investigation, engineers identified that an increased volume of requests had consumed a large number of available private endpoint connections for the SQL control plane in East US, thus leading to failures for subsequent control plane operations in the region.

Mitigation: Once the preliminary root cause was identified, engineering teams terminated connections from the source of the increased load.

Next steps: We apologize for the impact to affected customers. Engineers will continue to investigate the underlying cause and take steps to prevent future occurrences, which includes:

•   Further investigating and understanding the source of increased workload on the SQL platform

•   Increasing the resiliency of the SQL platform to better account for this type of work volume

[End of Report]

Anyway, I am posting this so that anyone who encounters this issue in the future should know - it may not be your issue. It may be an issue with the Azure hosting platform in which case you will just need to wait until engineers resolve the issue at their end.


问:
Powershell while loop cannot be broken
I have a while loop in powershell that checks for input

```<code>:checker while($choice1 = read-host "Do you want to continue? [Y/N/C]"){
    switch ($choice1){
        "N"{Echo Ok; $temporary = "Exit"; break :checker}
        "Y"{Echo Ok; $temporary = "Continue"; break :checker}
        "C"{Echo Ok; $temporary = "Cancel"; break :checker}
        default{"Invalid input"}
    }
}
</code>```

However, no matter the input, the while loop never gets broken. Is there an issue with my code, or is there a different way to do this that will ensure the correct things to happen?

答:
here is a variant on the idea. it works by setting $Choice to the user input ... and, if the input is not valid, setting $Choice to a blank string so that the while loop will continue.

i removed the call to ok since you didn't provide that code. [grin]

the code ...

```<code>$Choice = ''
while ([string]::IsNullOrEmpty($Choice))
    {
    $Choice = Read-Host 'Do you want to continue? [Y/N/C] '
    switch ($Choice)
        {
        "N"{$temporary = "Exit"; break}
        "Y"{$temporary = "Continue"; break}
        "C"{$temporary = "Cancel"; break}
        default{$Choice = ''; "Invalid input"}
        }
    }

$Choice
$Temporary
</code>```

output ...

```<code>Do you want to continue? [Y/N/C] : t
Invalid input
Do you want to continue? [Y/N/C] : y
y
Continue
</code>```

Title: Powershell while loop cannot be broken

Body:
I have a while loop in powershell that checks for input

:checker while($choice1 = read-host "Do you want to continue? [Y/N/C]"){
    switch ($choice1){
        "N"{Echo Ok; $temporary = "Exit"; break :checker}
        "Y"{Echo Ok; $temporary = "Continue"; break :checker}
        "C"{Echo Ok; $temporary = "Cancel"; break :checker}
        default{"Invalid input"}
    }
}

However, no matter the input, the while loop never gets broken. Is there an issue with my code, or is there a different way to do this that will ensure the correct things to happen?

Body:
here is a variant on the idea. it works by setting $Choice to the user input ... and, if the input is not valid, setting $Choice to a blank string so that the while loop will continue.

i removed the call to ok since you didn't provide that code. [grin]

the code ...

$Choice = ''
while ([string]::IsNullOrEmpty($Choice))
    {
    $Choice = Read-Host 'Do you want to continue? [Y/N/C] '
    switch ($Choice)
        {
        "N"{$temporary = "Exit"; break}
        "Y"{$temporary = "Continue"; break}
        "C"{$temporary = "Cancel"; break}
        default{$Choice = ''; "Invalid input"}
        }
    }

$Choice
$Temporary

output ...

Do you want to continue? [Y/N/C] : t
Invalid input
Do you want to continue? [Y/N/C] : y
y
Continue


问:
What models and fields do I need to handle subscriptions such as Apple's Autorenewable Subscriptions?
I want to build an autorenewable subscription service, with an introductory trial period. There doesn't seem to be much written documentation on what models and fields I need to best model (and futureproof) my subscriptions. I'm starting with Apple's App store right now, but I do have a web interface and want to go to the Play Store at some point.

From this video: https://developer.apple.com/videos/play/wwdc2018/705/ it seems like the minimum I need is something like a Subscription model with fields userId, productId, originalTransactionId, latestExpiresDate, consumedProductDiscounts, latestReceiptData.

Is there anything else I need?

Will I be able to properly retrieve other subscription information in the future and augment my table (i.e. the billingRetry information as suggested in the video for grace periods; my understanding is by sending the saved receipt data I can get the JSON blob again and retrieve additional fields if I need to)?

Is this extensible to co-exist with web and Play Store subscriptions?

答:
These is the models we use to handle the subscription. maybe it helps you.</p>

```<code>struct BillingTransaction : Codable {
    var expires_date: String
    var original_purchase_date: String
    var is_in_intro_offer_period: Bool
    var product_id: String
    var original_transaction_id: Int
    var transaction_id: Int
}

struct BillingReceipt : Codable {
    var app_item_id: String
    var application_version: String
    var bundle_id: String
    var in_app: [BillingTransaction]
}

struct BillingRenewalInfo : Codable {
    var product_id: String
    var auto_renew_product_id: String
    var auto_renew_status: Int
    var is_in_billing_retry_period: Int
    var original_transaction_id: Int
}

</code>```

Body:
These is the models we use to handle the subscription. maybe it helps you.

struct BillingTransaction : Codable {
    var expires_date: String
    var original_purchase_date: String
    var is_in_intro_offer_period: Bool
    var product_id: String
    var original_transaction_id: Int
    var transaction_id: Int
}

struct BillingReceipt : Codable {
    var app_item_id: String
    var application_version: String
    var bundle_id: String
    var in_app: [BillingTransaction]
}

struct BillingRenewalInfo : Codable {
    var product_id: String
    var auto_renew_product_id: String
    var auto_renew_status: Int
    var is_in_billing_retry_period: Int
    var original_transaction_id: Int
}


问:
Aggregate function two match with lookup mongodb
```<code>db.setting.aggregate([
  {
    $match: {
      status: true,
      deleted_at: 0,
      _id: {
        $in: [
          ObjectId("5c4ee7eea4affa32face874b"),
          ObjectId("5ebf891245aa27c290672325")
        ]
      }
    }
  },
  {
    $lookup: {
      from: "site",
      localField: "_id",
      foreignField: "admin_id",
      as: "data"
    }
  },
  {
    $project: {
      name: 1,
      status: 1,
      numberOfRecord: {
        $size: "$data"
      }
    }
  },
  {
    $sort: {
      numberOfRecord: 1
    }
  }
])
</code>```

I would like to fetch record and number of record which are greater then equal to 2020-01-01 tried to add below code but doesn't get success.

How can I make this correct please guide thanks in advance. Here is playground https://mongoplayground.net/p/GU8WbTVqo2I

```<code>{
    $match: {
      "data.createdAt": {
        $gte: new Date("2020-01-01")
      }
    }
  },
</code>```

Output should be

```<code>[
  {
    "_id": ObjectId("5ebf891245aa27c290672325"),
    "name": "Menz",
    "numberOfRecord": 0,
    "status": true
  },
  {
    "_id": ObjectId("5c4ee7eea4affa32face874b"),
    "name": "Dave",
    "numberOfRecord": 1, // instead 2 bcoz this is only gte "2020-01-01"
    "status": true
  }
]
</code>```

答:
You can use $unwind to split up the array, but using $match will completely eliminate documents that don't have any matching documents, so you would need to used $group with a conditional count, perhaps:

```<code>db.setting.aggregate([
  {$match: {
      status: true,
      deleted_at: 0,
      _id: {
        $in: [
          ObjectId("5c4ee7eea4affa32face874b"),
          ObjectId("5ebf891245aa27c290672325")
        ]
      }
  }},
  {$lookup: {
      from: "site",
      localField: "_id",
      foreignField: "admin_id",
      as: "data"
  }},
  {$unwind: {
        path: "$data",
        preserveNullAndEmptyArrays: true
  }},
  {$group: {
      _id: "$_id",
      name: {$first: "$name"},
      status: {$first: "$status"},
      numberOfRecord: {
        $sum:{
           $cond:{
              if:{
                  $gte:[
                        "$data.createdAt",
                        new Date("2020-01-01")
                       ]
              },
              then: 1,
              else: 0
           }
        }
     }
  }},
  {$sort: { numberOfRecord: 1 }}
])
</code>```

Playground

Body:
db.setting.aggregate([
  {
    $match: {
      status: true,
      deleted_at: 0,
      _id: {
        $in: [
          ObjectId("5c4ee7eea4affa32face874b"),
          ObjectId("5ebf891245aa27c290672325")
        ]
      }
    }
  },
  {
    $lookup: {
      from: "site",
      localField: "_id",
      foreignField: "admin_id",
      as: "data"
    }
  },
  {
    $project: {
      name: 1,
      status: 1,
      numberOfRecord: {
        $size: "$data"
      }
    }
  },
  {
    $sort: {
      numberOfRecord: 1
    }
  }
])

I would like to fetch record and number of record which are greater then equal to 2020-01-01 tried to add below code but doesn't get success.

How can I make this correct please guide thanks in advance. Here is playground https://mongoplayground.net/p/GU8WbTVqo2I

{
    $match: {
      "data.createdAt": {
        $gte: new Date("2020-01-01")
      }
    }
  },

Output should be

[
  {
    "_id": ObjectId("5ebf891245aa27c290672325"),
    "name": "Menz",
    "numberOfRecord": 0,
    "status": true
  },
  {
    "_id": ObjectId("5c4ee7eea4affa32face874b"),
    "name": "Dave",
    "numberOfRecord": 1, // instead 2 bcoz this is only gte "2020-01-01"
    "status": true
  }
]

Body:
You can use $unwind to split up the array, but using $match will completely eliminate documents that don't have any matching documents, so you would need to used $group with a conditional count, perhaps:

db.setting.aggregate([
  {$match: {
      status: true,
      deleted_at: 0,
      _id: {
        $in: [
          ObjectId("5c4ee7eea4affa32face874b"),
          ObjectId("5ebf891245aa27c290672325")
        ]
      }
  }},
  {$lookup: {
      from: "site",
      localField: "_id",
      foreignField: "admin_id",
      as: "data"
  }},
  {$unwind: {
        path: "$data",
        preserveNullAndEmptyArrays: true
  }},
  {$group: {
      _id: "$_id",
      name: {$first: "$name"},
      status: {$first: "$status"},
      numberOfRecord: {
        $sum:{
           $cond:{
              if:{
                  $gte:[
                        "$data.createdAt",
                        new Date("2020-01-01")
                       ]
              },
              then: 1,
              else: 0
           }
        }
     }
  }},
  {$sort: { numberOfRecord: 1 }}
])

Playground


问:
Dependency missing when running AzureML Estimator in docker environment

Scenario description

I'm trying to submit a training script to AzureML (want to use AmlCompute, but I'm starting/testing locally first, for debugging purposes).

The train.py script I have uses a custom package (arcus.ml) and I believe I have specified the right settings and dependencies, but still I get the error:

User program failed with ModuleNotFoundError: No module named 'arcus.ml'

Code and reproduction

This the python code I have:

name='test'
script_params = {
    '--test-par': 0.2
}

est = Estimator(source_directory='./' + name,
                   script_params=script_params,
                   compute_target='local',
                   entry_script='train.py',
                   pip_requirements_file='requirements.txt',
                   conda_packages=['scikit-learn','tensorflow', 'keras'])

run = exp.submit(est)
print(run.get_portal_url())
```

<p>This is the (fully simplified) train.py script in the <code>test</code>directory:</p>

<pre class="lang-py prettyprint-override"><code>from arcus.ml import dataframes as adf
from azureml.core import Workspace, Dataset, Datastore, Experiment, Run

# get hold of the current run
run = Run.get_context()
ws = run.get_environment()

print('training finished')
</code>```

And this is my requirements.txt file

```<code>arcus-azureml
arcus-ml
numpy
pandas
azureml-core
tqdm
joblib
scikit-learn
matplotlib
tensorflow
keras
</code>```

Logs

In the logs file of the run, I can see this section, sot it seems the external module is being installed anyhow.

```<code>Collecting arcus-azureml
  Downloading arcus_azureml-1.0.3-py3-none-any.whl (3.1 kB)
Collecting arcus-ml
  Downloading arcus_ml-1.0.6-py3-none-any.whl (2.1 kB)
</code>```

答:
I think this error isn't necessarily about Azure ML. I think the error has to do w/ the difference b/w using a hyphen and a period in your package name. But I'm a python packaging newb.
In a new conda environment on my laptop, I ran the following

```<code>> conda create -n arcus python=3.6 -y
> conda activate arcus
> pip install arcus-ml
> python
>>> from arcus.ml import dataframes as adf
ModuleNotFoundError: No module named 'arcus'
</code>```

When I look in the env's site packages folder, I didn't see the arcus/ml folder structure I was expecting. There's no arcus code there at all, only the .dist-info file

~/opt/anaconda3/envs/arcus/lib/python3.6/site-packages

Body:
Scenario description

I'm trying to submit a training script to AzureML (want to use AmlCompute, but I'm starting/testing locally first, for debugging purposes).

The train.py script I have uses a custom package (arcus.ml) and I believe I have specified the right settings and dependencies, but still I get the error:

User program failed with ModuleNotFoundError: No module named 'arcus.ml'

Code and reproduction

This the python code I have:

name='test'
script_params = {
    '--test-par': 0.2
}

est = Estimator(source_directory='./' + name,
                   script_params=script_params,
                   compute_target='local',
                   entry_script='train.py',
                   pip_requirements_file='requirements.txt',
                   conda_packages=['scikit-learn','tensorflow', 'keras'])

run = exp.submit(est)
print(run.get_portal_url())

This is the (fully simplified) train.py script in the testdirectory:

from arcus.ml import dataframes as adf
from azureml.core import Workspace, Dataset, Datastore, Experiment, Run

# get hold of the current run
run = Run.get_context()
ws = run.get_environment()

print('training finished')

And this is my requirements.txt file

arcus-azureml
arcus-ml
numpy
pandas
azureml-core
tqdm
joblib
scikit-learn
matplotlib
tensorflow
keras

Logs

In the logs file of the run, I can see this section, sot it seems the external module is being installed anyhow.

Collecting arcus-azureml
  Downloading arcus_azureml-1.0.3-py3-none-any.whl (3.1 kB)
Collecting arcus-ml
  Downloading arcus_ml-1.0.6-py3-none-any.whl (2.1 kB)

Body:
I think this error isn't necessarily about Azure ML. I think the error has to do w/ the difference b/w using a hyphen and a period in your package name. But I'm a python packaging newb.
In a new conda environment on my laptop, I ran the following

> conda create -n arcus python=3.6 -y
> conda activate arcus
> pip install arcus-ml
> python
>>> from arcus.ml import dataframes as adf
ModuleNotFoundError: No module named 'arcus'

When I look in the env's site packages folder, I didn't see the arcus/ml folder structure I was expecting. There's no arcus code there at all, only the .dist-info file

~/opt/anaconda3/envs/arcus/lib/python3.6/site-packages


问:
is there any way to make Silent installation to my C# program - on Visual-Studio 2008
is there any way to make Silent installation to my C# program -  on Visual-Studio 2008

(i mean that i dont want that when the user install my program he will need to press next->next...)

thanks in advance

答:
Yip, it's called clickOnce :-)

http://msdn.microsoft.com/en-us/library/wh45kb66.aspx

In solution explorer right click your Windows Presentation Foundation, Windows Forms, or console application, click publish and follow the steps, it's as easy as that.


问:
innerhtml returns undefined but the element exists
I'm trying to get the innerHTML of an element but it returns undefined.

```<code>let body = e.target.previousElementSibling.innerHTML;
console.log(body);
</code>```

//returns undefined

However, when I do this:

```<code>let body = e.target.previousElementSibling;
</code>```

and console log it,

it returns me the element, which is:

```<code><p class="card-text"> is the greatest </p>
</code>```

so why is the innerHTML returning undefined?

Here's the HTML:

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Microposts</title>

  <body>
<div id="posts">

    <div class="card-body 4" data-id="4">
     <h4 class="card-title"> code </h4>
     <p class="card-text"> why is this  </p>
     <i class="fa fa-pencil 4"> </i>
     <i class="fa fa-remove 4 " style="margin-left:30px"> </i>
     </div>

     <div class="card-body 5" data-id="5">
     <h4 class="card-title"> messi </h4>
     <p class="card-text"> is the greatest </p>
     <i class="fa fa-pencil 5"> </i>
     <i class="fa fa-remove 5 " style="margin-left:30px"> </i>
     </div>

     <div class="card-body 6" data-id="6">
     <h4 class="card-title"> Why is the compiler showing following code as incorrect syntax? </h4>
     <p class="card-text"> I dont know </p>
 <i class="fa fa-pencil 5"> </i>
     <i class="fa fa-remove 5 " style="margin-left:30px"> </i>
     </div>
 </div>
</body>
</html>
</code>```

Here's the JS Code

```<code>document.querySelector("#posts").addEventListener("click", postUpdate);

function postUpdate(e) {
  if (e.target.classList.contains("fa-pencil")) {
    let id = e.target.parentElement.dataset.id;
    let element = e.target.parentElement;
    let body = e.target.previousElementSibling.innerHTML;
    let title = body.previousElementSibling.innerHTML;

    console.log(body);
  }
}
</code>```

答:
Instead of:

```<code>let body = e.target.previousElementSibling.innerHTML;
let title = body.previousElementSibling.innerHTML;
</code>```

Do:

```<code>let body = e.target.previousElementSibling.innerHTML;
let title =e.target.previousElementSibling.previousElementSibling.innerHTML;
</code>```

Body:
I'm trying to get the innerHTML of an element but it returns undefined.

let body = e.target.previousElementSibling.innerHTML;
console.log(body);

//returns undefined

However, when I do this:

let body = e.target.previousElementSibling;

and console log it,

it returns me the element, which is:

 is the greatest

so why is the innerHTML returning undefined?

Here's the HTML:

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Microposts</title>

 code

 why is this

 messi

 is the greatest

 Why is the compiler showing following code as incorrect syntax?

 I dont know

Here's the JS Code

document.querySelector("#posts").addEventListener("click", postUpdate);

function postUpdate(e) {
  if (e.target.classList.contains("fa-pencil")) {
    let id = e.target.parentElement.dataset.id;
    let element = e.target.parentElement;
    let body = e.target.previousElementSibling.innerHTML;
    let title = body.previousElementSibling.innerHTML;

    console.log(body);
  }
}

Body:
Instead of:

let body = e.target.previousElementSibling.innerHTML;
let title = body.previousElementSibling.innerHTML;

Do:

let body = e.target.previousElementSibling.innerHTML;
let title =e.target.previousElementSibling.previousElementSibling.innerHTML;


问:
Resource missing error: Can't upgrade a plan on Stripe
I'd like to use Stripe Billing to implement the feature that allows the users to upgrade their plan in a subscription business. The users already are members of the free plan. It requires 2 steps.

1) Register their credit card

```<code>stripe.paymentMethods.attach(
  paymentMethodId,
  { customer: customerId }
)
</code>```

2) Upgrade a subscription plan

```<code>  stripe.subscriptions.update(subscriptionId, {
    cancel_at_period_end: false,
    proration_behavior: 'create_prorations',
    items: [{
      id: subscription.items.data[0].id,
      plan: planId,
    }]
  })
</code>```

I could have passed 1). But the issue occurs in 2).

The error:

```<code>{
  "error": {
    "code": "resource_missing",
    "doc_url": "https://stripe.com/docs/error-codes/resource-missing",
    "message": "This customer has no attached payment source or default payment method.",
    "type": "invalid_request_error"
  }
}
</code>```

How can I overcome this problem?

答:
After attaching the PaymentMethod to the Customer you need to register it as the default payment method for the subscription. There are two ways to do this.

You can register the PaymentMethod as the default payment method in the Customer's invoice settings:

https://stripe.com/docs/api/customers/update?lang=node#update_customer-invoice_settings-default_payment_method

```<code>// add this after attaching the PaymentMethod to the Customer
// (i.e, this won't work unless the PaymentMethod is attached to the Customer)

await stripe.customers.update(customerId, {
  invoice_settings: {
    default_payment_method: paymentMethodId,
  },
});
</code>```

When the customer subscribes to a paid plan they will be charged to this payment method by default.

The second option is to set the default payment method on the subscription itself:

https://stripe.com/docs/api/subscriptions/create?lang=node#create_subscription-default_payment_method

```<code>// add this after attaching the PaymentMethod to the Customer

stripe.subscriptions.update(subscriptionId, {
  default_payment_method: paymentMethodId,
  cancel_at_period_end: false,
  proration_behavior: 'create_prorations',
  items: [{
    id: subscription.items.data[0].id,
    plan: planId,
  }]
})
</code>```

The main difference between these two approaches is that if you go with the second approach (adding the default payment method to the subscription) you will have to do the same for any future subscriptions created for that customer. On the other hand, if you save the payment method as the default under the customer's invoice settings then that payment method will be used by default on any future subscriptions without you having to do anything.

Body:
I'd like to use Stripe Billing to implement the feature that allows the users to upgrade their plan in a subscription business. The users already are members of the free plan. It requires 2 steps.

1) Register their credit card

stripe.paymentMethods.attach(
  paymentMethodId,
  { customer: customerId }
)

2) Upgrade a subscription plan

  stripe.subscriptions.update(subscriptionId, {
    cancel_at_period_end: false,
    proration_behavior: 'create_prorations',
    items: [{
      id: subscription.items.data[0].id,
      plan: planId,
    }]
  })

I could have passed 1). But the issue occurs in 2).

The error:

{
  "error": {
    "code": "resource_missing",
    "doc_url": "https://stripe.com/docs/error-codes/resource-missing",
    "message": "This customer has no attached payment source or default payment method.",
    "type": "invalid_request_error"
  }
}

How can I overcome this problem?

Body:
After attaching the PaymentMethod to the Customer you need to register it as the default payment method for the subscription. There are two ways to do this.

You can register the PaymentMethod as the default payment method in the Customer's invoice settings:

https://stripe.com/docs/api/customers/update?lang=node#update_customer-invoice_settings-default_payment_method

// add this after attaching the PaymentMethod to the Customer
// (i.e, this won't work unless the PaymentMethod is attached to the Customer)

await stripe.customers.update(customerId, {
  invoice_settings: {
    default_payment_method: paymentMethodId,
  },
});

When the customer subscribes to a paid plan they will be charged to this payment method by default.

The second option is to set the default payment method on the subscription itself:

https://stripe.com/docs/api/subscriptions/create?lang=node#create_subscription-default_payment_method

// add this after attaching the PaymentMethod to the Customer

stripe.subscriptions.update(subscriptionId, {
  default_payment_method: paymentMethodId,
  cancel_at_period_end: false,
  proration_behavior: 'create_prorations',
  items: [{
    id: subscription.items.data[0].id,
    plan: planId,
  }]
})

The main difference between these two approaches is that if you go with the second approach (adding the default payment method to the subscription) you will have to do the same for any future subscriptions created for that customer. On the other hand, if you save the payment method as the default under the customer's invoice settings then that payment method will be used by default on any future subscriptions without you having to do anything.


问:
How to hide action bar before activity is created, and then show it again?
I need to implement splash screen in my honeycomb app.
I use this code in activity's onCreate to show splash:

```<code>setContentView(R.layout.splash);
getActionBar().hide();
</code>```

and this code to show main UI after sometime:

```<code>setContentView(R.layout.main);
getActionBar().show();
</code>```

But before onCreate is called and splash appears, there is small amount of time when action bar shown.

How can I make action bar invisible?

I tried to apply theme to activity without action bar:

```<code><item name="android:windowActionBar">false</item>
</code>```

but in that case getActionBar() always returns null and I found no way to show it again.

答:
this is the best way I used
Go to java file, after onCreate:

```<code>@Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Take instance of Action Bar
        // using getSupportActionBar and
        // if it is not Null
        // then call hide function
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
    }
</code>```

Body:
I need to implement splash screen in my honeycomb app.
I use this code in activity's onCreate to show splash:

setContentView(R.layout.splash);
getActionBar().hide();

and this code to show main UI after sometime:

setContentView(R.layout.main);
getActionBar().show();

But before onCreate is called and splash appears, there is small amount of time when action bar shown.

How can I make action bar invisible?

I tried to apply theme to activity without action bar:

<item name="android:windowActionBar">false</item>

but in that case getActionBar() always returns null and I found no way to show it again.

Body:
this is the best way I used
Go to java file, after onCreate:

@Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Take instance of Action Bar
        // using getSupportActionBar and
        // if it is not Null
        // then call hide function
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
    }


问:
N1ql Join and aggregate with additional values
I have a single bucket (Couchbase Community edition 6.5) consisting of the following documents:

```<code>employees {
    employeeGroupId: string,
    type: "Employee"
}
clocks {
    employeeId: string,
    areaId: string
    date: string,
    type: "Clock"
}
</code>```

Each employee has multiple corresponding clock items for each day. I need to get the following:

first clock -> clockIn

last clock -> clockOut

I have written the following query which gets the first and last clock items with execution time <100 ms:

```<code>SELECT META(employee).id AS employeeId,
       employee.employeeGroupId,
       MIN(clock.date) AS clockIn,
       MAX(clock.date) AS clockOut
FROM `bucket` employee LEFT
    JOIN `bucket` clock ON clock.employeeId = META(employee).id
    AND type = "Clock"
    AND clock.date BETWEEN "2020-06-01T00:00:00.000Z" AND "2020-06-02T00:00:00.000Z"
WHERE employee.type = "Employee"
GROUP BY employee;
</code>```

The problem is I need to get the corresponding areaId with the matching clock.

I have written the following query that does. I create two separate sub queries that sort all of the clock items for the day first ascending and then descending and select the first item.

```<code>CREATE INDEX adv_employeeId_type_date_blockId ON `bucket`(`employeeId`,`type`,`date`,`blockId`)
CREATE INDEX adv_employeeId_type_date ON `bucket`(`employeeId`,`type`,`date`)
CREATE INDEX adv_type_employeeId_date ON `bucket`(`type`,`employeeId`,`date`)

SELECT META(employee).id AS employeeId,
       employee.employeeGroupId,
       clockIn,
       clockOut
FROM `bucket` employee
    LEFT JOIN (
    SELECT obj.employeeId,
           obj.date,
           obj.areaId
    FROM `bucket` obj
    WHERE obj.employeeId = META(employee).id
        AND obj.type = "Clock"
        AND obj.date BETWEEN "2020-06-01T00:00:00.000Z" AND "2020-06-02T00:00:00.000Z"
    ORDER BY obj.date
    LIMIT 1) clockIn ON clockIn.employeeId = META(employee).id
    LEFT JOIN (
    SELECT obj.employeeId,
           obj.date,
           obj.areaId
    FROM `bucket` obj
    WHERE obj.employeeId = META(employee).id
        AND obj.type = "Clock"
        AND obj.date BETWEEN "2020-06-01T00:00:00.000Z" AND "2020-06-02T00:00:00.000Z"
    ORDER BY obj.date DESC
    LIMIT 1) clockOut ON clockOut.employeeId = META(employee).id
WHERE employee.type = "Employee"
GROUP BY employee,
         clockIn,
         clockOut;
</code>```

The problem is that the above query is inefficient with execution time >10 seconds.

In other words I need to get additional object values from the aggregate MIN() and MAX() functions.

I am sure the second query is not the most efficient method to achieve this, does anyone have any other suggestions?

答:
```<code>CREATE INDEX ix1 ON `bucket`(type, `employeeGroupId`) WHERE type = "Employee";
CREATE INDEX ix2 ON `bucket`(`employeeId`, date, areaId) WHERE type = "Clock";

SELECT META(employee).id AS employeeId,
       employee.employeeGroupId,
       minclock[0] AS clockIn,
       minclock[1] AS clockInAreaId,
       maxclock[0] AS clockOut,
       maxclock[1] AS clockOutAreaId
FROM `bucket` AS employee LEFT
    JOIN `bucket` AS clock ON clock.employeeId = META(employee).id
    AND type = "Clock"
    AND clock.date BETWEEN "2020-06-01T00:00:00.000Z" AND "2020-06-02T00:00:00.000Z"
WHERE employee.type = "Employee"
GROUP BY employee
LETTING minclock = MIN([clock.date,clock.areaId]),
        maxclock = MAX([clock.date,clock.areaId]);
</code>```

OR

```<code>SELECT META(employee).id AS employeeId,
       employee.employeeGroupId,
       MIN([clock.date, {clock.date, clock.areaId}])[1] AS clockIn,
       MAX([clock.date, {clock.date, clock.areaId}])[1] AS clockOut,
FROM `bucket` AS employee LEFT
    JOIN `bucket` AS clock ON clock.employeeId = META(employee).id
    AND type = "Clock"
    AND clock.date BETWEEN "2020-06-01T00:00:00.000Z" AND "2020-06-02T00:00:00.000Z"
WHERE employee.type = "Employee"
GROUP BY employee;
</code>```

Use MIN/MAX on Array. 0th expression is MIN/MAX expression. reset of array positions used only on ties (similar like ORDER BY multiple fields). Result will complete ARRAY expression.
Choose which positions you want project. This technique allows you project non-group by expressions.

Body:
I have a single bucket (Couchbase Community edition 6.5) consisting of the following documents:

employees {
    employeeGroupId: string,
    type: "Employee"
}
clocks {
    employeeId: string,
    areaId: string
    date: string,
    type: "Clock"
}

Each employee has multiple corresponding clock items for each day. I need to get the following:

first clock -> clockIn

last clock -> clockOut

I have written the following query which gets the first and last clock items with execution time <100 ms:

SELECT META(employee).id AS employeeId,
       employee.employeeGroupId,
       MIN(clock.date) AS clockIn,
       MAX(clock.date) AS clockOut
FROM `bucket` employee LEFT
    JOIN `bucket` clock ON clock.employeeId = META(employee).id
    AND type = "Clock"
    AND clock.date BETWEEN "2020-06-01T00:00:00.000Z" AND "2020-06-02T00:00:00.000Z"
WHERE employee.type = "Employee"
GROUP BY employee;

The problem is I need to get the corresponding areaId with the matching clock.

I have written the following query that does. I create two separate sub queries that sort all of the clock items for the day first ascending and then descending and select the first item.

CREATE INDEX adv_employeeId_type_date_blockId ON `bucket`(`employeeId`,`type`,`date`,`blockId`)
CREATE INDEX adv_employeeId_type_date ON `bucket`(`employeeId`,`type`,`date`)
CREATE INDEX adv_type_employeeId_date ON `bucket`(`type`,`employeeId`,`date`)

SELECT META(employee).id AS employeeId,
       employee.employeeGroupId,
       clockIn,
       clockOut
FROM `bucket` employee
    LEFT JOIN (
    SELECT obj.employeeId,
           obj.date,
           obj.areaId
    FROM `bucket` obj
    WHERE obj.employeeId = META(employee).id
        AND obj.type = "Clock"
        AND obj.date BETWEEN "2020-06-01T00:00:00.000Z" AND "2020-06-02T00:00:00.000Z"
    ORDER BY obj.date
    LIMIT 1) clockIn ON clockIn.employeeId = META(employee).id
    LEFT JOIN (
    SELECT obj.employeeId,
           obj.date,
           obj.areaId
    FROM `bucket` obj
    WHERE obj.employeeId = META(employee).id
        AND obj.type = "Clock"
        AND obj.date BETWEEN "2020-06-01T00:00:00.000Z" AND "2020-06-02T00:00:00.000Z"
    ORDER BY obj.date DESC
    LIMIT 1) clockOut ON clockOut.employeeId = META(employee).id
WHERE employee.type = "Employee"
GROUP BY employee,
         clockIn,
         clockOut;

The problem is that the above query is inefficient with execution time >10 seconds.

In other words I need to get additional object values from the aggregate MIN() and MAX() functions.

I am sure the second query is not the most efficient method to achieve this, does anyone have any other suggestions?

Body:
CREATE INDEX ix1 ON `bucket`(type, `employeeGroupId`) WHERE type = "Employee";
CREATE INDEX ix2 ON `bucket`(`employeeId`, date, areaId) WHERE type = "Clock";

SELECT META(employee).id AS employeeId,
       employee.employeeGroupId,
       minclock[0] AS clockIn,
       minclock[1] AS clockInAreaId,
       maxclock[0] AS clockOut,
       maxclock[1] AS clockOutAreaId
FROM `bucket` AS employee LEFT
    JOIN `bucket` AS clock ON clock.employeeId = META(employee).id
    AND type = "Clock"
    AND clock.date BETWEEN "2020-06-01T00:00:00.000Z" AND "2020-06-02T00:00:00.000Z"
WHERE employee.type = "Employee"
GROUP BY employee
LETTING minclock = MIN([clock.date,clock.areaId]),
        maxclock = MAX([clock.date,clock.areaId]);

OR

SELECT META(employee).id AS employeeId,
       employee.employeeGroupId,
       MIN([clock.date, {clock.date, clock.areaId}])[1] AS clockIn,
       MAX([clock.date, {clock.date, clock.areaId}])[1] AS clockOut,
FROM `bucket` AS employee LEFT
    JOIN `bucket` AS clock ON clock.employeeId = META(employee).id
    AND type = "Clock"
    AND clock.date BETWEEN "2020-06-01T00:00:00.000Z" AND "2020-06-02T00:00:00.000Z"
WHERE employee.type = "Employee"
GROUP BY employee;

Use MIN/MAX on Array. 0th expression is MIN/MAX expression. reset of array positions used only on ties (similar like ORDER BY multiple fields). Result will complete ARRAY expression.
Choose which positions you want project. This technique allows you project non-group by expressions.